Skip to content

Commit 8760279

Browse files
authored
Merge pull request #319 from Googolplexed0/no-case-headers
Change request.headers from Dicts to CaseInsensitiveDicts
2 parents a96b11c + e007092 commit 8760279

8 files changed

Lines changed: 36 additions & 30 deletions

File tree

examples/player/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import time
66

77
import requests
8+
from requests.structures import CaseInsensitiveDict
89

910
from librespot.audio.decoders import AudioQuality, VorbisOnlyAudioQuality
1011
from librespot.core import Session
@@ -66,7 +67,7 @@ def client():
6667
"q": cmd[2:],
6768
"type": "track"
6869
},
69-
headers={"Authorization": "Bearer %s" % token},
70+
headers=CaseInsensitiveDict({"Authorization": "Bearer %s" % token}),
7071
)
7172
i = 1
7273
tracks = resp.json()["tracks"]["items"]

examples/server/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import re
33
import socket
44
import threading
5+
from requests.structures import CaseInsensitiveDict
56

67
from librespot.audio.decoders import AudioQuality, VorbisOnlyAudioQuality
78
from librespot.core import Session
@@ -23,7 +24,7 @@ def handler(client: socket.socket, address: str):
2324
req_method = req_http_arr[0]
2425
req_uri = req_http_arr[1]
2526
req_http_version = req_http_arr[2]
26-
req_header = {}
27+
req_header = CaseInsensitiveDict()
2728
for header in req_header_str.split(b"\r\n"):
2829
try:
2930
key, value = header.split(b": ")
@@ -73,7 +74,7 @@ def main():
7374
threading.Thread(target=handler, args=sock.accept()).start()
7475

7576

