diff --git a/defs.py b/defs.py index b74a817..2045d7a 100644 --- a/defs.py +++ b/defs.py @@ -1,4 +1,6 @@ class Music: - def __init__(self, name: str, album: str): + def __init__(self, name: str, album: str, artist: str = ""): self.name = name self.album = album + self.artist = artist + self.name = f"{self.artist} - {self.name}" if self.artist else self.name diff --git a/main.py b/main.py index 3364c57..f54b195 100644 --- a/main.py +++ b/main.py @@ -7,6 +7,7 @@ app = FastAPI() @app.get('/search') async def search( *, + service: str = "apple", keyword: str = Query(..., title="The name of a song") ): - return await get_music(keyword) + return await get_music(service, keyword) diff --git a/services/apple.py b/services/apple.py index e132fac..30706fe 100644 --- a/services/apple.py +++ b/services/apple.py @@ -22,5 +22,5 @@ class Apple: results = [] for i in req["results"]: with contextlib.suppress(Exception): - results.append(Music(i["trackName"], i["artworkUrl100"])) + results.append(Music(i["trackName"], i["artworkUrl100"], i["artistName"])) return results diff --git a/utils.py b/utils.py index e171868..7f146de 100644 --- a/utils.py +++ b/utils.py @@ -15,14 +15,23 @@ def parse_data(data: List[Music]) -> dict: return {"resultCount": length, "results": results} -async def get_music(keyword: str) -> dict: +async def get_music(service: str, keyword: str) -> dict: if not keyword: return default_data with contextlib.suppress(Exception): apple_result = await apple.Apple.get(keyword) - if apple_result: - return parse_data(apple_result) - netease_result = await netease.Netease.get(keyword) - if netease_result: - return parse_data(netease_result) + if service == "apple": + if apple_result: + return parse_data(apple_result) + netease_result = await netease.Netease.get(keyword) + if netease_result: + return parse_data(netease_result) + else: + if apple_result and apple_result[0].name == keyword: + return parse_data(apple_result) + netease_result = await netease.Netease.get(keyword) + if netease_result: + return parse_data(netease_result) + if apple_result: + return parse_data(apple_result) return default_data