Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/player/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import time

import requests
from requests.structures import CaseInsensitiveDict

from librespot.audio.decoders import AudioQuality, VorbisOnlyAudioQuality
from librespot.core import Session
Expand Down Expand Up @@ -66,7 +67,7 @@ def client():
"q": cmd[2:],
"type": "track"
},
headers={"Authorization": "Bearer %s" % token},
headers=CaseInsensitiveDict({"Authorization": "Bearer %s" % token}),
)
i = 1
tracks = resp.json()["tracks"]["items"]
Expand Down
5 changes: 3 additions & 2 deletions examples/server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import socket
import threading
from requests.structures import CaseInsensitiveDict

from librespot.audio.decoders import AudioQuality, VorbisOnlyAudioQuality
from librespot.core import Session
Expand All @@ -23,7 +24,7 @@ def handler(client: socket.socket, address: str):
req_method = req_http_arr[0]
req_uri = req_http_arr[1]
req_http_version = req_http_arr[2]
req_header = {}
req_header = CaseInsensitiveDict()
for header in req_header_str.split(b"\r\n"):
try:
key, value = header.split(b": ")
Expand Down Expand Up @@ -73,7 +74,7 @@ def main():
threading.Thread(target=handler, args=sock.accept()).start()


def response(client: socket.socket, uri: str, header: dict,
def response(client: socket.socket, uri: str, header: CaseInsensitiveDict,
body: bytes) -> tuple[str, list, bytes, bool]:
if re.search(r"^/audio/track/([0-9a-zA-Z]{22})$", uri) is not None:
track_id_search = re.search(
Expand Down
13 changes: 6 additions & 7 deletions librespot/audio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from librespot.metadata import EpisodeId, PlayableId, TrackId
from librespot.proto import Metadata_pb2 as Metadata, StorageResolve_pb2 as StorageResolve
from librespot.structure import AudioDecrypt, AudioQualityPicker, Closeable, FeederException, GeneralAudioStream, GeneralWritableStream, HaltListener, NoopAudioDecrypt, PacketsReceiver
from requests.structures import CaseInsensitiveDict
import concurrent.futures
import io
import logging
Expand Down Expand Up @@ -471,9 +472,9 @@ class CdnException(Exception):

class InternalResponse:
buffer: bytes
headers: typing.Dict[str, str]
headers: CaseInsensitiveDict[str, str]

def __init__(self, buffer: bytes, headers: typing.Dict[str, str]):
def __init__(self, buffer: bytes, headers: CaseInsensitiveDict[str, str]):
self.buffer = buffer
self.headers = headers

Expand Down Expand Up @@ -578,8 +579,6 @@ def __init__(self, session: Session, stream_id: StreamId,
response = self.request(range_start=0,
range_end=ChannelManager.chunk_size - 1)
content_range = response.headers.get("Content-Range")
if content_range is None:
content_range = response.headers.get("content-range")
if content_range is None:
raise IOError("Missing Content-Range header!")
split = content_range.split("/")
Expand Down Expand Up @@ -633,16 +632,16 @@ def request(self, chunk: int = None, range_start: int = None, range_end: int = N
range_end = (chunk + 1) * ChannelManager.chunk_size - 1
response = self.__session.client().get(
self.__cdn_url.url,
headers={
headers=CaseInsensitiveDict({
"Range": "bytes={}-{}".format(range_start, range_end)
},
}),
)
if response.status_code != 206:
raise IOError(response.status_code)
body = response.content
if body is None:
raise IOError("Response body is empty!")
return CdnManager.InternalResponse(body, dict(response.headers))
return CdnManager.InternalResponse(body, response.headers)

class InternalStream(AbsChunkedInputStream):
streamer: CdnManager.Streamer
Expand Down
31 changes: 16 additions & 15 deletions librespot/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from Cryptodome.Protocol.KDF import PBKDF2
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5
from requests.structures import CaseInsensitiveDict

from librespot import util
from librespot import Version
Expand Down Expand Up @@ -80,7 +81,7 @@ def build_request(
self,
method: str,
suffix: str,
headers: typing.Union[None, typing.Dict[str, str]],
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
body: typing.Union[None, bytes],
url: typing.Union[None, str],
) -> requests.PreparedRequest:
Expand All @@ -89,7 +90,7 @@ def build_request(
:param method: str:
:param suffix: str:
:param headers: typing.Union[None:
:param typing.Dict[str:
:param CaseInsensitiveDict[str:
:param str]]:
:param body: typing.Union[None:
:param bytes]:
Expand All @@ -106,7 +107,7 @@ def build_request(
request = requests.PreparedRequest()
request.method = method
request.data = body
request.headers = {}
request.headers = CaseInsensitiveDict()
if headers is not None:
request.headers = headers
request.headers["Authorization"] = "Bearer {}".format(
Expand All @@ -122,15 +123,15 @@ def send(
self,
method: str,
suffix: str,
headers: typing.Union[None, typing.Dict[str, str]],
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
body: typing.Union[None, bytes],
) -> requests.Response:
"""

:param method: str:
:param suffix: str:
:param headers: typing.Union[None:
:param typing.Dict[str:
:param CaseInsensitiveDict[str:
:param str]]:
:param body: typing.Union[None:
:param bytes]:
Expand All @@ -145,7 +146,7 @@ def sendToUrl(
method: str,
url: str,
suffix: str,
headers: typing.Union[None, typing.Dict[str, str]],
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
body: typing.Union[None, bytes],
) -> requests.Response:
"""
Expand All @@ -154,7 +155,7 @@ def sendToUrl(
:param url: str:
:param suffix: str:
:param headers: typing.Union[None:
:param typing.Dict[str:
:param CaseInsensitiveDict[str:
:param str]]:
:param body: typing.Union[None:
:param bytes]:
Expand Down Expand Up @@ -327,10 +328,10 @@ def __client_token(self):
resp = requests.post(
"https://clienttoken.spotify.com/v1/clienttoken",
proto_req.SerializeToString(),
headers={
headers=CaseInsensitiveDict({
"Accept": "application/x-protobuf",
"Content-Encoding": "",
},
}),
)

ApiClient.StatusCodeException.check_status(resp)
Expand Down Expand Up @@ -604,10 +605,10 @@ def wait_for_listener(self) -> None:
return
self.__message_listeners_lock.wait()

def __get_headers(self, obj: typing.Any) -> dict[str, str]:
def __get_headers(self, obj: typing.Any) -> CaseInsensitiveDict[str, str]:
headers = obj.get("headers")
if headers is None:
return {}
return CaseInsensitiveDict()
return headers

class ConnectionHolder(Closeable):
Expand Down Expand Up @@ -1212,12 +1213,12 @@ def mercury(self) -> MercuryClient:
raise RuntimeError("Session isn't authenticated!")
return self.__mercury_client

def on_message(self, uri: str, headers: typing.Dict[str, str],
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
payload: bytes):
"""

:param uri: str:
:param headers: typing.Dict[str:
:param headers: CaseInsensitiveDict[str:
:param str]:
:param payload: bytes:

Expand Down Expand Up @@ -2331,10 +2332,10 @@ def login5(self, scopes: typing.List[str]) -> typing.Union[StoredToken, None]:
response = requests.post(
"https://login5.spotify.com/v3/login",
data=login5_request.SerializeToString(),
headers={
headers=CaseInsensitiveDict({
"Content-Type": "application/x-protobuf",
"Accept": "application/x-protobuf"
})
}))

if response.status_code == 200:
login5_response = Login5.LoginResponse()
Expand Down
5 changes: 3 additions & 2 deletions librespot/mercury.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from librespot.crypto import Packet
from librespot.proto import Mercury_pb2 as Mercury, Pubsub_pb2 as Pubsub
from librespot.structure import Closeable, PacketsReceiver, SubListener
from requests.structures import CaseInsensitiveDict
import io
import json
import logging
Expand Down Expand Up @@ -346,11 +347,11 @@ def new_builder():
return RawMercuryRequest.Builder()

class Builder:
header_dict: dict
header_dict: CaseInsensitiveDict
payload: typing.List[bytes]

def __init__(self):
self.header_dict = {}
self.header_dict = CaseInsensitiveDict()
self.payload = []

def set_uri(self, uri: str):
Expand Down
3 changes: 2 additions & 1 deletion librespot/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from librespot.crypto import Packet
from librespot.mercury import MercuryClient
from librespot.proto import Metadata_pb2 as Metadata
from requests.structures import CaseInsensitiveDict


class AudioDecrypt:
Expand Down Expand Up @@ -61,7 +62,7 @@ def stream_read_resumed(self, chunk: int, _time: int) -> None:


class MessageListener:
def on_message(self, uri: str, headers: typing.Dict[str, str],
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
payload: bytes):
raise NotImplementedError

Expand Down
3 changes: 2 additions & 1 deletion librespot/zeroconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from librespot.crypto import DiffieHellman
from librespot.proto import Connect_pb2 as Connect
from librespot.structure import Closeable, Runnable, SessionListener
from requests.structures import CaseInsensitiveDict
import base64
import concurrent.futures
import copy
Expand Down Expand Up @@ -275,7 +276,7 @@ def __handle(self, __socket: socket.socket) -> None:
method = request_line[0].decode()
path = request_line[1].decode()
http_version = request_line[2].decode()
headers = {}
headers = CaseInsensitiveDict()
while True:
header = request.readline().strip()
if not header:
Expand Down
3 changes: 2 additions & 1 deletion librespot_player/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from librespot.mercury import MercuryRequests
from librespot.proto import Connect_pb2 as Connect
from librespot.structure import Closeable, MessageListener, RequestListener
from requests.structures import CaseInsensitiveDict
import concurrent.futures
import logging
import typing
Expand Down Expand Up @@ -200,6 +201,6 @@ def __init__(self, session: Session, player: Player,
"hm://collection/collection/" + session.username() + "/json"
])

def on_message(self, uri: str, headers: typing.Dict[str, str],
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
payload: bytes):
pass
Loading