Update pool.py

This commit is contained in:
Crussader 2021-10-30 17:09:20 +04:00 committed by GitHub
parent 86fc4fbaf1
commit 6eb472d774
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 63 additions and 104 deletions

View File

@ -6,11 +6,10 @@ import random
import re import re
import socket import socket
import time import time
from typing import Dict, Optional, TYPE_CHECKING, Union from typing import Dict, Optional, TYPE_CHECKING
from urllib.parse import quote from urllib.parse import quote
import aiohttp import aiohttp
import discord
from discord.ext import commands from discord.ext import commands
from . import __version__, spotify from . import __version__, spotify
@ -21,18 +20,10 @@ from .exceptions import (
NodeCreationError, NodeCreationError,
NodeNotAvailable, NodeNotAvailable,
NoNodesAvailable, NoNodesAvailable,
SpotifyAlbumLoadFailed,
SpotifyPlaylistLoadFailed,
SpotifyTrackLoadFailed,
TrackLoadError TrackLoadError
) )
from .objects import Playlist, Track from .objects import Playlist, Track
from .utils import ( from .utils import ClientType, ExponentialBackoff, NodeStats
ClientType,
ExponentialBackoff,
NodeStats,
NodeAlgorithms,
)
if TYPE_CHECKING: if TYPE_CHECKING:
from .player import Player from .player import Player
@ -42,10 +33,12 @@ SPOTIFY_URL_REGEX = re.compile(
) )
DISCORD_MP3_URL_REGEX = re.compile( DISCORD_MP3_URL_REGEX = re.compile(
r"https?://cdn.discordapp.com/attachments/(?P<channel_id>[0-9]+)/(?P<message_id>[0-9]+)/(?P<file>[a-zA-Z0-9_.]+)+" r"https?://cdn.discordapp.com/attachments/(?P<channel_id>[0-9]+)/"
r"(?P<message_id>[0-9]+)/(?P<file>[a-zA-Z0-9_.]+)+"
) )
URL_REGEX = re.compile( URL_REGEX = re.compile(
r'https?://(?:www\.)?.+' r"https?://(?:www\.)?.+"
) )
@ -210,7 +203,8 @@ class Node:
async def send(self, **data): async def send(self, **data):
if not self._available: if not self._available:
raise NodeNotAvailable( 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)) await self._websocket.send_str(json.dumps(data))
@ -261,24 +255,23 @@ class Node:
) -> Track: ) -> Track:
""" """
Builds a track using a valid track identifier Builds a track using a valid track identifier
You can also pass in a discord.py Context object to get a You can also pass in a discord.py Context object to get a
Context object on the track it builds. Context object on the track it builds.
""" """
async with self._session.get(f'{self._rest_uri}/decodetrack?', async with self._session.get(
headers={'Authorization': self._password}, f"{self._rest_uri}/decodetrack?",
params={'track': identifier}) as resp: headers={"Authorization": self._password},
params={"track": identifier}
) as resp:
if not resp.status == 200:
raise TrackLoadError(
f"Failed to build track. Check the identifier is correct and try again."
)
data: dict = await resp.json() data: dict = await resp.json()
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.')
return Track(track_id=identifier, ctx=ctx, info=data) return Track(track_id=identifier, ctx=ctx, info=data)
async def get_tracks( async def get_tracks(
self, self,
query: str, query: str,
@ -287,10 +280,8 @@ class Node:
search_type: SearchType = SearchType.ytsearch search_type: SearchType = SearchType.ytsearch
): ):
"""Fetches tracks from the node's REST api to parse into Lavalink. """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 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. 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 You can also pass in a discord.py Context object to get a
Context object on any track you search. Context object on any track you search.
""" """
@ -308,70 +299,7 @@ class Node:
spotify_results = await self._spotify_client.search(query=query) spotify_results = await self._spotify_client.search(query=query)
if isinstance(spotify_results, spotify.Playlist): if isinstance(spotify_results, spotify.Track):
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):
return [ return [
Track( Track(
track_id=spotify_results.id, track_id=spotify_results.id,
@ -388,10 +316,38 @@ class Node:
"isSeekable": False, "isSeekable": False,
"position": 0, "position": 0,
"thumbnail": spotify_results.image "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): elif discord_url := DISCORD_MP3_URL_REGEX.match(query):
async with self._session.get( async with self._session.get(
@ -401,19 +357,22 @@ class Node:
data: dict = await response.json() data: dict = await response.json()
track: dict = data["tracks"][0] track: dict = data["tracks"][0]
info: dict = track.get('info') info: dict = track.get("info")
return [Track( return [
track_id=track['track'], Track(
info={ track_id=track["track"],
"title": discord_url.group('file'), info={
"author": "Unknown", "title": discord_url.group("file"),
"length": info.get('length'), "author": "Unknown",
"uri": info.get('uri'), "length": info.get("length"),
"position": info.get('position'), "uri": info.get("uri"),
"identifier": info.get('identifier') "position": info.get("position"),
}, "identifier": info.get("identifier")
ctx=ctx)] },
ctx=ctx
)
]
else: else:
async with self._session.get( async with self._session.get(