diff --git a/ythdd_extractor.py b/ythdd_extractor.py index 48eecf1..ba0ed63 100644 --- a/ythdd_extractor.py +++ b/ythdd_extractor.py @@ -343,3 +343,36 @@ def WEBextractSearchResults(search_query: str) -> list: results = safeTraverse(results, ["contents", "twoColumnSearchResultsRenderer", "primaryContents", "sectionListRenderer", "contents", 0, "itemSectionRenderer", "contents"], default=[]) return results + +def WEBgetSearchSuggestions(query: str, previous_query: str = '') -> list: + # Takes in a search query and returns relevant suggestions. + # Can optionally take the previous query but that's rather novel and + # not supported across players nor invidious API itself. + params = { + 'ds': 'yt', + 'hl': 'en', # host language + 'gl': 'us', # geolocation + 'client': 'youtube', + 'gs_ri': 'youtube', + 'q': str(query), # query + 'pq': str(previous_query) if previous_query is not None else '' # previous query + } + + response = requests.get( + 'https://suggestqueries-clients6.youtube.com/complete/search', + params=params, + headers=stage2_headers + ) + # can break anytime but hopefully the tiny speed gain will make up for it + results = response.text[23 + len(query):] + results = results[:results.rfind("{") - 1] + results = json.loads(results) + + suggestions = [] + for result in results: + suggestions.append(result[0]) + + return { + "query": query, + "suggestions": suggestions + } \ No newline at end of file diff --git a/ythdd_inv_tl.py b/ythdd_inv_tl.py index 8a35383..0a36b3b 100644 --- a/ythdd_inv_tl.py +++ b/ythdd_inv_tl.py @@ -642,8 +642,9 @@ def search(data, req): if (data[-2].lower() != "search" or data[-1].lower() != "") and data[-1].lower() != "search": print(f"'{data[-2]}', '{data[-1]}'") - print("search suggestions are not yet supported") - return send(501, {"status": "error", "msg": "search suggestions not supported in this version of ythdd", "data": []}) + previous_query = req.args.get('pq') + suggestions = ythdd_extractor.WEBgetSearchSuggestions(search_query, previous_query) + return send(200, suggestions) results = ythdd_extractor.WEBextractSearchResults(search_query) results_list = []