Skip to content

Commit

Permalink
cache visitor ID on first use
Browse files Browse the repository at this point in the history
```diff
import ytmusicapi
import timeit

yt = ytmusicapi.YTMusic()
for _ in range(2):
  round(timeit.timeit(lambda: yt.get_album('MPREb_4pL8gzRtw1p'), number=1) * 1000)

-710
-593
+753
+146
```
  • Loading branch information
sgvictorino committed Feb 3, 2025
1 parent a004bed commit 413bb6a
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions ytmusicapi/ytmusic.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ def __init__(
except KeyError:
raise YTMusicUserError("Your cookie is missing the required value __Secure-3PAPISID")

self.visitor_id = None

@property
def base_headers(self) -> CaseInsensitiveDict:
if self.auth_type == AuthType.BROWSER or self.auth_type == AuthType.OAUTH_CUSTOM_FULL:
Expand All @@ -168,10 +170,11 @@ def base_headers(self) -> CaseInsensitiveDict:

@property
def headers(self) -> CaseInsensitiveDict:
headers = self.base_headers
visitor_id = self.visitor_id or get_visitor_id(partial(self._send_get_request, use_base_headers=True))
self.visitor_id = visitor_id

if "X-Goog-Visitor-Id" not in headers:
headers.update(get_visitor_id(partial(self._send_get_request, use_base_headers=True)))
headers = self.base_headers
headers.update(visitor_id)

# keys updated each use, custom oauth implementations left untouched
if self.auth_type == AuthType.BROWSER:
Expand Down

0 comments on commit 413bb6a

Please sign in to comment.