aboutsummaryrefslogtreecommitdiff
path: root/code/utils/source_helpers
diff options
context:
space:
mode:
authorParker <contact@pkrm.dev>2024-12-03 06:05:14 +0000
committerGitHub <noreply@github.com>2024-12-03 06:05:14 +0000
commit15e33831639355546b32477a6870eb0a3ac47e24 (patch)
treea5455e0a8391747c7226a751354b7236c8c5d40b /code/utils/source_helpers
parentfcbfe460701316ded25e29356ed1fda42386e5c0 (diff)
parentce18cd27488d90fbd0aae7319a36a89e9fa85aa7 (diff)
Merge pull request #10 from PacketParker/dev
Update
Diffstat (limited to 'code/utils/source_helpers')
-rw-r--r--code/utils/source_helpers/apple/album.py74
-rw-r--r--code/utils/source_helpers/apple/playlist.py88
-rw-r--r--code/utils/source_helpers/apple/song.py68
-rw-r--r--code/utils/source_helpers/parse.py91
-rw-r--r--code/utils/source_helpers/spotify/album.py68
-rw-r--r--code/utils/source_helpers/spotify/artist.py77
-rw-r--r--code/utils/source_helpers/spotify/playlist.py68
-rw-r--r--code/utils/source_helpers/spotify/song.py63
8 files changed, 597 insertions, 0 deletions
diff --git a/code/utils/source_helpers/apple/album.py b/code/utils/source_helpers/apple/album.py
new file mode 100644
index 0000000..aa4ea0d
--- /dev/null
+++ b/code/utils/source_helpers/apple/album.py
@@ -0,0 +1,74 @@
+import datetime
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the album info from the Apple Music API
+ """
+ album_id = query.split("/album/")[1].split("/")[1]
+
+ try:
+ # Get the album info
+ response = requests.get(
+ f"https://api.music.apple.com/v1/catalog/us/albums/{album_id}",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Album Not Found",
+ description=(
+ "The album could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Apple Music API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the album info
+ album = response.json()
+ name = album["data"][0]["attributes"]["name"]
+ artist = album["data"][0]["attributes"]["artistName"]
+ num_tracks = len(album["data"][0]["relationships"]["tracks"]["data"])
+ except IndexError:
+ LOG.error("Failed unpacking Apple Music album info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Apple Music API")
+ return None, None
+
+ # Extract artwork URL, if available
+ artwork_url = (
+ album["data"][0]["attributes"].get("artwork", {}).get("url", None)
+ )
+ if artwork_url:
+ artwork_url = artwork_url.replace("{w}x{h}", "300x300")
+
+ embed = create_embed(
+ title="Album Queued",
+ description=(
+ f"**{name}** by **{artist}**\n"
+ f"` {num_tracks} ` tracks\n\n"
+ f"Queued by: {user.mention}"
+ ),
+ thumbnail=artwork_url,
+ )
+
+ return album, embed
diff --git a/code/utils/source_helpers/apple/playlist.py b/code/utils/source_helpers/apple/playlist.py
new file mode 100644
index 0000000..65dfbf8
--- /dev/null
+++ b/code/utils/source_helpers/apple/playlist.py
@@ -0,0 +1,88 @@
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the playlist info from the Apple Music API
+ """
+ playlist_id = query.split("/playlist/")[1].split("/")[1]
+ try:
+ # Get all of the tracks in the playlist (limit at 100)
+ response = requests.get(
+ f"https://api.music.apple.com/v1/catalog/us/playlists/{playlist_id}/tracks?limit=100",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Playlist Not Found",
+ description=(
+ "The playlist could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Apple Music API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ playlist = response.json()
+
+ # Get the general playlist info (name, artwork)
+ response = requests.get(
+ f"https://api.music.apple.com/v1/catalog/us/playlists/{playlist_id}",
+ headers=headers,
+ )
+
+ response.raise_for_status()
+ # Unpack the playlist info
+ playlist_info = response.json()
+ name = playlist_info["data"][0]["attributes"]["name"]
+ num_tracks = len(playlist["data"])
+ except IndexError:
+ LOG.error("Failed unpacking Apple Music playlist info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Apple Music API")
+ return None, None
+
+ # Extract artwork URL, if available
+ artwork_url = (
+ playlist_info["data"][0]["attributes"]
+ .get("artwork", {})
+ .get("url", None)
+ )
+ if artwork_url:
+ artwork_url = artwork_url.replace("{w}x{h}", "300x300")
+
+ embed = create_embed(
+ title="Playlist Queued",
+ description=(
+ f"**{name}**\n` {num_tracks} ` tracks\n\nQueued by: {user.mention}"
+ ),
+ thumbnail=artwork_url,
+ )
+
+ # Add small alert if the playlist is the max size
+ if len(playlist["data"]) == 100:
+ embed.description += (
+ "\n\n*This playlist is longer than the 100 song"
+ " maximum. Only the first 100 songs will be"
+ " queued.*"
+ )
+
+ return playlist, embed
diff --git a/code/utils/source_helpers/apple/song.py b/code/utils/source_helpers/apple/song.py
new file mode 100644
index 0000000..4190b63
--- /dev/null
+++ b/code/utils/source_helpers/apple/song.py
@@ -0,0 +1,68 @@
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the song info from the Apple Music API
+ """
+ song_id = query.split("/album/")[1].split("?i=")[1]
+
+ try:
+ # Get the song info
+ response = requests.get(
+ f"https://api.music.apple.com/v1/catalog/us/songs/{song_id}",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Song Not Found",
+ description=(
+ "The song could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Apple Music API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the song info
+ song = response.json()
+ name = song["data"][0]["attributes"]["name"]
+ artist = song["data"][0]["attributes"]["artistName"]
+ except IndexError:
+ LOG.error("Failed unpacking Apple Music song info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Apple Music API")
+ return None, None
+
+ # Extract artwork URL, if available
+ artwork_url = (
+ song["data"][0]["attributes"].get("artwork", {}).get("url", None)
+ )
+ if artwork_url:
+ artwork_url = artwork_url.replace("{w}x{h}", "300x300")
+
+ embed = create_embed(
+ title="Song Queued",
+ description=f"**{name}** by **{artist}**\n\nQueued by {user.mention}",
+ thumbnail=artwork_url,
+ )
+
+ return song, embed
diff --git a/code/utils/source_helpers/parse.py b/code/utils/source_helpers/parse.py
new file mode 100644
index 0000000..b23a895
--- /dev/null
+++ b/code/utils/source_helpers/parse.py
@@ -0,0 +1,91 @@
+import discord
+
+from utils.source_helpers.apple import (
+ album as apple_album,
+ playlist as apple_playlist,
+ song as apple_song,
+)
+from utils.source_helpers.spotify import (
+ album as spotify_album,
+ artist as spotify_artist,
+ playlist as spotify_playlist,
+ song as spotify_song,
+)
+from utils.custom_sources import AppleSource, SpotifySource
+
+
+async def parse_custom_source(
+ self, provider: str, query: str, user: discord.User
+):
+ """
+ Parse the query and run the appropriate functions to get the results/info
+
+ Return the results and an embed or None, None
+ """
+ load_funcs = {
+ "apple": {
+ "album": apple_album.load,
+ "playlist": apple_playlist.load,
+ "song": apple_song.load,
+ },
+ "spotify": {
+ "album": spotify_album.load,
+ "artist": spotify_artist.load,
+ "playlist": spotify_playlist.load,
+ "song": spotify_song.load,
+ },
+ }
+
+ headers = {
+ "apple": self.bot.apple_headers,
+ "spotify": self.bot.spotify_headers,
+ }
+
+ sources = {
+ "apple": AppleSource,
+ "spotify": SpotifySource,
+ }
+ # Catch all songs
+ if "?i=" in query or "/track/" in query:
+ song, embed = await load_funcs[provider]["song"](
+ headers[provider], query, user
+ )
+
+ if song:
+ results = await sources[provider].load_item(self, user, song)
+ else:
+ return None, embed
+ # Catch all playlists
+ elif "/playlist/" in query:
+ playlist, embed = await load_funcs[provider]["playlist"](
+ headers[provider], query, user
+ )
+
+ if playlist:
+ results = await sources[provider].load_playlist(
+ self, user, playlist
+ )
+ else:
+ return None, embed
+ # Catch all albums
+ elif "/album/" in query:
+ album, embed = await load_funcs[provider]["album"](
+ headers[provider], query, user
+ )
+
+ if album:
+ results = await sources[provider].load_album(self, user, album)
+ else:
+ return None, embed
+ # Catch Spotify artists
+ elif "/artist/" in query:
+ artist, embed = await load_funcs[provider]["artist"](
+ headers[provider], query, user
+ )
+
+ if artist:
+ results = await sources[provider].load_artist(self, user, artist)
+ else:
+ return None, embed
+
+ return results, embed
diff --git a/code/utils/source_helpers/spotify/album.py b/code/utils/source_helpers/spotify/album.py
new file mode 100644
index 0000000..0ebc7d5
--- /dev/null
+++ b/code/utils/source_helpers/spotify/album.py
@@ -0,0 +1,68 @@
+import datetime
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the album info from the Spotify API
+ """
+ album_id = query.split("/album/")[1]
+
+ try:
+ # Get the album info
+ response = requests.get(
+ f"https://api.spotify.com/v1/albums/{album_id}",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Album Not Found",
+ description=(
+ "The album could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Spotify API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the album info
+ album = response.json()
+ name = album["name"]
+ artist = album["artists"][0]["name"]
+ num_tracks = len(album["tracks"]["items"])
+ artwork_url = album["images"][0]["url"]
+ except IndexError:
+ LOG.error("Failed unpacking Spotify album info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Spotify API")
+ return None, None
+
+ embed = create_embed(
+ title="Album Queued",
+ description=(
+ f"**{name}** by **{artist}**\n"
+ f"` {num_tracks} ` tracks\n\n"
+ f"Queued by: {user.mention}"
+ ),
+ thumbnail=artwork_url,
+ )
+
+ return album, embed
diff --git a/code/utils/source_helpers/spotify/artist.py b/code/utils/source_helpers/spotify/artist.py
new file mode 100644
index 0000000..995e208
--- /dev/null
+++ b/code/utils/source_helpers/spotify/artist.py
@@ -0,0 +1,77 @@
+import datetime
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the artists top tracks from the Spotify API
+ """
+ artist_id = query.split("/artist/")[1]
+
+ try:
+ # Get the artists songs
+ response = requests.get(
+ f"https://api.spotify.com/v1/artists/{artist_id}/top-tracks",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Artist Not Found",
+ description=(
+ "Either the provided link is malformed, the artist does"
+ " not exist, or the artist does not have any songs."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Spotify API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the artists songs
+ artist = response.json()
+ name = artist["tracks"][0]["artists"][0]["name"]
+ num_tracks = len(artist["tracks"])
+
+ # Get the artist info (for the thumbnail)
+ response = requests.get(
+ f"https://api.spotify.com/v1/artists/{artist_id}",
+ headers=headers,
+ )
+
+ response.raise_for_status()
+ try:
+ artwork_url = response.json()["images"][0]["url"]
+ except IndexError:
+ artwork_url = None
+
+ except IndexError:
+ LOG.error("Failed unpacking Spotify artist info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Spotify API")
+ return None, None
+
+ embed = create_embed(
+ title="Artist Queued",
+ description=(
+ f"Top `{num_tracks}` track by **{name}**\n\n"
+ f"Queued by {user.mention}"
+ ),
+ thumbnail=artwork_url,
+ )
+ return artist, embed
diff --git a/code/utils/source_helpers/spotify/playlist.py b/code/utils/source_helpers/spotify/playlist.py
new file mode 100644
index 0000000..7ca9c6a
--- /dev/null
+++ b/code/utils/source_helpers/spotify/playlist.py
@@ -0,0 +1,68 @@
+import datetime
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the playlist info from the Spotify API
+ """
+ playlist_id = query.split("/playlist/")[1]
+
+ try:
+ # Get the playlist info
+ response = requests.get(
+ f"https://api.spotify.com/v1/playlists/{playlist_id}",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Playlist Not Found",
+ description=(
+ "The playlist could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Spotify API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the playlist info
+ playlist = response.json()
+ name = playlist["name"]
+ owner = playlist["owner"]["display_name"]
+ num_tracks = len(playlist["tracks"]["items"])
+ artwork_url = playlist["images"][0]["url"]
+ except IndexError:
+ LOG.error("Failed unpacking Spotify playlist info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Spotify API")
+ return None, None
+
+ embed = create_embed(
+ title="Playlist Queued",
+ description=(
+ f"**{name}** from **{owner}**\n"
+ f"` {num_tracks} ` tracks\n\n"
+ f"Queued by {user.mention}"
+ ),
+ thumbnail=artwork_url,
+ )
+
+ return playlist, embed
diff --git a/code/utils/source_helpers/spotify/song.py b/code/utils/source_helpers/spotify/song.py
new file mode 100644
index 0000000..b0c7379
--- /dev/null
+++ b/code/utils/source_helpers/spotify/song.py
@@ -0,0 +1,63 @@
+import datetime
+import discord
+import requests
+from typing import Tuple, Optional
+from requests.exceptions import JSONDecodeError
+
+from utils.config import create_embed, LOG
+
+
+async def load(
+ headers: dict,
+ query: str,
+ user: discord.User,
+) -> Tuple[Optional[dict], Optional[discord.Embed]]:
+ """
+ Get the song info from the Spotify API
+ """
+ song_id = query.split("/track/")[1]
+
+ try:
+ # Get the song info
+ response = requests.get(
+ f"https://api.spotify.com/v1/tracks/{song_id}",
+ headers=headers,
+ )
+
+ if response.status_code == 404:
+ embed = create_embed(
+ title="Song Not Found",
+ description=(
+ "The song could not be found as the provided link is"
+ " invalid. Please try again."
+ ),
+ )
+ return None, embed
+
+ if response.status_code == 401:
+ LOG.error(
+ "Could not authorize with Spotify API. Likely need to"
+ " restart the bot."
+ )
+ return None, None
+
+ response.raise_for_status()
+ # Unpack the song info
+ song = response.json()
+ name = song["name"]
+ artist = song["artists"][0]["name"]
+ artwork_url = song["album"]["images"][0]["url"]
+ except IndexError:
+ LOG.error("Failed unpacking Spotify song info")
+ return None, None
+ except (JSONDecodeError, requests.HTTPError):
+ LOG.error("Failed making request to Spotify API")
+ return None, None
+
+ embed = create_embed(
+ title="Song Queued",
+ description=f"**{name}** by **{artist}**\n\nQueued by {user.mention}",
+ thumbnail=artwork_url,
+ )
+
+ return song, embed