Compare commits

...

10 Commits

Author SHA1 Message Date
72dffca271 feat: improve Login5 authentication with token renewal
Signed-off-by: Lev Rusanov <30170278+JDM170@users.noreply.github.com>
2025-09-20 23:38:20 +07:00
xoconoch
56dade95e7 fix: README url 2025-08-30 11:26:43 -06:00
xoconoch
130b933c46 fix: Readme's license 2025-08-30 11:26:19 -06:00
xoconoch
8bca880d33 fix: license + login5 2025-08-30 11:25:07 -06:00
Xoconoch
28bfcbf826 Hotfix for spotify's metadata host. See https://github.com/devgianlu/go-librespot/issues/189 2025-08-07 12:26:40 -06:00
Xoconoch
bd75f2f5cc Patch zeroconf 2025-08-07 09:52:59 -06:00
Xoconoch
4f8364441c update readme 2025-06-05 14:57:25 -06:00
cool.gitter.not.me.again.duh
f108e4a8f1 smh 2025-05-31 17:00:16 -06:00
cool.gitter.not.me.again.duh
1b6c39790c I guess nott 2025-05-31 16:58:11 -06:00
cool.gitter.not.me.again.duh
2a99432b49 was it because of the "'s? 2025-05-31 16:55:04 -06:00
13 changed files with 643 additions and 197 deletions

View File

