Skip to content
This repository was archived by the owner on Jun 30, 2022. It is now read-only.

Commit 31dfb19

Browse files
committed
Fix for StreamURLFetcher - Needs to be improved
1 parent 59ce6b1 commit 31dfb19

File tree

3 files changed

+35
-50
lines changed

3 files changed

+35
-50
lines changed

‎youtubesearchpython/core/streamurlfetcher.py‎

Lines changed: 19 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import urllib.request
23

34
from youtubesearchpython.core.requests import RequestCore
@@ -31,21 +32,11 @@ def __init__(self):
3132
Saving videoFormats inside a dictionary with key "player_response" for apply_descrambler & apply_signature methods.
3233
'''
3334
def _getDecipheredURLs(self, videoFormats: dict) -> None:
34-
if not videoFormats['streamingData']:
35-
try:
36-
self.use_oauth = False
37-
self.allow_oauth_cache = False
38-
self.video_id = videoFormats["id"]
39-
self.bypass_age_gate()
40-
r = self._vid_info["streamingData"]
41-
''' Derived from extract.video_info_url_age_restricted '''
42-
''' Google returns content as a query string instead of a JSON. '''
43-
except:
44-
raise Exception('ERROR: Could not make request.')
45-
else:
46-
r = videoFormats["streamingData"]
47-
self._player_response = {'player_response': r}
4835
self.video_id = videoFormats["id"]
36+
self._player_response = videoFormats
37+
url = f"https://www.youtube.com/watch?v={self.video_id}"
38+
self.youtube = pytube.YouTube(url)
39+
4940
self._decipher()
5041

5142
'''
@@ -56,49 +47,36 @@ def _getDecipheredURLs(self, videoFormats: dict) -> None:
5647
Removed v parameter from the query. (No idea about why PyTube bothered with that)
5748
'''
5849
def _getJS(self) -> None:
59-
response = urllib.request.urlopen('https://youtube.com/watch')
60-
watch_html = response.read().decode()
61-
try:
62-
self._js_url = extract.js_url(watch_html)
63-
if pytube.__js_url__ != self._js_url:
64-
response = httpx.get(self._js_url, timeout = None)
65-
self._js = response.text
66-
pytube.__js__ = self._js
67-
pytube.__js_url__ = self._js_url
68-
else:
69-
self._js = pytube.__js__
70-
except:
71-
raise Exception('ERROR: Could not make request.')
72-
73-
async def _asyncGetJS(self):
74-
# Due to some errors with JS fetching with httpx, we are now using sync urllib
75-
self._getJS()
50+
self._js = self.youtube.js
7651

7752
async def getJavaScript(self):
78-
await self._asyncGetJS()
53+
# we don't wanna break compatibility, so we just pass
54+
pass
7955

8056
'''
8157
Not fetching for new player JavaScript if pytube.__js__ is not None or exception is not caused.
8258
'''
8359
def _decipher(self, retry: bool = False):
8460
if not pytube.__js__ or retry:
61+
self.youtube._js = None
62+
self.youtube._js_url = None
63+
pytube.__js__ = None
64+
pytube.__js_url__ = None
8565
self._getJS()
8666
try:
8767
'''
8868
These two are the main methods being used from PyTube.
8969
Used to decipher the stream URLs using player JavaScript & the player_response passed from the getStream method of this derieved class.
9070
These methods operate on the value of "player_response" key in dictionary of self._player_response & save _deciphered information in the "url_encoded_fmt_stream_map" key.
9171
'''
72+
#self._player_response = self.youtube.vid_info
73+
with open("test2.json", "w+", encoding="utf-8") as f:
74+
f.write(json.dumps(self.youtube.vid_info))
9275

93-
stream = apply_descrambler(self._player_response["player_response"])
94-
95-
try:
96-
apply_signature(
97-
stream, self._player_response, pytube.__js__
98-
)
99-
except:
100-
# TODO: Applying signature is randomly failing - not to me, but on GitHub Actions server. I disabled throwing errors, since we don't want a whole mailbox of failed tests...
101-
pass
76+
stream = apply_descrambler(self._player_response["streamingData"])
77+
apply_signature(
78+
stream, self._player_response, pytube.__js__
79+
)
10280
self._streams = stream
10381
except Exception as e:
10482
if retry:

‎youtubesearchpython/core/video.py‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import copy
12
import json
23
from typing import Union, List
34
from urllib.parse import urlencode
@@ -20,7 +21,16 @@ def __init__(self, videoLink: str, componentMode: str, resultMode: int, timeout:
2021
'racyCheckOk': True,
2122
"videoId": getVideoId(self.videoLink)
2223
})
23-
self.data = requestPayload
24+
self.data = {
25+
'context': {
26+
'client': {
27+
'clientName': 'ANDROID',
28+
'clientVersion': '16.20',
29+
'clientScreen': 'EMBED'
30+
}
31+
},
32+
'api_key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
33+
}
2434

2535
def post_request_processing(self):
2636
self.__parseSource()
@@ -46,6 +56,8 @@ def sync_create(self):
4656
def __parseSource(self) -> None:
4757
try:
4858
self.responseSource = json.loads(self.response)
59+
with open("test.json", "w+", encoding="utf-8") as f:
60+
f.write(self.response)
4961
except Exception as e:
5062
raise Exception('ERROR: Could not parse YouTube response.')
5163

@@ -83,10 +95,5 @@ def __getVideoComponent(self, mode: str) -> None:
8395
component['isLiveNow'] = component['isLiveContent'] and component['duration']['secondsText'] == "0"
8496
component['link'] = 'https://www.youtube.com/watch?v=' + component['id']
8597
component['channel']['link'] = 'https://www.youtube.com/channel/' + component['channel']['id']
86-
videoComponent.update(component)
87-
if mode in ['getFormats', None]:
88-
component = {
89-
'streamingData': getValue(self.responseSource, ['streamingData']),
90-
}
91-
videoComponent.update(component)
92-
self.__videoComponent = videoComponent
98+
self.responseSource.update(component)
99+
self.__videoComponent = self.responseSource

‎youtubesearchpython/streamurlfetcher.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class StreamURLFetcher(StreamURLFetcherCore):
2727
'''
2828
def __init__(self):
2929
super().__init__()
30-
self._getJS()
30+
#self._getJS()
3131

3232
def get(self, videoFormats: dict, itag: int) -> Union[str, None]:
3333
'''Gets direct stream URL for a YouTube video fetched using `Video.get` or `Video.getFormats`.

0 commit comments

Comments
 (0)