76-
def response(client: socket.socket, uri: str, header: dict,
77+
def response(client: socket.socket, uri: str, header: CaseInsensitiveDict,
7778
body: bytes) -> tuple[str, list, bytes, bool]:
7879
if re.search(r"^/audio/track/([0-9a-zA-Z]{22})$", uri) is not None:
7980
track_id_search = re.search(

librespot/audio/__init__.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from librespot.metadata import EpisodeId, PlayableId, TrackId
99
from librespot.proto import Metadata_pb2 as Metadata, StorageResolve_pb2 as StorageResolve
1010
from librespot.structure import AudioDecrypt, AudioQualityPicker, Closeable, FeederException, GeneralAudioStream, GeneralWritableStream, HaltListener, NoopAudioDecrypt, PacketsReceiver
11+
from requests.structures import CaseInsensitiveDict
1112
import concurrent.futures
1213
import io
1314
import logging
@@ -471,9 +472,9 @@ class CdnException(Exception):
471472

472473
class InternalResponse:
473474
buffer: bytes
474-
headers: typing.Dict[str, str]
475+
headers: CaseInsensitiveDict[str, str]
475476

476-
def __init__(self, buffer: bytes, headers: typing.Dict[str, str]):
477+
def __init__(self, buffer: bytes, headers: CaseInsensitiveDict[str, str]):
477478
self.buffer = buffer
478479
self.headers = headers
479480

@@ -578,8 +579,6 @@ def __init__(self, session: Session, stream_id: StreamId,
578579
response = self.request(range_start=0,
579580
range_end=ChannelManager.chunk_size - 1)
580581
content_range = response.headers.get("Content-Range")
581-
if content_range is None:
582-
content_range = response.headers.get("content-range")
583582
if content_range is None:
584583
raise IOError("Missing Content-Range header!")
585584
split = content_range.split("/")
@@ -633,16 +632,16 @@ def request(self, chunk: int = None, range_start: int = None, range_end: int = N
633632
range_end = (chunk + 1) * ChannelManager.chunk_size - 1
634633
response = self.__session.client().get(
635634
self.__cdn_url.url,
636-
headers={
635+
headers=CaseInsensitiveDict({
637636
"Range": "bytes={}-{}".format(range_start, range_end)
638-
},
637+
}),
639638
)
640639
if response.status_code != 206:
641640
raise IOError(response.status_code)
642641
body = response.content
643642
if body is None:
644643
raise IOError("Response body is empty!")
645-
return CdnManager.InternalResponse(body, dict(response.headers))
644+
return CdnManager.InternalResponse(body, response.headers)
646645

647646
class InternalStream(AbsChunkedInputStream):
648647
streamer: CdnManager.Streamer

librespot/core.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from Cryptodome.Protocol.KDF import PBKDF2
2929
from Cryptodome.PublicKey import RSA
3030
from Cryptodome.Signature import PKCS1_v1_5
31+
from requests.structures import CaseInsensitiveDict
3132

3233
from librespot import util
3334
from librespot import Version
@@ -80,7 +81,7 @@ def build_request(
8081
self,
8182
method: str,
8283
suffix: str,
83-
headers: typing.Union[None, typing.Dict[str, str]],
84+
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
8485
body: typing.Union[None, bytes],
8586
url: typing.Union[None, str],
8687
) -> requests.PreparedRequest:
@@ -89,7 +90,7 @@ def build_request(
8990
:param method: str:
9091
:param suffix: str:
9192
:param headers: typing.Union[None:
92-
:param typing.Dict[str:
93+
:param CaseInsensitiveDict[str:
9394
:param str]]:
9495
:param body: typing.Union[None:
9596
:param bytes]:
@@ -106,7 +107,7 @@ def build_request(
106107
request = requests.PreparedRequest()
107108
request.method = method
108109
request.data = body
109-
request.headers = {}
110+
request.headers = CaseInsensitiveDict()
110111
if headers is not None:
111112
request.headers = headers
112113
request.headers["Authorization"] = "Bearer {}".format(
@@ -122,15 +123,15 @@ def send(
122123
self,
123124
method: str,
124125
suffix: str,
125-
headers: typing.Union[None, typing.Dict[str, str]],
126+
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
126127
body: typing.Union[None, bytes],
127128
) -> requests.Response:
128129
"""
129130
130131
:param method: str:
131132
:param suffix: str:
132133
:param headers: typing.Union[None:
133-
:param typing.Dict[str:
134+
:param CaseInsensitiveDict[str:
134135
:param str]]:
135136
:param body: typing.Union[None:
136137
:param bytes]:
@@ -145,7 +146,7 @@ def sendToUrl(
145146
method: str,
146147
url: str,
147148
suffix: str,
148-
headers: typing.Union[None, typing.Dict[str, str]],
149+
headers: typing.Union[None, CaseInsensitiveDict[str, str]],
149150
body: typing.Union[None, bytes],
150151
) -> requests.Response:
151152
"""
@@ -154,7 +155,7 @@ def sendToUrl(
154155
:param url: str:
155156
:param suffix: str:
156157
:param headers: typing.Union[None:
157-
:param typing.Dict[str:
158+
:param CaseInsensitiveDict[str:
158159
:param str]]:
159160
:param body: typing.Union[None:
160161
:param bytes]:
@@ -327,10 +328,10 @@ def __client_token(self):
327328
resp = requests.post(
328329
"https://clienttoken.spotify.com/v1/clienttoken",
329330
proto_req.SerializeToString(),
330-
headers={
331+
headers=CaseInsensitiveDict({
331332
"Accept": "application/x-protobuf",
332333
"Content-Encoding": "",
333-
},
334+
}),
334335
)
335336

336337
ApiClient.StatusCodeException.check_status(resp)
@@ -604,10 +605,10 @@ def wait_for_listener(self) -> None:
604605
return
605606
self.__message_listeners_lock.wait()
606607

607-
def __get_headers(self, obj: typing.Any) -> dict[str, str]:
608+
def __get_headers(self, obj: typing.Any) -> CaseInsensitiveDict[str, str]:
608609
headers = obj.get("headers")
609610
if headers is None:
610-
return {}
611+
return CaseInsensitiveDict()
611612
return headers
612613

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

1215-
def on_message(self, uri: str, headers: typing.Dict[str, str],
1216+
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
12161217
payload: bytes):
12171218
"""
12181219
12191220
:param uri: str:
1220-
:param headers: typing.Dict[str:
1221+
:param headers: CaseInsensitiveDict[str:
12211222
:param str]:
12221223
:param payload: bytes:
12231224
@@ -2331,10 +2332,10 @@ def login5(self, scopes: typing.List[str]) -> typing.Union[StoredToken, None]:
23312332
response = requests.post(
23322333
"https://login5.spotify.com/v3/login",
23332334
data=login5_request.SerializeToString(),
2334-
headers={
2335+
headers=CaseInsensitiveDict({
23352336
"Content-Type": "application/x-protobuf",
23362337
"Accept": "application/x-protobuf"
2337-
})
2338+
}))
23382339

23392340
if response.status_code == 200:
23402341
login5_response = Login5.LoginResponse()

librespot/mercury.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from librespot.crypto import Packet
44
from librespot.proto import Mercury_pb2 as Mercury, Pubsub_pb2 as Pubsub
55
from librespot.structure import Closeable, PacketsReceiver, SubListener
6+
from requests.structures import CaseInsensitiveDict
67
import io
78
import json
89
import logging
@@ -346,11 +347,11 @@ def new_builder():
346347
return RawMercuryRequest.Builder()
347348

348349
class Builder:
349-
header_dict: dict
350+
header_dict: CaseInsensitiveDict
350351
payload: typing.List[bytes]
351352

352353
def __init__(self):
353-
self.header_dict = {}
354+
self.header_dict = CaseInsensitiveDict()
354355
self.payload = []
355356

356357
def set_uri(self, uri: str):

librespot/structure.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from librespot.crypto import Packet
99
from librespot.mercury import MercuryClient
1010
from librespot.proto import Metadata_pb2 as Metadata
11+
from requests.structures import CaseInsensitiveDict
1112

1213

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

6263

6364
class MessageListener:
64-
def on_message(self, uri: str, headers: typing.Dict[str, str],
65+
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
6566
payload: bytes):
6667
raise NotImplementedError
6768

librespot/zeroconf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from librespot.crypto import DiffieHellman
88
from librespot.proto import Connect_pb2 as Connect
99
from librespot.structure import Closeable, Runnable, SessionListener
10+
from requests.structures import CaseInsensitiveDict
1011
import base64
1112
import concurrent.futures
1213
import copy
@@ -275,7 +276,7 @@ def __handle(self, __socket: socket.socket) -> None:
275276
method = request_line[0].decode()
276277
path = request_line[1].decode()
277278
http_version = request_line[2].decode()
278-
headers = {}
279+
headers = CaseInsensitiveDict()
279280
while True:
280281
header = request.readline().strip()
281282
if not header:

librespot_player/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from librespot.mercury import MercuryRequests
66
from librespot.proto import Connect_pb2 as Connect
77
from librespot.structure import Closeable, MessageListener, RequestListener
8+
from requests.structures import CaseInsensitiveDict
89
import concurrent.futures
910
import logging
1011
import typing
@@ -200,6 +201,6 @@ def __init__(self, session: Session, player: Player,
200201
"hm://collection/collection/" + session.username() + "/json"
201202
])
202203

203-
def on_message(self, uri: str, headers: typing.Dict[str, str],
204+
def on_message(self, uri: str, headers: CaseInsensitiveDict[str, str],
204205
payload: bytes):
205206
pass

0 commit comments

Comments
 (0)