Skip to content

Commit 9504243

Browse files
committed
Cleanup
1 parent 11d8887 commit 9504243

33 files changed

+153
-123
lines changed

.vscode/settings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@
1111
"--disable=too-few-public-methods",
1212
"--disable=too-many-return-statements",
1313
"--disable=too-many-branches"
14-
]
14+
],
15+
"editor.formatOnSave": true
1516
}

bot/cogs/debug.py renamed to bot/cogs/debug/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from nextcord.ext import application_checks
99
from nextcord.ext.commands import Cog
1010

11-
from bot.dataclass.custom_embed import CustomEmbed
11+
from bot.models.custom_embed import CustomEmbed
1212
from bot.utils.embeds import create_success_embed
1313
from bot.utils.logger import create_logger
1414
from bot.utils.paginator import Paginator

bot/cogs/player/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from nextcord.ext.commands import Cog
2424
from requests import HTTPError, codes
2525

26-
from bot.dataclass.custom_embed import CustomEmbed
26+
from bot.models.custom_embed import CustomEmbed
2727
from bot.utils.constants import RELEASE, SPOTIFY_403_ERR_MSG
2828
from bot.utils.embeds import create_error_embed, create_success_embed
2929
from bot.utils.exceptions import (
@@ -42,7 +42,7 @@
4242
from .jockey import Jockey
4343

4444
if TYPE_CHECKING:
45-
from bot.dataclass.queue_item import QueueItem
45+
from bot.models.queue_item import QueueItem
4646
from bot.utils.blanco import BlancoBot
4747

4848

bot/cogs/player/lavalink_client.py renamed to bot/cogs/player/helpers/lavalink_search.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from mafic import Playlist, SearchType, TrackLoadException
1010

11-
from bot.dataclass.lavalink_result import LavalinkResult
11+
from bot.models.lavalink_result import LavalinkResult
1212
from bot.utils.constants import BLACKLIST
1313
from bot.utils.exceptions import LavalinkSearchError
1414
from bot.utils.fuzzy import check_similarity

bot/cogs/player/track_finder.py renamed to bot/cogs/player/helpers/lavalink_track.py

Lines changed: 63 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
1+
"""
2+
Lavalink track helpers, which take care of finding a matching
3+
playable Lavalink track for a QueueItem, caching it, and
4+
invalidating it when necessary.
5+
"""
6+
17
from typing import TYPE_CHECKING, List, Optional, Tuple
28

39
from mafic import SearchType
410

511
from bot.database.redis import REDIS
612
from bot.utils.constants import CONFIDENCE_THRESHOLD
713
from bot.utils.exceptions import LavalinkSearchError
14+
from bot.utils.fuzzy import rank_results
815
from bot.utils.logger import create_logger
916
from bot.utils.musicbrainz import annotate_track
1017

11-
from .jockey_helpers import rank_results
12-
from .lavalink_client import get_deezer_matches, get_deezer_track, get_youtube_matches
18+
from .lavalink_search import get_deezer_matches, get_deezer_track, get_youtube_matches
1319

1420
if TYPE_CHECKING:
1521
from mafic import Node, Track
1622

17-
from bot.dataclass.lavalink_result import LavalinkResult
18-
from bot.dataclass.queue_item import QueueItem
23+
from bot.models.lavalink_result import LavalinkResult
24+
from bot.models.queue_item import QueueItem
1925

20-
from .lavalink_client import LavalinkSearchError
26+
from .lavalink_search import LavalinkSearchError
2127

2228
LOGGER = create_logger('track_finder')
2329

@@ -112,19 +118,36 @@ async def find_lavalink_track(
112118
return lavalink_track
113119

114120

121+
def invalidate_cached_track(item: 'QueueItem'):
122+
"""
123+
Removes a cached Lavalink track from Redis.
124+
125+
:param item: The QueueItem to invalidate the track for.
126+
"""
127+
if REDIS is None:
128+
return
129+
130+
redis_key, redis_key_type = _determine_cache_key(item)
131+
132+
# Invalidate cached Lavalink track
133+
if redis_key is not None and redis_key_type is not None:
134+
REDIS.invalidate_lavalink_track(redis_key, key_type=redis_key_type)
135+
else:
136+
LOGGER.warning("Could not invalidate cached track for `%s': no key", item.title)
137+
138+
115139
def _get_cached_track(
116140
item: 'QueueItem',
117141
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
118-
redis_key = None
119-
redis_key_type = None
120-
if item.spotify_id is not None:
121-
redis_key = item.spotify_id
122-
redis_key_type = 'spotify_id'
123-
elif item.isrc is not None:
124-
redis_key = item.isrc
125-
redis_key_type = 'isrc'
142+
"""
143+
Gets a cached Lavalink track from Redis.
144+
145+
:param item: The QueueItem to get the cached track for.
146+
"""
126147

148+
redis_key, redis_key_type = _determine_cache_key(item)
127149
cached = None
150+
128151
if REDIS is not None and redis_key is not None and redis_key_type is not None:
129152
cached = REDIS.get_lavalink_track(redis_key, key_type=redis_key_type)
130153

@@ -136,10 +159,37 @@ def _set_cached_track(
136159
key: Optional[str] = None,
137160
key_type: Optional[str] = None,
138161
):
162+
"""
163+
Caches a Lavalink track in Redis.
164+
165+
:param lavalink_track: The Lavalink track to cache.
166+
:param key: The key to cache the track under.
167+
:param key_type: The type of key to cache the track under.
168+
"""
139169
if REDIS is not None and key_type is not None and key is not None:
140170
REDIS.set_lavalink_track(key, lavalink_track, key_type=key_type)
141171

142172

173+
def _determine_cache_key(item: 'QueueItem') -> Tuple[Optional[str], Optional[str]]:
174+
"""
175+
Determines the Redis key and key type for caching a Lavalink track.
176+
177+
:param item: The QueueItem to determine the cache key for.
178+
"""
179+
180+
redis_key = None
181+
redis_key_type = None
182+
183+
if item.spotify_id is not None:
184+
redis_key = item.spotify_id
185+
redis_key_type = 'spotify_id'
186+
elif item.isrc is not None:
187+
redis_key = item.isrc
188+
redis_key_type = 'isrc'
189+
190+
return redis_key, redis_key_type
191+
192+
143193
async def _append_deezer_results_for_isrc(
144194
results: List['LavalinkResult'],
145195
node: 'Node',

bot/cogs/player/jockey_helpers.py renamed to bot/cogs/player/helpers/parsers.py

Lines changed: 6 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
"""
2-
Helper functions for the music player.
2+
Playback query parsers for the Player cog.
33
"""
44

5-
from typing import TYPE_CHECKING, List, Tuple, TypeVar
5+
from typing import TYPE_CHECKING, List
66

77
from mafic import SearchType
88
from requests.status_codes import codes
99
from spotipy.exceptions import SpotifyException
1010

11-
from bot.database.redis import REDIS
12-
from bot.dataclass.queue_item import QueueItem
11+
from bot.models.queue_item import QueueItem
1312
from bot.utils.constants import CONFIDENCE_THRESHOLD
1413
from bot.utils.exceptions import (
1514
JockeyException,
1615
LavalinkInvalidIdentifierError,
1716
SpotifyNoResultsError,
1817
)
19-
from bot.utils.fuzzy import check_similarity_weighted
18+
from bot.utils.fuzzy import rank_results
2019
from bot.utils.logger import create_logger
2120
from bot.utils.spotify_client import Spotify
2221
from bot.utils.url import (
@@ -32,85 +31,17 @@
3231
get_ytlistid_from_url,
3332
)
3433

35-
from .lavalink_client import (
34+
from .lavalink_search import (
3635
get_soundcloud_matches,
3736
get_youtube_matches,
3837
)
3938

4039
if TYPE_CHECKING:
4140
from mafic import Node
4241

43-
from bot.dataclass.spotify import SpotifyTrack
42+
from bot.models.spotify import SpotifyTrack
4443

4544
LOGGER = create_logger('jockey_helpers')
46-
T = TypeVar('T')
47-
48-
49-
def rank_results(
50-
query: str, results: List[T], result_type: SearchType
51-
) -> List[Tuple[T, int]]:
52-
"""
53-
Ranks search results based on similarity to a fuzzy query.
54-
55-
:param query: The query to check against.
56-
:param results: The results to rank. Can be mafic.Track, dataclass.SpotifyTrack,
57-
or any object with a title and author string attribute.
58-
:param result_type: The type of result. See ResultType.
59-
:return: A list of tuples containing the result and its similarity to the query.
60-
"""
61-
# Rank results
62-
similarities = [
63-
check_similarity_weighted(
64-
query,
65-
f'{result.title} {result.author}', # type: ignore
66-
int(100 * (0.8**i)),
67-
)
68-
for i, result in enumerate(results)
69-
]
70-
ranked = sorted(zip(results, similarities), key=lambda x: x[1], reverse=True)
71-
72-
# Print confidences for debugging
73-
type_name = 'YouTube'
74-
if result_type == SearchType.SPOTIFY_SEARCH:
75-
type_name = 'Spotify'
76-
elif result_type == SearchType.DEEZER_SEARCH:
77-
type_name = 'Deezer'
78-
LOGGER.debug('%s results and confidences for "%s":', type_name, query)
79-
for result, confidence in ranked:
80-
LOGGER.debug(
81-
' %3d %-20s %-25s',
82-
confidence,
83-
result.author[:20], # type: ignore
84-
result.title[:25], # type: ignore
85-
)
86-
87-
return ranked
88-
89-
90-
def invalidate_lavalink_track(item: QueueItem):
91-
"""
92-
Removes a cached Lavalink track from Redis.
93-
94-
:param item: The QueueItem to invalidate the track for.
95-
"""
96-
if REDIS is None:
97-
return
98-
99-
# Determine key type
100-
redis_key = None
101-
redis_key_type = None
102-
if item.spotify_id is not None:
103-
redis_key = item.spotify_id
104-
redis_key_type = 'spotify_id'
105-
elif item.isrc is not None:
106-
redis_key = item.isrc
107-
redis_key_type = 'isrc'
108-
109-
# Invalidate cached Lavalink track
110-
if redis_key is not None and redis_key_type is not None:
111-
REDIS.invalidate_lavalink_track(redis_key, key_type=redis_key_type)
112-
else:
113-
LOGGER.warning("Could not invalidate cached track for `%s': no key", item.title)
11445

11546

11647
async def parse_query(

bot/cogs/player/queue.py renamed to bot/cogs/player/helpers/queue_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from random import shuffle
66
from typing import TYPE_CHECKING, List, Tuple
77

8-
from bot.dataclass.queue_item import QueueItem
8+
from bot.models.queue_item import QueueItem
99
from bot.utils.exceptions import EmptyQueueError, EndOfQueueError
1010
from bot.utils.logger import create_logger
1111

bot/cogs/player/scrobbler.py renamed to bot/cogs/player/helpers/scrobble_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
if TYPE_CHECKING:
1010
from nextcord.abc import Connectable
1111

12-
from bot.dataclass.queue_item import QueueItem
12+
from bot.models.queue_item import QueueItem
1313
from bot.utils.blanco import BlancoBot
1414

1515

bot/cogs/player/jockey.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
VoiceChannel,
1818
)
1919

20-
from bot.dataclass.custom_embed import CustomEmbed
20+
from bot.models.custom_embed import CustomEmbed
2121
from bot.utils.constants import UNPAUSE_THRESHOLD
2222
from bot.utils.embeds import create_error_embed
2323
from bot.utils.exceptions import (
@@ -31,17 +31,17 @@
3131
from bot.utils.time import human_readable_time
3232
from bot.views.now_playing import NowPlayingView
3333

34-
from .jockey_helpers import invalidate_lavalink_track, parse_query
35-
from .queue import QueueManager
36-
from .scrobbler import ScrobbleHandler
37-
from .track_finder import find_lavalink_track
34+
from .helpers.lavalink_track import find_lavalink_track, invalidate_cached_track
35+
from .helpers.parsers import parse_query
36+
from .helpers.queue_manager import QueueManager
37+
from .helpers.scrobble_handler import ScrobbleHandler
3838

3939
if TYPE_CHECKING:
4040
from mafic import Track
4141
from nextcord import Embed
4242
from nextcord.abc import Connectable, Messageable
4343

44-
from bot.dataclass.queue_item import QueueItem
44+
from bot.models.queue_item import QueueItem
4545
from bot.utils.blanco import BlancoBot
4646

4747

@@ -241,7 +241,7 @@ async def _play(self, item: 'QueueItem', position: Optional[int] = None):
241241
wait_time += 0.1
242242

243243
# Remove cached Lavalink track and try again
244-
invalidate_lavalink_track(item)
244+
invalidate_cached_track(item)
245245
has_retried = True
246246
else:
247247
# Clear pause timestamp for new track

bot/database/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import sqlite3 as sql
66
from typing import List, Optional
77

8-
from bot.dataclass.oauth import LastfmAuth, OAuth
8+
from bot.models.oauth import LastfmAuth, OAuth
99
from bot.utils.logger import create_logger
1010

1111
from .migrations import run_migrations

0 commit comments

Comments
 (0)