Fixed broken search for youtube (hopefully)

This commit is contained in:
Christoph Stahl 2024-11-18 13:20:24 +01:00
parent 8144c772f9
commit 838f91d480

View file

@ -30,7 +30,7 @@ class YouTube:
A minimal compatibility layer for the YouTube object of pytube, implemented via yt-dlp A minimal compatibility layer for the YouTube object of pytube, implemented via yt-dlp
""" """
def __init__(self, url: Optional[str] = None): def __init__(self, url: Optional[str] = None, info: Optional[dict[str, Any]] = None):
""" """
Construct a YouTube object from a url. Construct a YouTube object from a url.
@ -45,7 +45,10 @@ class YouTube:
if url is not None: if url is not None:
try: try:
self._infos = YoutubeDL({"quiet": True}).extract_info(url, download=False) if info is not None:
self._infos = info
else:
self._infos = YoutubeDL({"quiet": True}).extract_info(url, download=False)
except DownloadError: except DownloadError:
self.length = 300 self.length = 300
self._title = None self._title = None
@ -94,8 +97,6 @@ class YouTube:
""" """
Construct a YouTube object from yt-dlp search results. Construct a YouTube object from yt-dlp search results.
Updates the cache with the url and the metadata.
:param search_result: The search result from yt-dlp. :param search_result: The search result from yt-dlp.
:type search_result: dict[str, Any] :type search_result: dict[str, Any]
""" """
@ -106,7 +107,7 @@ class YouTube:
# "channel": search_result["channel"], # "channel": search_result["channel"],
# "url": url, # "url": url,
# } # }
return cls(url) return cls(url, info=search_result)
class Search: class Search:
@ -128,9 +129,9 @@ class Search:
:param channel: The channel to search in. :param channel: The channel to search in.
:type channel: Optional[str] :type channel: Optional[str]
""" """
sp = "EgIQAfABAQ==" # This is a magic string, that tells youtube to search for videos sp = "EgIQAQ==" # This is a magic string, that tells youtube to search for videos
if channel is None: if channel is None:
query_url = f"https://youtube.com/results?{urlencode({'search_query': query, 'sp':sp})}" query_url = f"https://youtube.com/results?{urlencode({'search_query': query})}"
else: else:
if channel[0] == "/": if channel[0] == "/":
channel = channel[1:] channel = channel[1:]
@ -141,7 +142,7 @@ class Search:
results = YoutubeDL( results = YoutubeDL(
{ {
"extract_flat": True, "extract_flat": True,
"quiet": True, "quiet": False,
"playlist_items": ",".join(map(str, range(1, 51))), "playlist_items": ",".join(map(str, range(1, 51))),
} }
).extract_info( ).extract_info(