Fixed issue #13

This commit is contained in:
DraftKinner 2025-03-23 14:16:14 -04:00
parent cf06b40afc
commit 83f56b0cac
2 changed files with 103 additions and 41 deletions

View file

@ -252,6 +252,7 @@ class ApiClient(LibrespotApiClient):
params: dict[str, Any] = {}, params: dict[str, Any] = {},
limit: int = 20, limit: int = 20,
offset: int = 0, offset: int = 0,
raw_url: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
Requests data from API Requests data from API
@ -269,10 +270,13 @@ class ApiClient(LibrespotApiClient):
"Accept-Language": self.__session.language(), "Accept-Language": self.__session.language(),
"app-platform": "WebPlayer", "app-platform": "WebPlayer",
} }
if not raw_url:
params["limit"] = limit params["limit"] = limit
params["offset"] = offset params["offset"] = offset
response = get(API_URL + url, headers=headers, params=params) response = get(API_URL + url, headers=headers, params=params)
else:
response = get(url, headers=headers)
data = response.json() data = response.json()
try: try:

View file

@ -44,7 +44,10 @@ class Selection:
"episode", "episode",
], ],
) -> list[str]: ) -> list[str]:
offset = 0
categories = ",".join(category) categories = ",".join(category)
ids = []
while True:
with Loader("Searching..."): with Loader("Searching..."):
country = self.__session.api().invoke_url("me")["country"] country = self.__session.api().invoke_url("me")["country"]
resp = self.__session.api().invoke_url( resp = self.__session.api().invoke_url(
@ -56,14 +59,17 @@ class Selection:
"market": country, "market": country,
}, },
limit=10, limit=10,
offset=0, offset=offset,
) )
print(f'Search results for "{search_text}"') print(f'Search results for "{search_text}"')
count = 0 count = 0
next_page = {}
self.__items = []
for cat in categories.split(","): for cat in categories.split(","):
label = cat + "s" label = cat + "s"
items = resp[label]["items"] items = resp[label]["items"]
next_page[label] = resp[label]["next"]
if len(items) > 0: if len(items) > 0:
print(f"\n{label.capitalize()}:") print(f"\n{label.capitalize()}:")
try: try:
@ -72,15 +78,39 @@ class Selection:
self.__print(count, items, "name") self.__print(count, items, "name")
count += len(items) count += len(items)
self.__items.extend(items) self.__items.extend(items)
return self.__get_selection()
for id in self.__get_selection(allow_empty=True):
ids.append(id)
next_flag = False
for page in next_page.values():
if page is not None and next_flag is False:
next_flag = True
params = page.split("?", 1)[1]
page_offset = int(params.split("&")[0].split("=")[1])
offset = page_offset
break
if not next_flag:
break
get_next = self.__get_next_prompt()
if get_next.lower() == "n":
break
return ids
def get(self, category: str, name: str = "", content: str = "") -> list[str]: def get(self, category: str, name: str = "", content: str = "") -> list[str]:
with Loader("Fetching items..."): with Loader("Fetching items..."):
r = self.__session.api().invoke_url(f"me/{category}", limit=50) r = self.__session.api().invoke_url(f"me/{category}", limit=50)
ids = []
while True:
if content != "": if content != "":
r = r[content] r = r[content]
resp = r["items"] resp = r["items"]
self.__items = []
for i in range(len(resp)): for i in range(len(resp)):
try: try:
item = resp[i][name] item = resp[i][name]
@ -88,20 +118,38 @@ class Selection:
item = resp[i] item = resp[i]
self.__items.append(item) self.__items.append(item)
print( print(
"{:<2} {:<38}".format(i + 1, self.__fix_string_length(item["name"], 38)) "{:<2} {:<38}".format(
i + 1, self.__fix_string_length(item["name"], 38)
) )
return self.__get_selection() )
for id in self.__get_selection():
ids.append(id)
if r["next"] is None:
break
get_next = self.__get_next_prompt()
if get_next.lower() == "n":
break
with Loader("Fetching items..."):
r = self.__session.api().invoke_url(r["next"], raw_url=True)
return ids
@staticmethod @staticmethod
def from_file(file_path: Path) -> list[str]: def from_file(file_path: Path) -> list[str]:
with open(file_path, "r", encoding="utf-8") as f: with open(file_path, "r", encoding="utf-8") as f:
return [line.strip() for line in f.readlines()] return [line.strip() for line in f.readlines()]
def __get_selection(self) -> list[str]: def __get_selection(self, allow_empty: bool = False) -> list[str]:
print("\nResults to save (eg: 1,2,5 1-3)") print("\nResults to save (eg: 1,2,5 1-3)")
selection = "" selection = ""
while len(selection) == 0: while len(selection) == 0:
selection = input("==> ") selection = input("==> ")
if len(selection) == 0 and allow_empty:
return []
ids = [] ids = []
selections = selection.split(",") selections = selection.split(",")
for i in selections: for i in selections:
@ -149,6 +197,16 @@ class Selection:
return text[: max_length - 3] + "..." return text[: max_length - 3] + "..."
return text return text
def __get_next_prompt(self) -> str:
print("\nGet next page? Y/n")
get_next = None
while get_next not in ["Y", "y", "N", "n"]:
get_next = input("==> ")
if len(get_next) == 0:
get_next = "y"
return get_next
class App: class App:
def __init__(self, args: Namespace): def __init__(self, args: Namespace):