@@ -32,14 +32,14 @@ jobs:
- name: Update version in setup.py
run: |
VERSION_TAG="${{ steps.get_version.outputs.VERSION }}"
sed -i "s/version="[^"]*"/version="${VERSION_TAG}""/" setup.py
VERSION_TAG=${{ steps.get_version.outputs.VERSION }}
sed -i "s/version=\"[^\"]*\"/version=\"${VERSION_TAG}\"/" setup.py
echo "Updated setup.py to version $VERSION_TAG for build:"
cat setup.py
- name: Update version in librespot/__init__.py
run: |
VERSION_TAG="${{ steps.get_version.outputs.VERSION }}"
VERSION_TAG=${{ steps.get_version.outputs.VERSION }}
sed -i "s/version_name = \".*\"/version_name = \"${VERSION_TAG}\"/" librespot/__init__.py
echo "Updated librespot/__init__.py to version $VERSION_TAG for build:"
cat librespot/__init__.py

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright © 2020-2021 kokarare1212 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,6 +1,7 @@
include README.md
include requirements.txt
include LICENSE
include NOTICE
# Include all .proto files in the proto directory and its subdirectories
graft proto

11
NOTICE Normal file
View File

@@ -0,0 +1,11 @@
librespot-spotizerr
Copyright © 2020-2021 kokarare1212
This product includes software developed as part of the librespot-spotizerr project and is licensed under the Apache License, Version 2.0.
You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -4,7 +4,7 @@ Spotizerr's librespot python integration
## About The Project
This project is to further add more features for the spotizerr project, forked from [librespot-python](https://github.com/Xoconoch/librespot-spotizerr)
This project is to further add more features for the Spotizerr project, forked from [librespot-python](https://github.com/kokarare1212/librespot-python)
## Getting Started
@@ -14,16 +14,8 @@ This project is to further add more features for the spotizerr project, forked f
### Installation
Stable Version
```commandline
pip install librespot
```
Snapshot Version \***Recommended**
```commandline
pip install git+https://github.com/Xoconoch/librespot-spotizerr
pip install librespot-spotizerr
```
## Usage
@@ -67,11 +59,6 @@ stream = session.content_feeder().load(track_id, VorbisOnlyAudioQuality(AudioQua
# stream.input_stream.stream().read() to get one byte of the music stream.
```
Other uses are
[examples](https://github.com/Xoconoch/librespot-spotizerr/tree/main/examples)
or read [this document](https://librespot-spotizerr.rtfd.io) for detailed
specifications.
## Debug
To display the debug information, you need to inject the following code at the
@@ -90,8 +77,8 @@ Pull requests are welcome.
## License
Distributed under the GPL yada yada, See
[LICENSE](https://github.com/Xoconoch/librespot-spotizerr/blob/main/LICENSE)
Licensed under the Apache License, Version 2.0. See
[LICENSE](https://lavaforge.org/spotizerr/librespot-spotizerr/src/branch/main/LICENSE)
for more information.
## Related Projects

View File

@@ -40,7 +40,6 @@ from librespot.crypto import CipherPair
from librespot.crypto import DiffieHellman
from librespot.crypto import Packet
from librespot.mercury import MercuryClient
from librespot.mercury import MercuryRequests
from librespot.mercury import RawMercuryRequest
from librespot.metadata import AlbumId
from librespot.metadata import ArtistId
@@ -56,6 +55,8 @@ from librespot.proto import Keyexchange_pb2 as Keyexchange
from librespot.proto import Metadata_pb2 as Metadata
from librespot.proto import Playlist4External_pb2 as Playlist4External
from librespot.proto.ExplicitContentPubsub_pb2 import UserAttributesUpdate
from librespot.proto.spotify.login5.v3 import Login5_pb2 as Login5
from librespot.proto.spotify.login5.v3.credentials import Credentials_pb2 as Login5Credentials
from librespot.structure import Closeable
from librespot.structure import MessageListener
from librespot.structure import RequestListener
@@ -80,33 +81,27 @@ class ApiClient(Closeable):
headers: typing.Union[None, typing.Dict[str, str]],
body: typing.Union[None, bytes],
) -> requests.PreparedRequest:
"""
:param method: str:
:param suffix: str:
:param headers: typing.Union[None:
:param typing.Dict[str:
:param str]]:
:param body: typing.Union[None:
:param bytes]:
"""
if self.__client_token_str is None:
resp = self.__client_token()
self.__client_token_str = resp.granted_token.token
self.logger.debug("Updated client token: {}".format(
self.__client_token_str))
self.logger.debug("Updated client token: {}".format(self.__client_token_str))
request = requests.PreparedRequest()
request.method = method
request.data = body
request.headers = {}
if headers is not None:
request.headers = headers
request.headers = headers.copy() if headers else {}
request.headers["Authorization"] = "Bearer {}".format(
self.__session.tokens().get("playlist-read"))
self.__session.tokens().get("playlist-read")
)
request.headers["client-token"] = self.__client_token_str
request.url = self.__base_url + suffix
# Force metadata requests to use a specific host
if suffix.startswith("/metadata/4/"):
base_url = "https://spclient.wg.spotify.com"
else:
base_url = self.__base_url
request.url = base_url + suffix
return request
def send(
@@ -116,29 +111,12 @@ class ApiClient(Closeable):
headers: typing.Union[None, typing.Dict[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 str]]:
:param body: typing.Union[None:
:param bytes]:
"""
response = self.__session.client().send(
self.build_request(method, suffix, headers, body))
self.build_request(method, suffix, headers, body)
)
return response
def put_connect_state(self, connection_id: str,
proto: Connect.PutStateRequest) -> None:
"""
:param connection_id: str:
:param proto: Connect.PutStateRequest:
"""
def put_connect_state(self, connection_id: str, proto: Connect.PutStateRequest) -> None:
response = self.send(
"PUT",
"/connect-state/v1/devices/{}".format(self.__session.device_id()),
@@ -150,21 +128,17 @@ class ApiClient(Closeable):
)
if response.status_code == 413:
self.logger.warning(
"PUT state payload is too large: {} bytes uncompressed.".
format(len(proto.SerializeToString())))
"PUT state payload is too large: {} bytes uncompressed.".format(
len(proto.SerializeToString())
)
)
elif response.status_code != 200:
self.logger.warning("PUT state returned {}. headers: {}".format(
response.status_code, response.headers))
self.logger.warning(
"PUT state returned {}. headers: {}".format(response.status_code, response.headers)
)
def get_metadata_4_track(self, track: TrackId) -> Metadata.Track:
"""
:param track: TrackId:
"""
response = self.send("GET",
"/metadata/4/track/{}".format(track.hex_id()),
None, None)
response = self.send("GET", "/metadata/4/track/{}".format(track.hex_id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
@@ -174,14 +148,7 @@ class ApiClient(Closeable):
return proto
def get_metadata_4_episode(self, episode: EpisodeId) -> Metadata.Episode:
"""
:param episode: EpisodeId:
"""
response = self.send("GET",
"/metadata/4/episode/{}".format(episode.hex_id()),
None, None)
response = self.send("GET", "/metadata/4/episode/{}".format(episode.hex_id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
@@ -191,16 +158,8 @@ class ApiClient(Closeable):
return proto
def get_metadata_4_album(self, album: AlbumId) -> Metadata.Album:
"""
:param album: AlbumId:
"""
response = self.send("GET",
"/metadata/4/album/{}".format(album.hex_id()),
None, None)
response = self.send("GET", "/metadata/4/album/{}".format(album.hex_id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
raise IOError()
@@ -209,14 +168,7 @@ class ApiClient(Closeable):
return proto
def get_metadata_4_artist(self, artist: ArtistId) -> Metadata.Artist:
"""
:param artist: ArtistId:
"""
response = self.send("GET",
"/metadata/4/artist/{}".format(artist.hex_id()),
None, None)
response = self.send("GET", "/metadata/4/artist/{}".format(artist.hex_id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
@@ -226,14 +178,7 @@ class ApiClient(Closeable):
return proto
def get_metadata_4_show(self, show: ShowId) -> Metadata.Show:
"""
:param show: ShowId:
"""
response = self.send("GET",
"/metadata/4/show/{}".format(show.hex_id()), None,
None)
response = self.send("GET", "/metadata/4/show/{}".format(show.hex_id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
@@ -242,16 +187,8 @@ class ApiClient(Closeable):
proto.ParseFromString(body)
return proto
def get_playlist(self,
_id: PlaylistId) -> Playlist4External.SelectedListContent:
"""
:param _id: PlaylistId:
"""
response = self.send("GET",
"/playlist/v2/playlist/{}".format(_id.id()), None,
None)
def get_playlist(self, _id: PlaylistId) -> Playlist4External.SelectedListContent:
response = self.send("GET", "/playlist/v2/playlist/{}".format(_id.id()), None, None)
ApiClient.StatusCodeException.check_status(response)
body = response.content
if body is None:
@@ -261,19 +198,13 @@ class ApiClient(Closeable):
return proto
def set_client_token(self, client_token):
"""
:param client_token:
"""
self.__client_token_str = client_token
def __client_token(self):
proto_req = ClientToken.ClientTokenRequest(
request_type=ClientToken.ClientTokenRequestType.
REQUEST_CLIENT_DATA_REQUEST,
request_type=ClientToken.ClientTokenRequestType.REQUEST_CLIENT_DATA_REQUEST,
client_data=ClientToken.ClientDataRequest(
client_id=MercuryRequests.keymaster_client_id,
client_id=Session.CLIENT_ID,
client_version=Version.version_name,
connectivity_sdk_data=Connectivity.ConnectivitySdkData(
device_id=self.__session.device_id(),
@@ -286,7 +217,8 @@ class ApiClient(Closeable):
something7=332,
something8=33404,
something10=True,
), ),
),
),
),
),
)
@@ -307,7 +239,6 @@ class ApiClient(Closeable):
return proto_resp
class StatusCodeException(IOError):
""" """
code: int
def __init__(self, response: requests.Response):
@@ -316,11 +247,6 @@ class ApiClient(Closeable):
@staticmethod
def check_status(response: requests.Response) -> None:
"""
:param response: requests.Response:
"""
if response.status_code != 200:
raise ApiClient.StatusCodeException(response)
@@ -856,6 +782,7 @@ class MessageType(enum.Enum):
class Session(Closeable, MessageListener, SubListener):
""" """
CLIENT_ID = "65b708073fc0480ea92a077233ca87bd" # Spotify client ID for librespot
cipher_pair: typing.Union[CipherPair, None]
country_code: str = "EN"
connection: typing.Union[ConnectionHolder, None]
@@ -937,9 +864,11 @@ class Session(Closeable, MessageListener, SubListener):
"""
self.__authenticate_partial(credential, False)
with self.__auth_lock:
self.__mercury_client = MercuryClient(self)
self.__token_provider = TokenProvider(self)
self.__audio_key_manager = AudioKeyManager(self)
self.__channel_manager = ChannelManager(self)
self.__api = ApiClient(self)
@@ -949,6 +878,12 @@ class Session(Closeable, MessageListener, SubListener):
self.__dealer_client = DealerClient(self)
self.__search = SearchManager(self)
self.__event_service = EventService(self)
# Try Login5 authentication for access token (after session is fully initialized)
try:
self.__token_provider.authenticate_login5(credential)
except Exception as e:
self.logger.warning(f"Login5 authentication failed: {e}")
self.__auth_lock_bool = False
self.__auth_lock.notify_all()
self.dealer().connect()
@@ -1354,6 +1289,7 @@ class Session(Closeable, MessageListener, SubListener):
def __send_unchecked(self, cmd: bytes, payload: bytes) -> None:
self.cipher_pair.send_encoded(self.connection, cmd, payload)
def __wait_auth_lock(self) -> None:
if self.__closing and self.connection is None:
self.logger.debug("Connection was broken while closing.")
@@ -1996,7 +1932,7 @@ class Session(Closeable, MessageListener, SubListener):
format(util.bytes_to_hex(packet.cmd),
packet.payload))
continue
except (RuntimeError, ConnectionResetError) as ex:
except (RuntimeError, ConnectionResetError, OSError) as ex:
if self.__running:
self.__session.logger.fatal(
"Failed reading packet! {}".format(ex))
@@ -2217,6 +2153,123 @@ class TokenProvider:
def __init__(self, session: Session):
self._session = session
def authenticate_login5(self, credential: Authentication.LoginCredentials) -> bool:
"""Authenticate using Login5 to get initial access token"""
self.logger.debug("Starting initial Login5 authentication process...")
# Use the login5 method to get initial token with common scopes
initial_scopes = ["playlist-read", "user-read-private", "user-read-playback-state"]
token = self.login5(initial_scopes)
if token is not None:
self.__tokens.append(token)
self.logger.info("Initial Login5 authentication successful, token cached")
return True
else:
self.logger.error("Initial Login5 authentication failed")
return False
def login5(self, scopes: typing.List[str]) -> typing.Union[StoredToken, None]:
"""Get a Login5 token for the specified scopes"""
self.logger.debug("Requesting Login5 token for scopes: {}".format(scopes))
try:
# Build Login5 request
login5_request = Login5.LoginRequest()
# Set client info
login5_request.client_info.client_id = Session.CLIENT_ID
login5_request.client_info.device_id = self._session.device_id()
# Set stored credential from APWelcome
has_attr = hasattr(self._session, '_Session__ap_welcome')
if has_attr:
try:
# Use a different approach since signal doesn't work in threads
import threading
result = [None] # Use list for mutable reference
exception = [None]
def get_ap_welcome():
try:
result[0] = self._session.ap_welcome()
except Exception as e:
exception[0] = e
thread = threading.Thread(target=get_ap_welcome)
thread.daemon = True
thread.start()
thread.join(timeout=3) # 3-second timeout
if thread.is_alive():
self.logger.warning("ap_welcome() call timed out")
return None
if exception[0]:
raise exception[0]
ap_welcome = result[0]
if ap_welcome:
stored_cred = Login5Credentials.StoredCredential()
stored_cred.username = ap_welcome.canonical_username
stored_cred.data = ap_welcome.reusable_auth_credentials
login5_request.stored_credential.CopyFrom(stored_cred)
else:
self.logger.warning("Login5 token request skipped: No APWelcome credentials available")
return None
except Exception as e:
self.logger.warning("Login5 token request skipped: No APWelcome credentials available")
return None
else:
self.logger.warning("Login5 token request skipped: No APWelcome credentials available")
return None
# Send Login5 request
login5_url = "https://login5.spotify.com/v3/login"
headers = {
"Content-Type": "application/x-protobuf",
"Accept": "application/x-protobuf"
}
self.logger.debug("Sending Login5 token request to: {}".format(login5_url))
response = requests.post(
login5_url,
data=login5_request.SerializeToString(),
headers=headers,
timeout=10 # Add timeout to prevent hanging
)
if response.status_code == 200:
login5_response = Login5.LoginResponse()
login5_response.ParseFromString(response.content)
if login5_response.HasField('ok'):
# Create StoredToken object
token_data = {
"expiresIn": login5_response.ok.access_token_expires_in,
"accessToken": login5_response.ok.access_token,
"scope": scopes
}
stored_token = TokenProvider.StoredToken(token_data)
self.logger.info("Login5 token obtained successfully with {} seconds validity".format(
login5_response.ok.access_token_expires_in))
return stored_token
else:
error_msg = "Login5 token request failed"
if login5_response.HasField('error'):
error_msg += f": {login5_response.error}"
self.logger.error(error_msg)
return None
else:
self.logger.error("Login5 token request failed with status: {}".format(response.status_code))
return None
except Exception as e:
self.logger.error("Failed to obtain Login5 token: {} - {}".format(type(e).__name__, str(e)))
return None
def find_token_with_all_scopes(
self, scopes: typing.List[str]) -> typing.Union[StoredToken, None]:
"""
@@ -2246,24 +2299,29 @@ class TokenProvider:
scopes = list(scopes)
if len(scopes) == 0:
raise RuntimeError("The token doesn't have any scope")
# Check existing tokens first
token = self.find_token_with_all_scopes(scopes)
if token is not None:
if token.expired():
self.logger.debug("Token expired, removing from cache")
self.__tokens.remove(token)
else:
self.logger.debug("Using cached token for scopes: {}".format(scopes))
return token
self.logger.debug(
"Token expired or not suitable, requesting again. scopes: {}, old_token: {}"
.format(scopes, token))
response = self._session.mercury().send_sync_json(
MercuryRequests.request_token(self._session.device_id(),
",".join(scopes)))
token = TokenProvider.StoredToken(response)
self.logger.debug(
"Updated token successfully! scopes: {}, new_token: {}".format(
scopes, token))
self.__tokens.append(token)
return token
# Try to get a new Login5 token
self.logger.debug("No valid cached token found, attempting Login5 renewal")
login5_token = self.login5(scopes)
if login5_token is not None:
self.__tokens.append(login5_token)
self.logger.debug("Login5 token obtained and cached for scopes: {}".format(scopes))
return login5_token
# No valid token available
self.logger.warning("Unable to obtain access token through Login5")
raise RuntimeError("Unable to obtain access token. Login5 authentication failed.")
class StoredToken:
""" """

View File

@@ -299,13 +299,6 @@ class MercuryRequests:
@TODO implement function
"""
@staticmethod
def request_token(device_id, scope):
return JsonMercuryRequest(
RawMercuryRequest.get(
"hm://keymaster/token/authenticated?scope={}&client_id={}&device_id={}"
.format(scope, MercuryRequests.keymaster_client_id,
device_id)))
class RawMercuryRequest:

View File

@@ -7,19 +7,19 @@ from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import enum_type_wrapper
from spotify.login5.v3 import \
client_info_pb2 as spotify_dot_login5_dot_v3_dot_client__info__pb2
from spotify.login5.v3 import \
user_info_pb2 as spotify_dot_login5_dot_v3_dot_user__info__pb2
from spotify.login5.v3.challenges import \
code_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_code__pb2
from spotify.login5.v3.challenges import \
hashcash_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_hashcash__pb2
from spotify.login5.v3.credentials import \
credentials_pb2 as \
from librespot.proto.spotify.login5.v3 import \
ClientInfo_pb2 as spotify_dot_login5_dot_v3_dot_client__info__pb2
from librespot.proto.spotify.login5.v3 import \
UserInfo_pb2 as spotify_dot_login5_dot_v3_dot_user__info__pb2
from librespot.proto.spotify.login5.v3.challenges import \
Code_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_code__pb2
from librespot.proto.spotify.login5.v3.challenges import \
Hashcash_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_hashcash__pb2
from librespot.proto.spotify.login5.v3.credentials import \
Credentials_pb2 as \
spotify_dot_login5_dot_v3_dot_credentials_dot_credentials__pb2
from spotify.login5.v3.identifiers import \
identifiers_pb2 as \
from librespot.proto.spotify.login5.v3.identifiers import \
Identifiers_pb2 as \
spotify_dot_login5_dot_v3_dot_identifiers_dot_identifiers__pb2
# @@protoc_insertion_point(imports)

View File

@@ -23,6 +23,8 @@ import zeroconf
class ZeroconfServer(Closeable):
logger = logging.getLogger("Librespot:ZeroconfServer")
logger.propagate = False
service = "_spotify-connect._tcp.local."
__connecting_username: typing.Union[str, None] = None
__connection_lock = threading.Condition()
@@ -61,13 +63,16 @@ class ZeroconfServer(Closeable):
def __init__(self, inner: Inner, listen_port):
self.__inner = inner
self.__keys = DiffieHellman()
if listen_port == -1:
listen_port = random.randint(self.__min_port + 1, self.__max_port)
self.__runner = ZeroconfServer.HttpRunner(self, listen_port)
threading.Thread(target=self.__runner.run,
name="zeroconf-http-server").start()
name="zeroconf-http-server",
daemon=True).start()
self.__zeroconf = zeroconf.Zeroconf()
advertised_ip_str = self._get_local_ip()
server_hostname = socket.gethostname()
@@ -101,7 +106,12 @@ class ZeroconfServer(Closeable):
addresses=service_addresses # Pass resolved IP, or None if 0.0.0.0 or conversion failed
)
self.__zeroconf.register_service(self.__service_info)
try:
self.__zeroconf.register_service(self.__service_info)
self.logger.info("Zeroconf service registered successfully!")
except Exception as e:
self.logger.error("Failed to register zeroconf service: {}".format(e))
raise
def _get_local_ip(self) -> str:
"""Tries to determine a non-loopback local IP address for network advertisement."""
@@ -120,7 +130,7 @@ class ZeroconfServer(Closeable):
hostname = socket.gethostname()
# gethostbyname can return 127.0.0.1 if hostname resolves to it
ip_address = socket.gethostbyname(hostname)
self.logger.info(f"IP from socket.gethostbyname('{hostname}'): {ip_address}")
self.logger.info(f"IP from socket.gethostname('{hostname}'): {ip_address}")
except socket.gaierror:
self.logger.error(
f"socket.gaierror resolving hostname '{socket.gethostname()}'. Falling back to 0.0.0.0."
@@ -180,6 +190,7 @@ class ZeroconfServer(Closeable):
def handle_add_user(self, __socket: socket.socket, params: dict[str, str],
http_version: str) -> None:
self.logger.info("Spotify Connect transfer detected")
username = params.get("userName")
if not username:
self.logger.error("Missing userName!")
@@ -232,31 +243,42 @@ class ZeroconfServer(Closeable):
initial_value=int.from_bytes(
iv, "big")))
decrypted = aes.decrypt(encrypted)
self.close_session()
with self.__connection_lock:
self.__connecting_username = username
self.logger.info("Accepted new user from {}. [deviceId: {}]".format(
params.get("deviceName"), self.__inner.device_id))
response = json.dumps(self.__default_successful_add_user)
__socket.send(http_version.encode())
__socket.send(b" 200 OK")
__socket.send(self.__eol)
__socket.send(b"Content-Length: ")
__socket.send(str(len(response)).encode())
__socket.send(self.__eol)
__socket.send(self.__eol)
__socket.send(response.encode())
self.__session = Session.Builder(self.__inner.conf) \
.set_device_id(self.__inner.device_id) \
.set_device_name(self.__inner.device_name) \
.set_device_type(self.__inner.device_type) \
.set_preferred_locale(self.__inner.preferred_locale) \
.blob(username, decrypted) \
.create()
with self.__connection_lock:
self.__connecting_username = None
for session_listener in self.__session_listeners:
session_listener.session_changed(self.__session)
try:
self.close_session()
with self.__connection_lock:
self.__connecting_username = username
self.logger.info("Accepted new user from {}. [deviceId: {}]".format(
params.get("deviceName"), self.__inner.device_id))
response = json.dumps(self.__default_successful_add_user)
__socket.send(http_version.encode())
__socket.send(b" 200 OK")
__socket.send(self.__eol)
__socket.send(b"Content-Length: ")
__socket.send(str(len(response)).encode())
__socket.send(self.__eol)
__socket.send(self.__eol)
__socket.send(response.encode())
self.__session = Session.Builder(self.__inner.conf) \
.set_device_id(self.__inner.device_id) \
.set_device_name(self.__inner.device_name) \
.set_device_type(self.__inner.device_type) \
.set_preferred_locale(self.__inner.preferred_locale) \
.blob(username, decrypted) \
.create()
with self.__connection_lock:
self.__connecting_username = None
self.logger.info("Session created for user: {}".format(self.__session.username()))
for session_listener in self.__session_listeners:
session_listener.session_changed(self.__session)
except Exception as e:
self.logger.error("Error in handle_add_user: {}".format(e))
with self.__connection_lock:
self.__connecting_username = None
def handle_get_info(self, __socket: socket.socket,
http_version: str) -> None:
@@ -285,6 +307,10 @@ class ZeroconfServer(Closeable):
self.__session = None
return valid
def get_session(self) -> typing.Union[Session, None]:
"""Get the current session if valid, None otherwise"""
return self.__session if self.has_valid_session() else None
def parse_path(self, path: str) -> dict[str, str]:
url = "https://host" + path
parsed = {}
@@ -305,10 +331,10 @@ class ZeroconfServer(Closeable):
return self
def create(self) -> ZeroconfServer:
return ZeroconfServer(
ZeroconfServer.Inner(self.device_type, self.device_name,
self.device_id, self.preferred_locale,
self.conf), self.listen_port)
inner = ZeroconfServer.Inner(self.device_type, self.device_name,
self.device_id, self.preferred_locale,
self.conf)
return ZeroconfServer(inner, self.listen_port)
class HttpRunner(Closeable, Runnable):
__should_stop = False
@@ -388,6 +414,7 @@ class ZeroconfServer(Closeable):
def handle_request(self, __socket: socket.socket, http_version: str,
action: str, params: dict[str, str]) -> None:
self.__zeroconf_server.logger.debug("HTTP request received - action: {}, params: {}".format(action, params.keys() if params else "None"))
if action == "addUser":
if params is None:
raise RuntimeError
@@ -414,4 +441,4 @@ class ZeroconfServer(Closeable):
self.device_id = util.random_hex_string(
40).lower() if not device_id else device_id
self.device_type = device_type
self.preferred_locale = preferred_locale
self.preferred_locale = preferred_locale

View File

@@ -20,10 +20,11 @@ setuptools.setup(name="librespot-spotizerr",
author="Xoconoch",
url="https://github.com/Xoconoch/librespot-spotizerr",
license="Apache-2.0", # SPDX identifier
license_files=["LICENSE", "NOTICE"],
packages=setuptools.find_packages("."),
install_requires=install_requires,
classifiers=[
"Development Status :: 1 - Planning",
# "License :: OSI Approved :: Apache Software License", # Removed
"Topic :: Multimedia :: Sound/Audi o"
"License :: OSI Approved :: Apache Software License",
"Topic :: Multimedia :: Sound/Audio"
])

76
tests/test_login5.py Normal file
View File

@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""
Test script to verify Login5 authentication using stored credentials
"""
import logging
import sys
import os
from librespot.core import Session
# Enable debug logging to see what's happening
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def test_with_stored_credentials():
"""Test using stored credentials (if available)"""
print("=== Testing with stored credentials ===")
try:
if os.path.exists("credentials.json"):
session = Session.Builder().stored_file("credentials.json").create()
print(f"✓ Successfully authenticated as: {session.username()}")
# Test token retrieval
token_provider = session.tokens()
try:
token = token_provider.get("playlist-read")
print(f"✓ Successfully got playlist-read token: {token[:20]}...")
# Test Login5 token by requesting a different scope
try:
login5_token = token_provider.get_token("user-read-email", "user-read-private")
if login5_token and login5_token.access_token:
print(f"✓ Login5 token available: {login5_token.access_token[:20]}...")
else:
print("⚠ Login5 token not available")
except Exception as login5_error:
print(f"⚠ Login5 token test failed: {login5_error}")
session.close()
return True
except Exception as e:
print(f"✗ Token retrieval failed: {e}")
session.close()
return False
else:
print("⚠ No credentials.json file found")
return False
except Exception as e:
print(f"✗ Authentication failed: {e}")
return False
def main():
print("Testing Login5 Authentication Implementation")
print("=" * 50)
# Test with stored credentials
stored_success = test_with_stored_credentials()
# Note: Username/password authentication has been deprecated by Spotify
# and is no longer supported. Use stored credentials or OAuth flow instead.
print("\n" + "=" * 50)
print("Test Results:")
print(f"Stored credentials: {'✓ PASS' if stored_success else '✗ FAIL or NO CREDENTIALS'}")
if stored_success:
print("\n🎉 Login5 authentication is working!")
return 0
else:
print("\n⚠ Could not test authentication - no valid credentials.json file found")
print(" Please authenticate using OAuth or other supported methods first.")
return 1
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""
Test script using Zeroconf/Spotify Connect to verify Login5 authentication
"""
import logging
import time
import pathlib
from librespot.zeroconf import ZeroconfServer
# Enable debug logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def test_zeroconf_login5():
"""Test Login5 using Zeroconf authentication"""
print("=== Testing Login5 with Zeroconf ===")
print("IMPORTANT: This test requires a Spotify Connect transfer!")
print("1. Open Spotify on your phone/computer")
print("2. Start playing some music")
print("3. Look for 'librespot-spotizerr' in Spotify Connect devices")
print("4. Click on 'librespot-spotizerr' to transfer playback to it")
print("5. Wait for credentials to be stored...")
print("\nWaiting for Spotify Connect transfer...")
print("NOTE: You'll see 'Created new session!' logs - this is normal startup.")
print("The test will only succeed when you transfer playback from Spotify Connect.")
zs = ZeroconfServer.Builder().create()
start_time = time.time()
timeout = 60 # 60 seconds timeout
while True:
time.sleep(1)
elapsed = time.time() - start_time
if elapsed > timeout:
print(f"\n⚠ Timeout after {timeout} seconds")
print("Make sure you:")
print("- Have Spotify open on another device")
print("- Can see 'librespot-spotizerr' in Spotify Connect")
print("- Transfer playback to it")
return False
# Check for session
session = zs.get_session()
if session:
print(f"\n✓ Got session for user: {session.username()}")
# Test token retrieval
try:
token_provider = session.tokens()
token = token_provider.get("playlist-read")
print(f"✓ Got playlist-read token: {token[:20]}...")
# Test Login5 token by requesting a different scope using get_token
login5_token = token_provider.get_token("user-read-email", "user-read-private")
if login5_token:
print(f"✓ Login5 token available: {login5_token.access_token[:20]}...")
else:
print("⚠ Login5 token not available")
# Check if credentials were saved
if pathlib.Path("credentials.json").exists():
print("✓ Credentials saved to credentials.json")
print("\nYou can now use the stored credentials for future tests!")
return True
else:
print("⚠ Credentials not saved")
return True
except Exception as e:
print(f"✗ Token test failed: {e}")
return False
def main():
print("Zeroconf Login5 Test")
print("=" * 30)
success = test_zeroconf_login5()
print("\n" + "=" * 30)
if success:
print("🎉 Zeroconf Login5 test completed successfully!")
return 0
else:
print("⚠ Zeroconf test failed or timed out")
return 1
if __name__ == "__main__":
import sys
sys.exit(main())