From 6eb472d7741dffcf946a99ff2717f08943828df1 Mon Sep 17 00:00:00 2001 From: Crussader <75786691+Crussader@users.noreply.github.com> Date: Sat, 30 Oct 2021 17:09:20 +0400 Subject: [PATCH] Update pool.py --- pomice/pool.py | 167 +++++++++++++++++++------------------------------ 1 file changed, 63 insertions(+), 104 deletions(-) diff --git a/pomice/pool.py b/pomice/pool.py index ff266fa..648f7d4 100644 --- a/pomice/pool.py +++ b/pomice/pool.py @@ -6,11 +6,10 @@ import random import re import socket import time -from typing import Dict, Optional, TYPE_CHECKING, Union +from typing import Dict, Optional, TYPE_CHECKING from urllib.parse import quote import aiohttp -import discord from discord.ext import commands from . import __version__, spotify @@ -21,18 +20,10 @@ from .exceptions import ( NodeCreationError, NodeNotAvailable, NoNodesAvailable, - SpotifyAlbumLoadFailed, - SpotifyPlaylistLoadFailed, - SpotifyTrackLoadFailed, TrackLoadError ) from .objects import Playlist, Track -from .utils import ( - ClientType, - ExponentialBackoff, - NodeStats, - NodeAlgorithms, -) +from .utils import ClientType, ExponentialBackoff, NodeStats if TYPE_CHECKING: from .player import Player @@ -42,10 +33,12 @@ SPOTIFY_URL_REGEX = re.compile( ) DISCORD_MP3_URL_REGEX = re.compile( - r"https?://cdn.discordapp.com/attachments/(?P[0-9]+)/(?P[0-9]+)/(?P[a-zA-Z0-9_.]+)+" + r"https?://cdn.discordapp.com/attachments/(?P[0-9]+)/" + r"(?P[0-9]+)/(?P[a-zA-Z0-9_.]+)+" ) + URL_REGEX = re.compile( - r'https?://(?:www\.)?.+' + r"https?://(?:www\.)?.+" ) @@ -210,8 +203,9 @@ class Node: async def send(self, **data): if not self._available: raise NodeNotAvailable( - f"The node '{self.identifier}' is not currently available.") - + f"The node '{self.identifier}' is unavailable." + ) + await self._websocket.send_str(json.dumps(data)) def get_player(self, guild_id: int): @@ -261,24 +255,23 @@ class Node: ) -> Track: """ Builds a track using a valid track identifier - You can also pass in a discord.py Context object to get a Context object on the track it builds. """ - async with self._session.get(f'{self._rest_uri}/decodetrack?', - headers={'Authorization': self._password}, - params={'track': identifier}) as resp: - - data: dict = await resp.json() - + async with self._session.get( + f"{self._rest_uri}/decodetrack?", + headers={"Authorization": self._password}, + params={"track": identifier} + ) as resp: if not resp.status == 200: - raise TrackLoadError(f'Failed to build track. Status: {data["status"]}, Error: {data["error"]}.' - f'Check the identifier is correct and try again.') + raise TrackLoadError( + f"Failed to build track. Check the identifier is correct and try again." + ) + data: dict = await resp.json() return Track(track_id=identifier, ctx=ctx, info=data) - async def get_tracks( self, query: str, @@ -287,10 +280,8 @@ class Node: search_type: SearchType = SearchType.ytsearch ): """Fetches tracks from the node's REST api to parse into Lavalink. - If you passed in Spotify API credentials, you can also pass in a Spotify URL of a playlist, album or track and it will be parsed accordingly. - You can also pass in a discord.py Context object to get a Context object on any track you search. """ @@ -308,70 +299,7 @@ class Node: spotify_results = await self._spotify_client.search(query=query) - if isinstance(spotify_results, spotify.Playlist): - tracks = [ - Track( - track_id=track.id, - ctx=ctx, - search_type=search_type, - spotify=True, - info={ - "title": track.name, - "author": track.artists, - "length": track.length, - "identifier": track.id, - "uri": track.uri, - "isStream": False, - "isSeekable": False, - "position": 0, - "thumbnail": track.image - }, - ) for track in spotify_results.tracks - ] - - return Playlist( - playlist_info={"name": spotify_results.name, "selectedTrack": tracks[0]}, - tracks=tracks, - ctx=ctx, - spotify=True, - thumbnail=spotify_results.image, - uri=spotify_results.uri, - ) - - elif isinstance(spotify_results, spotify.Album): - - tracks = [ - Track( - track_id=track.id, - ctx=ctx, - search_type=search_type, - spotify=True, - info={ - "title": track.name, - "author": track.artists, - "length": track.length, - "identifier": track.id, - "uri": track.uri, - "isStream": False, - "isSeekable": False, - "position": 0, - "thumbnail": track.image - }, - ) for track in spotify_results.tracks - ] - - return Playlist( - playlist_info={"name": spotify_results.name, "selectedTrack": tracks[0]}, - tracks=tracks, - ctx=ctx, - spotify=True, - thumbnail=spotify_results.image, - uri=spotify_results.uri, - ) - - - elif isinstance(spotify_results, spotify.Track): - + if isinstance(spotify_results, spotify.Track): return [ Track( track_id=spotify_results.id, @@ -388,10 +316,38 @@ class Node: "isSeekable": False, "position": 0, "thumbnail": spotify_results.image - }, + } ) ] + tracks = [ + Track( + track_id=track.id, + ctx=ctx, + search_type=search_type, + spotify=True, + info={ + "title": track.name, + "author": track.artists, + "length": track.length, + "identifier": track.id, + "uri": track.uri, + "isStream": False, + "isSeekable": False, + "position": 0, + "thumbnail": track.image + } + ) for track in spotify_results.tracks + ] + + return Playlist( + playlist_info={"name": spotify_results.name, "selectedTrack": tracks[0]}, + tracks=tracks, + ctx=ctx, + spotify=True, + thumbnail=spotify_results.image, + uri=spotify_results.uri + ) elif discord_url := DISCORD_MP3_URL_REGEX.match(query): async with self._session.get( @@ -401,19 +357,22 @@ class Node: data: dict = await response.json() track: dict = data["tracks"][0] - info: dict = track.get('info') + info: dict = track.get("info") - return [Track( - track_id=track['track'], - info={ - "title": discord_url.group('file'), - "author": "Unknown", - "length": info.get('length'), - "uri": info.get('uri'), - "position": info.get('position'), - "identifier": info.get('identifier') - }, - ctx=ctx)] + return [ + Track( + track_id=track["track"], + info={ + "title": discord_url.group("file"), + "author": "Unknown", + "length": info.get("length"), + "uri": info.get("uri"), + "position": info.get("position"), + "identifier": info.get("identifier") + }, + ctx=ctx + ) + ] else: async with self._session.get(