Skip to content

Commit 1da1967

Browse files
committed
Minor improvements for remove search suggestions
1 parent 2d52e04 commit 1da1967

File tree

3 files changed

+31
-46
lines changed

3 files changed

+31
-46
lines changed

tests/mixins/test_search.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,25 +117,25 @@ def test_search_library(self, config, yt_oauth):
117117
yt_oauth.search("beatles", filter="featured_playlists", scope="library", limit=40)
118118

119119
def test_remove_suggestion_valid(self, yt_auth):
120-
first_pass = yt_auth.search("b")
120+
first_pass = yt_auth.search("b") # Populate the suggestion history
121121
assert len(first_pass) > 0, "Search returned no results"
122122

123-
results = yt_auth.get_search_suggestions("b", detailed_runs=True)
123+
results, feedback_tokens = yt_auth.get_search_suggestions("b", detailed_runs=True)
124124
assert len(results) > 0, "No search suggestions returned"
125125
assert any(item.get("fromHistory") for item in results), "No suggestions from history found"
126126

127-
suggestion_to_remove = 1
128-
response = yt_auth.remove_search_suggestion(suggestion_to_remove)
127+
suggestion_to_remove = 0
128+
response = yt_auth.remove_search_suggestion(suggestion_to_remove, feedback_tokens)
129129
assert response is True, "Failed to remove search suggestion"
130130

131131
def test_remove_suggestion_invalid_number(self, yt_auth):
132132
first_pass = yt_auth.search("a")
133133
assert len(first_pass) > 0, "Search returned no results"
134134

135-
results = yt_auth.get_search_suggestions("a", detailed_runs=True)
135+
results, feedback_tokens = yt_auth.get_search_suggestions("a", detailed_runs=True)
136136
assert len(results) > 0, "No search suggestions returned"
137137
assert any(item.get("fromHistory") for item in results), "No suggestions from history found"
138138

139139
suggestion_to_remove = 99
140-
response = yt_auth.remove_search_suggestion(suggestion_to_remove)
140+
response = yt_auth.remove_search_suggestion(suggestion_to_remove, feedback_tokens)
141141
assert response is False

ytmusicapi/mixins/search.py

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@
77

88

