Skip to content

Commit

Permalink
Customizations and optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyTempel committed Mar 13, 2018
1 parent c30d9a8 commit ec4e440
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 27 deletions.
44 changes: 32 additions & 12 deletions lavalink/AudioTrack.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,43 @@ def __init__(self, message):


class AudioTrack:
def build(self, track, requester):
def __init__(self, track, identifier, can_seek, author, duration, stream,
title, uri, requester, enable_msg: bool = True, is_ad: bool = False, quit_after_empty: bool = False, ):
self.track = track
self.identifier = identifier
self.can_seek = can_seek
self.author = author
self.duration = duration
self.stream = stream
self.title = title
self.uri = uri
self.requester = requester
self.enable_msg = enable_msg
self.is_ad = is_ad
self.quit_after_empty = quit_after_empty

@classmethod
def build(cls, track, requester, enable_msg: bool = True, is_ad: bool = False, quit_after_empty: bool = False):
""" Returns an optional AudioTrack """
try:
self.track = track['track']
self.identifier = track['info']['identifier']
self.can_seek = track['info']['isSeekable']
self.author = track['info']['author']
self.duration = track['info']['length']
self.stream = track['info']['isStream']
self.title = track['info']['title']
self.uri = track['info']['uri']
self.requester = requester

return self
_track = track['track']
identifier = track['info']['identifier']
can_seek = track['info']['isSeekable']
author = track['info']['author']
duration = track['info']['length']
stream = track['info']['isStream']
title = track['info']['title']
uri = track['info']['uri']
requester = requester
enable_msg = enable_msg
is_ad = is_ad
quit_after_empty = quit_after_empty
except KeyError:
raise InvalidTrack('an invalid track was passed')

return cls(_track, identifier, can_seek, author, duration, stream, title,
uri, requester, enable_msg, is_ad, quit_after_empty)

@property
def thumbnail(self):
""" Returns the video thumbnail. Could be an empty string. """
Expand Down
11 changes: 10 additions & 1 deletion lavalink/Client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import logging

import aiohttp

from .PlayerManager import PlayerManager, DefaultPlayer
Expand Down Expand Up @@ -34,6 +35,14 @@ def __init__(self, bot, log_level=logging.INFO, loop=asyncio.get_event_loop(), h
)
self.players = PlayerManager(self, player=player)

@classmethod
def persistent(cls, bot, *args, **kwargs):
try:
return bot.lavalink
except AttributeError:
bot.lavalink = cls(bot, *args, **kwargs)
return bot.lavalink

def register_hook(self, func):
if func not in self.hooks:
self.hooks.append(func)
Expand All @@ -42,7 +51,7 @@ def unregister_hook(self, func):
if func in self.hooks:
self.hooks.remove(func)

async def dispatch_event(self, event: str, guild_id: str, reason: str= ''):
async def dispatch_event(self, event: str, guild_id: str, reason: str = ''):
player = self.players[int(guild_id)]

if player:
Expand Down
23 changes: 16 additions & 7 deletions lavalink/PlayerManager.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from abc import ABC, abstractmethod
from random import randrange
from .Events import *
from .AudioTrack import *

from .AudioTrack import *
from .Events import *

__all__ = ["PlayerManager", "BasePlayer", "DefaultPlayer"]

Expand Down Expand Up @@ -39,6 +39,7 @@ def __init__(self, lavalink, guild_id: int):

self.queue = []
self.current = None
self.previous = None

@property
def is_playing(self):
Expand Down Expand Up @@ -81,15 +82,23 @@ def fetch(self, key: object, default=None):
""" Retrieves the related value from the stored user data """
return self._user_data.get(key, default)

def add(self, requester: int, track: dict):
def add(self, requester: int, track: dict, is_ad: bool = False, enable_msg: bool = True,
quit_after_empty: bool = False):
""" Adds a track to the queue """
self.queue.append(AudioTrack().build(track, requester))
self.queue.append(
AudioTrack.build(track, requester, is_ad=is_ad, enable_msg=enable_msg, quit_after_empty=quit_after_empty))

def add_next(self, requester: int, track: dict, is_ad: bool = False, enable_msg: bool = True,
quit_after_empty: bool = False):
""" Adds a track to the beginning of the queue """
self.queue.insert(0, AudioTrack.build(track, requester, is_ad=is_ad, enable_msg=enable_msg,
quit_after_empty=quit_after_empty))

async def play(self):
""" Plays the first track in the queue, if any """
if self.repeat and self.current is not None:
self.queue.append(self.current)

self.previous = self.current
self.current = None
self.position = 0
self.paused = False
Expand Down Expand Up @@ -132,8 +141,8 @@ async def seek(self, pos: int):

async def handle_event(self, event):
if isinstance(event, (TrackStartEvent, TrackExceptionEvent)) or \
isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':
await self.play()
isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':
await self.play()


class PlayerManager:
Expand Down
1 change: 0 additions & 1 deletion lavalink/Utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
class Utils:

@staticmethod
def format_time(time):
""" Formats the given time into HH:MM:SS """
Expand Down
4 changes: 2 additions & 2 deletions lavalink/WebSocket.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import asyncio
import websockets
import json
import logging

import websockets

log = logging.getLogger(__name__)


Expand Down Expand Up @@ -119,6 +120,5 @@ async def send(self, **data):
self._queue.append(data)
log.debug('Send called before websocket ready; queueing payload\n\t', str(data))


def destroy(self):
self._shutdown = False
7 changes: 3 additions & 4 deletions lavalink/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@
__license__ = 'MIT'
__copyright__ = 'Copyright 2018 Luke & William'
__version__ = '2.1'
__modified__ = "By: Andraž Korenč"
import sys

from .AudioTrack import *
from .Client import *
from .Events import *
from .PlayerManager import *
from .Utils import *
from .WebSocket import *
from .Events import *

import logging
import sys

log = logging.getLogger(__name__)

Expand Down

0 comments on commit ec4e440

Please sign in to comment.