fix: license + login5

This commit is contained in:
xoconoch
2025-08-30 11:25:07 -06:00
parent 28bfcbf826
commit 8bca880d33
10 changed files with 494 additions and 51 deletions

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 README.md
include requirements.txt include requirements.txt
include LICENSE include LICENSE
include NOTICE
# Include all .proto files in the proto directory and its subdirectories # Include all .proto files in the proto directory and its subdirectories
graft proto 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 ## 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 ## Getting Started
@@ -14,18 +14,10 @@ This project is to further add more features for the spotizerr project, forked f
### Installation ### Installation
Stable Version
```commandline ```commandline
pip install librespot-spotizerr pip install librespot-spotizerr
``` ```
Snapshot Version \***Not recommended**
```commandline
pip install git+https://github.com/Xoconoch/librespot-spotizerr
```
## Usage ## Usage
### Use Zeroconf for Login (no premium required) ### Use Zeroconf for Login (no premium required)
@@ -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. # 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 ## Debug
To display the debug information, you need to inject the following code at the To display the debug information, you need to inject the following code at the
@@ -90,8 +77,8 @@ Pull requests are welcome.
## License ## License
Distributed under the GPL yada yada, See Licensed under the Apache License, Version 2.0. See
[LICENSE](https://github.com/Xoconoch/librespot-spotizerr/blob/main/LICENSE) [LICENSE](https://github.com/spotizerr-dev/librespot-spotizerr/blob/main/LICENSE)
for more information. for more information.
## Related Projects ## Related Projects

View File

@@ -40,7 +40,6 @@ from librespot.crypto import CipherPair
from librespot.crypto import DiffieHellman from librespot.crypto import DiffieHellman
from librespot.crypto import Packet from librespot.crypto import Packet
from librespot.mercury import MercuryClient from librespot.mercury import MercuryClient
from librespot.mercury import MercuryRequests
from librespot.mercury import RawMercuryRequest from librespot.mercury import RawMercuryRequest
from librespot.metadata import AlbumId from librespot.metadata import AlbumId
from librespot.metadata import ArtistId 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 Metadata_pb2 as Metadata
from librespot.proto import Playlist4External_pb2 as Playlist4External from librespot.proto import Playlist4External_pb2 as Playlist4External
from librespot.proto.ExplicitContentPubsub_pb2 import UserAttributesUpdate 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 Closeable
from librespot.structure import MessageListener from librespot.structure import MessageListener
from librespot.structure import RequestListener from librespot.structure import RequestListener
@@ -203,7 +204,7 @@ class ApiClient(Closeable):
proto_req = ClientToken.ClientTokenRequest( 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_data=ClientToken.ClientDataRequest(
client_id=MercuryRequests.keymaster_client_id, client_id=Session.CLIENT_ID,
client_version=Version.version_name, client_version=Version.version_name,
connectivity_sdk_data=Connectivity.ConnectivitySdkData( connectivity_sdk_data=Connectivity.ConnectivitySdkData(
device_id=self.__session.device_id(), device_id=self.__session.device_id(),
@@ -781,6 +782,7 @@ class MessageType(enum.Enum):
class Session(Closeable, MessageListener, SubListener): class Session(Closeable, MessageListener, SubListener):
""" """ """ """
CLIENT_ID = "65b708073fc0480ea92a077233ca87bd" # Spotify client ID for librespot
cipher_pair: typing.Union[CipherPair, None] cipher_pair: typing.Union[CipherPair, None]
country_code: str = "EN" country_code: str = "EN"
connection: typing.Union[ConnectionHolder, None] connection: typing.Union[ConnectionHolder, None]
@@ -823,6 +825,8 @@ class Session(Closeable, MessageListener, SubListener):
__stored_str: str = "" __stored_str: str = ""
__token_provider: typing.Union[TokenProvider, None] __token_provider: typing.Union[TokenProvider, None]
__user_attributes = {} __user_attributes = {}
__login5_access_token: typing.Union[str, None] = None
__login5_token_expiry: typing.Union[int, None] = None
def __init__(self, inner: Inner, address: str) -> None: def __init__(self, inner: Inner, address: str) -> None:
self.__client = Session.create_client(inner.conf) self.__client = Session.create_client(inner.conf)
@@ -862,6 +866,10 @@ class Session(Closeable, MessageListener, SubListener):
""" """
self.__authenticate_partial(credential, False) self.__authenticate_partial(credential, False)
# Try Login5 authentication for access token
self.__authenticate_login5(credential)
with self.__auth_lock: with self.__auth_lock:
self.__mercury_client = MercuryClient(self) self.__mercury_client = MercuryClient(self)
self.__token_provider = TokenProvider(self) self.__token_provider = TokenProvider(self)
@@ -1279,6 +1287,66 @@ class Session(Closeable, MessageListener, SubListener):
def __send_unchecked(self, cmd: bytes, payload: bytes) -> None: def __send_unchecked(self, cmd: bytes, payload: bytes) -> None:
self.cipher_pair.send_encoded(self.connection, cmd, payload) self.cipher_pair.send_encoded(self.connection, cmd, payload)
def __authenticate_login5(self, credential: Authentication.LoginCredentials) -> None:
"""Authenticate using Login5 to get access token"""
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.__inner.device_id
# Set stored credential from APWelcome
if hasattr(self, '_Session__ap_welcome') and self.__ap_welcome:
stored_cred = Login5Credentials.StoredCredential()
stored_cred.username = self.__ap_welcome.canonical_username
stored_cred.data = self.__ap_welcome.reusable_auth_credentials
login5_request.stored_credential.CopyFrom(stored_cred)
# Send Login5 request
login5_url = "https://login5.spotify.com/v3/login"
headers = {
"Content-Type": "application/x-protobuf",
"Accept": "application/x-protobuf"
}
response = requests.post(
login5_url,
data=login5_request.SerializeToString(),
headers=headers
)
if response.status_code == 200:
login5_response = Login5.LoginResponse()
login5_response.ParseFromString(response.content)
if login5_response.HasField('ok'):
self.__login5_access_token = login5_response.ok.access_token
self.__login5_token_expiry = int(time.time()) + login5_response.ok.access_token_expires_in
self.logger.info("Login5 authentication successful, got access token")
else:
error_msg = "Login5 authentication failed"
if login5_response.HasField('error'):
error_msg += f": {login5_response.error}"
self.logger.error(error_msg)
# Don't raise exception here, as the session can still work with some limitations
else:
self.logger.error("Login5 request failed with status: {}".format(response.status_code))
# Don't raise exception here, as the session can still work with some limitations
except Exception as e:
self.logger.error("Failed to authenticate with Login5: {}".format(e))
# Don't raise exception here, as the session can still work with some limitations
def get_login5_token(self) -> typing.Union[str, None]:
"""Get the Login5 access token if available and not expired"""
if self.__login5_access_token and self.__login5_token_expiry:
if int(time.time()) < self.__login5_token_expiry - 60: # 60 second buffer
return self.__login5_access_token
else:
self.logger.debug("Login5 token expired, need to re-authenticate")
return None
def __wait_auth_lock(self) -> None: def __wait_auth_lock(self) -> None:
if self.__closing and self.connection is None: if self.__closing and self.connection is None:
self.logger.debug("Connection was broken while closing.") self.logger.debug("Connection was broken while closing.")
@@ -1921,7 +1989,7 @@ class Session(Closeable, MessageListener, SubListener):
format(util.bytes_to_hex(packet.cmd), format(util.bytes_to_hex(packet.cmd),
packet.payload)) packet.payload))
continue continue
except (RuntimeError, ConnectionResetError) as ex: except (RuntimeError, ConnectionResetError, OSError) as ex:
if self.__running: if self.__running:
self.__session.logger.fatal( self.__session.logger.fatal(
"Failed reading packet! {}".format(ex)) "Failed reading packet! {}".format(ex))
@@ -2171,24 +2239,46 @@ class TokenProvider:
scopes = list(scopes) scopes = list(scopes)
if len(scopes) == 0: if len(scopes) == 0:
raise RuntimeError("The token doesn't have any scope") raise RuntimeError("The token doesn't have any scope")
# Use Login5 token
login5_token = self._session.get_login5_token()
if login5_token:
# Create a StoredToken-compatible object using Login5 token
login5_stored_token = TokenProvider.Login5StoredToken(login5_token, scopes)
self.logger.debug("Using Login5 access token for scopes: {}".format(scopes))
return login5_stored_token
# Check existing tokens
token = self.find_token_with_all_scopes(scopes) token = self.find_token_with_all_scopes(scopes)
if token is not None: if token is not None:
if token.expired(): if token.expired():
self.__tokens.remove(token) self.__tokens.remove(token)
else: else:
return token return token
self.logger.debug(
"Token expired or not suitable, requesting again. scopes: {}, old_token: {}" # No valid token available
.format(scopes, token)) raise RuntimeError("Unable to obtain access token. Login5 authentication may have failed.")
response = self._session.mercury().send_sync_json(
MercuryRequests.request_token(self._session.device_id(), class Login5StoredToken:
",".join(scopes))) """StoredToken-compatible wrapper for Login5 access tokens"""
token = TokenProvider.StoredToken(response) access_token: str
self.logger.debug( scopes: typing.List[str]
"Updated token successfully! scopes: {}, new_token: {}".format(
scopes, token)) def __init__(self, access_token: str, scopes: typing.List[str]):
self.__tokens.append(token) self.access_token = access_token
return token self.scopes = scopes
def expired(self) -> bool:
"""Login5 tokens are managed by Session, so delegate expiry check"""
return False # Session handles expiry
def has_scope(self, scope: str) -> bool:
"""Login5 tokens are general-purpose, assume they have all scopes"""
return True
def has_scopes(self, sc: typing.List[str]) -> bool:
"""Login5 tokens are general-purpose, assume they have all scopes"""
return True
class StoredToken: class StoredToken:
""" """ """ """

View File

@@ -299,13 +299,6 @@ class MercuryRequests:
@TODO implement function @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: 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 reflection as _reflection
from google.protobuf import symbol_database as _symbol_database from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import enum_type_wrapper from google.protobuf.internal import enum_type_wrapper
from spotify.login5.v3 import \ from librespot.proto.spotify.login5.v3 import \
client_info_pb2 as spotify_dot_login5_dot_v3_dot_client__info__pb2 ClientInfo_pb2 as spotify_dot_login5_dot_v3_dot_client__info__pb2
from spotify.login5.v3 import \ from librespot.proto.spotify.login5.v3 import \
user_info_pb2 as spotify_dot_login5_dot_v3_dot_user__info__pb2 UserInfo_pb2 as spotify_dot_login5_dot_v3_dot_user__info__pb2
from spotify.login5.v3.challenges import \ from librespot.proto.spotify.login5.v3.challenges import \
code_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_code__pb2 Code_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_code__pb2
from spotify.login5.v3.challenges import \ from librespot.proto.spotify.login5.v3.challenges import \
hashcash_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_hashcash__pb2 Hashcash_pb2 as spotify_dot_login5_dot_v3_dot_challenges_dot_hashcash__pb2
from spotify.login5.v3.credentials import \ from librespot.proto.spotify.login5.v3.credentials import \
credentials_pb2 as \ Credentials_pb2 as \
spotify_dot_login5_dot_v3_dot_credentials_dot_credentials__pb2 spotify_dot_login5_dot_v3_dot_credentials_dot_credentials__pb2
from spotify.login5.v3.identifiers import \ from librespot.proto.spotify.login5.v3.identifiers import \
identifiers_pb2 as \ Identifiers as \
spotify_dot_login5_dot_v3_dot_identifiers_dot_identifiers__pb2 spotify_dot_login5_dot_v3_dot_identifiers_dot_identifiers__pb2
# @@protoc_insertion_point(imports) # @@protoc_insertion_point(imports)

View File

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

73
tests/test_login5.py Normal file
View File

@@ -0,0 +1,73 @@
#!/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]}...")
# Check if Login5 token is available
login5_token = session.get_login5_token()
if login5_token:
print(f"✓ Login5 token available: {login5_token[:20]}...")
else:
print("⚠ Login5 token not available")
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,86 @@
#!/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("1. Open Spotify on your phone/computer")
print("2. Look for 'librespot-spotizerr' in Spotify Connect devices")
print("3. Transfer playback to it")
print("4. Wait for credentials to be stored...")
print("\nWaiting for Spotify Connect transfer...")
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
if zs._ZeroconfServer__session:
session = zs._ZeroconfServer__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
login5_token = session.get_login5_token()
if login5_token:
print(f"✓ Login5 token available: {login5_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())