99
class SearchMixin(MixinProtocol):
10-
def __init__(self):
11-
self._latest_suggestions = None
12-
self._latest_feedback_tokens = None
13-
1410
def search(
1511
self,
1612
query: str,
@@ -262,7 +258,7 @@ def parse_func(contents):
262258

263259
return search_results
264260

265-
def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[str], list[dict]]:
261+
def get_search_suggestions(self, query: str, detailed_runs=False) -> tuple[Union[list[str], list[dict]], dict[int, str]]:
266262
"""
267263
Get Search Suggestions
268264
@@ -272,7 +268,10 @@ def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[
272268
suggestion along with the complete text (like many search services
273269
usually bold the text typed by the user).
274270
Default: False, returns the list of search suggestions in plain text.
275-
:return: List of search suggestion results depending on ``detailed_runs`` param.
271+
:return: A tuple containing:
272+
- A list of search suggestions. If ``detailed_runs`` is False, it returns plain text suggestions.
273+
If ``detailed_runs`` is True, it returns a list of dictionaries with detailed information.
274+
- A dictionary of feedback tokens that can be used to remove suggestions later.
276275
277276
Example response when ``query`` is 'fade' and ``detailed_runs`` is set to ``False``::
278277
@@ -300,7 +299,7 @@ def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[
300299
"text": "d"
301300
}
302301
],
303-
"number": 1
302+
"index": 0
304303
},
305304
{
306305
"text": "faded alan walker lyrics",
@@ -313,7 +312,7 @@ def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[
313312
"text": "d alan walker lyrics"
314313
}
315314
],
316-
"number": 2
315+
"index": 1
317316
},
318317
{
319318
"text": "faded alan walker",
@@ -326,7 +325,7 @@ def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[
326325
"text": "d alan walker"
327326
}
328327
],
329-
"number": 3
328+
"index": 2
330329
},
331330
...
332331
]
@@ -340,36 +339,33 @@ def get_search_suggestions(self, query: str, detailed_runs=False) -> Union[list[
340339
feedback_tokens: dict[int, str] = {}
341340
search_suggestions = parse_search_suggestions(response, detailed_runs, feedback_tokens)
342341

343-
# Store the suggestions and feedback tokens for later use
344-
self._latest_suggestions = search_suggestions
345-
self._latest_feedback_tokens = feedback_tokens
346-
347-
return search_suggestions
342+
return search_suggestions, feedback_tokens
348343

349-
def remove_search_suggestion(self, number: int) -> bool:
344+
def remove_search_suggestion(self, index: int, feedback_tokens: dict[int, str]) -> bool:
350345
"""
351346
Remove a search suggestion from the user search history based on the number displayed next to it.
352347
353-
:param number: The number of the suggestion to be removed.
348+
:param index: The number of the suggestion to be removed.
354349
This number is displayed when the `detailed_runs` and `display_numbers` parameters are set to True
355350
in the `get_search_suggestions` method.
351+
:param feedback_tokens: A dictionary containing feedback tokens for each suggestion.
352+
This dictionary is obtained from the `get_search_suggestions` method.
356353
:return: True if the operation was successful, False otherwise.
357354
358-
Example usage:
355+
Example usage::
359356
360-
# Assuming you want to remove suggestion number 1
361-
success = ytmusic.remove_search_suggestion(number=1)
357+
# Assuming you want to remove suggestion number 0
358+
suggestions, feedback_tokens = ytmusic.get_search_suggestions(query="fade", detailed_runs=True)
359+
success = ytmusic.remove_search_suggestion(index=0, feedback_tokens=feedback_tokens)
362360
if success:
363361
print("Suggestion removed successfully")
364362
else:
365363
print("Failed to remove suggestion")
366364
"""
367-
if self._latest_suggestions is None or self._latest_feedback_tokens is None:
368-
raise ValueError(
369-
"No suggestions available. Please run get_search_suggestions first to retrieve suggestions."
370-
)
371-
372-
feedback_token = self._latest_feedback_tokens.get(number)
365+
if not feedback_tokens:
366+
raise YTMusicUserError("No feedback tokens provided. Please run get_search_suggestions first to retrieve suggestions.")
367+
368+
feedback_token = feedback_tokens.get(index)
373369

374370
if not feedback_token:
375371
return False
@@ -379,7 +375,4 @@ def remove_search_suggestion(self, number: int) -> bool:
379375

380376
response = self._send_request(endpoint, body)
381377

382-
if "feedbackResponses" in response and response["feedbackResponses"][0].get("isProcessed", False):
383-
return True
384-
385-
return False
378+
return bool(nav(response, ["feedbackResponses", 0, "isProcessed"], none_if_absent=True))

ytmusicapi/parsers/search.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
UNIQUE_RESULT_TYPES = ["artist", "playlist", "song", "video", "station", "profile", "podcast", "episode"]
66
ALL_RESULT_TYPES = ["album", *UNIQUE_RESULT_TYPES]
7-
FEEDBACK_TOKENS: dict[int, str] = {}
87

98

109
def get_search_result_type(result_type_local, result_types_local):
@@ -265,8 +264,7 @@ def parse_search_suggestions(results, detailed_runs, feedback_tokens):
265264
raw_suggestions = results["contents"][0]["searchSuggestionsSectionRenderer"]["contents"]
266265
suggestions = []
267266

268-
count = 1 # Used for deleting a search suggestion
269-
for raw_suggestion in raw_suggestions:
267+
for index, raw_suggestion in enumerate(raw_suggestions):
270268
if "historySuggestionRenderer" in raw_suggestion:
271269
suggestion_content = raw_suggestion["historySuggestionRenderer"]
272270
from_history = True
@@ -276,7 +274,7 @@ def parse_search_suggestions(results, detailed_runs, feedback_tokens):
276274

277275
# Store the feedback token in the provided dictionary if it exists
278276
if feedback_token:
279-
feedback_tokens[count] = feedback_token
277+
feedback_tokens[index] = feedback_token
280278
else:
281279
suggestion_content = raw_suggestion["searchSuggestionRenderer"]
282280
from_history = False
@@ -285,14 +283,8 @@ def parse_search_suggestions(results, detailed_runs, feedback_tokens):
285283
runs = suggestion_content["suggestion"]["runs"]
286284

287285
if detailed_runs:
288-
suggestions.append({"text": text, "runs": runs, "fromHistory": from_history, "number": count})
286+
suggestions.append({"text": text, "runs": runs, "fromHistory": from_history, "index": index})
289287
else:
290288
suggestions.append(text)
291289

292-
count += 1
293-
294290
return suggestions
295-
296-
297-
def get_feedback_token(suggestion_number):
298-
return FEEDBACK_TOKENS.get(suggestion_number)

0 commit comments

Comments
 (0)