Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimized visitorData extraction #410

Merged
merged 1 commit into from
Jan 9, 2025
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
13 changes: 9 additions & 4 deletions pytubefix/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,16 @@ def visitor_data(self) -> str:
if self._visitor_data:
return self._visitor_data

innertube_response = InnerTube('WEB').player(self.video_id)
try:
self._visitor_data = innertube_response['responseContext']['visitorData']
except KeyError:
self._visitor_data = innertube_response['responseContext']['serviceTrackingParams'][0]['params'][6]['value']
logger.debug("Looking for visitorData in initial_data")
self._visitor_data = extract.visitor_data(str(self.initial_data['responseContext']))
except (KeyError, pytubefix.exceptions.RegexMatchError):
logger.debug("Unable to obtain visitorData from initial_data. Trying to request from the WEB client")
innertube_response = InnerTube('WEB').player(self.video_id)
try:
self._visitor_data = innertube_response['responseContext']['visitorData']
except KeyError:
self._visitor_data = innertube_response['responseContext']['serviceTrackingParams'][0]['params'][6]['value']
logger.debug('VisitorData obtained successfully')

return self._visitor_data
Expand Down
6 changes: 5 additions & 1 deletion pytubefix/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ def signature_timestamp(js: str) -> str:
return regex_search(r"signatureTimestamp:(\d*)", js, group=1)


def visitor_data(response_context: str) -> str:
return regex_search(r"visitor_data[',\"\s]+value['\"]:\s?['\"]([a-zA-Z0-9_%-]+)['\"]", response_context, group=1)


def video_id(url: str) -> str:
"""Extract the ``video_id`` from a YouTube url.

Expand Down Expand Up @@ -414,6 +418,7 @@ def apply_po_token(stream_manifest: Dict, vid_info: Dict, po_token: str) -> None
:param str po_token:
Proof of Origin Token.
"""
logger.debug(f'Applying poToken')
for i, stream in enumerate(stream_manifest):
try:
url: str = stream["url"]
Expand All @@ -433,7 +438,6 @@ def apply_po_token(stream_manifest: Dict, vid_info: Dict, po_token: str) -> None
k: v[0] for k, v in query_params.items()
}

logger.debug(f'Applying po_token to itag={stream["itag"]}')
query_params['pot'] = po_token

url = f'{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}?{urlencode(query_params)}'
Expand Down