This commit is contained in:
Lartza
2020-03-10 22:22:20 +02:00
parent 44c7adae1f
commit b2ced96ba4
15 changed files with 166 additions and 121 deletions

View File

@ -20,7 +20,7 @@ class MusicCache(dict):
self.files = []
self.dir_lock = threading.Lock()
def get_item_by_id(self, bot, id): # Why all these functions need a bot? Because it need the bot to send message!
def get_item_by_id(self, bot, id): # Why all these functions need a bot? Because it need the bot to send message!
if id in self:
return self[id]
@ -32,9 +32,8 @@ class MusicCache(dict):
return item
else:
return None
#print(id)
#raise KeyError("Unable to fetch item from the database! Please try to refresh the cache by !recache.")
# print(id)
# raise KeyError("Unable to fetch item from the database! Please try to refresh the cache by !recache.")
def get_item(self, bot, **kwargs):
# kwargs should provide type and id, and parameters to build the item if not existed in the library.
@ -55,7 +54,7 @@ class MusicCache(dict):
return item
# if not in the database, build one
self[id] = item_builders[kwargs['type']](bot, **kwargs) # newly built item will not be saved immediately
self[id] = item_builders[kwargs['type']](bot, **kwargs) # newly built item will not be saved immediately
return self[id]
def get_items_by_tags(self, bot, tags):
@ -254,4 +253,4 @@ def get_cached_wrappers_by_tags(bot, tags, user):
ret = []
for item in items:
ret.append(CachedItemWrapper(var.cache, item.id, item.type, user))
return ret
return ret

View File

@ -24,15 +24,19 @@ type : file
user
'''
def file_item_builder(bot, **kwargs):
return FileItem(bot, kwargs['path'])
def file_item_loader(bot, _dict):
return FileItem(bot, "", _dict)
def file_item_id_generator(**kwargs):
return hashlib.md5(kwargs['path'].encode()).hexdigest()
item_builders['file'] = file_item_builder
item_loaders['file'] = file_item_loader
item_id_generators['file'] = file_item_id_generator
@ -74,7 +78,7 @@ class FileItem(BaseItem):
self.send_client_message(constants.strings('file_missed', file=self.path))
return False
#self.version += 1 # 0 -> 1, notify the wrapper to save me when validate() is visited the first time
# self.version += 1 # 0 -> 1, notify the wrapper to save me when validate() is visited the first time
self.ready = "yes"
return True
@ -153,17 +157,17 @@ class FileItem(BaseItem):
def format_song_string(self, user):
return constants.strings("file_item",
title=self.title,
artist=self.artist if self.artist else '??',
user=user
)
title=self.title,
artist=self.artist if self.artist else '??',
user=user
)
def format_current_playing(self, user):
display = constants.strings("now_playing", item=self.format_song_string(user))
if self.thumbnail:
thumbnail_html = '<img width="80" src="data:image/jpge;base64,' + \
self.thumbnail + '"/>'
display += "<br />" + thumbnail_html
display += "<br />" + thumbnail_html
return display

View File

@ -15,19 +15,24 @@ item_builders = {}
item_loaders = {}
item_id_generators = {}
def example_builder(bot, **kwargs):
return BaseItem(bot)
def example_loader(bot, _dict):
return BaseItem(bot, from_dict=_dict)
def example_id_generator(**kwargs):
return ""
item_builders['base'] = example_builder
item_loaders['base'] = example_loader
item_id_generators['base'] = example_id_generator
def dicts_to_items(bot, music_dicts):
items = []
for music_dict in music_dicts:
@ -35,6 +40,7 @@ def dicts_to_items(bot, music_dicts):
items.append(item_loaders[type](bot, music_dict))
return items
def dict_to_item(bot, music_dict):
type = music_dict['type']
return item_loaders[type](bot, music_dict)
@ -48,11 +54,11 @@ class BaseItem:
self.title = ""
self.path = ""
self.tags = []
self.version = 0 # if version increase, wrapper will re-save this item
self.version = 0 # if version increase, wrapper will re-save this item
if from_dict is None:
self.id = ""
self.ready = "pending" # pending - is_valid() -> validated - prepare() -> yes, failed
self.ready = "pending" # pending - is_valid() -> validated - prepare() -> yes, failed
else:
self.id = from_dict['id']
self.ready = from_dict['ready']
@ -110,6 +116,6 @@ class BaseItem:
self.bot.send_msg(msg)
def to_dict(self):
return {"type" : self.type, "id": self.id, "ready": self.ready, "path": self.path, "tags": self.tags}
return {"type": self.type, "id": self.id, "ready": self.ready, "path": self.path, "tags": self.tags}

View File

@ -162,12 +162,12 @@ class BasePlaylist(list):
def randomize(self):
# current_index will lose track after shuffling, thus we take current music out before shuffling
#current = self.current_item()
#del self[self.current_index]
# current = self.current_item()
# del self[self.current_index]
random.shuffle(self)
#self.insert(0, current)
# self.insert(0, current)
self.current_index = -1
self.version += 1
@ -183,7 +183,7 @@ class BasePlaylist(list):
var.db.set("playlist", "current_index", self.current_index)
for index, music in enumerate(self):
var.db.set("playlist_item", str(index), json.dumps({'id': music.id, 'user': music.user }))
var.db.set("playlist_item", str(index), json.dumps({'id': music.id, 'user': music.user}))
def load(self):
current_index = var.db.getint("playlist", "current_index", fallback=-1)
@ -212,7 +212,7 @@ class BasePlaylist(list):
def start_async_validating(self):
if not self.validating_thread_lock.locked():
time.sleep(0.1) # Just avoid validation finishes too fast and delete songs while something is reading it.
time.sleep(0.1) # Just avoid validation finishes too fast and delete songs while something is reading it.
th = threading.Thread(target=self._check_valid, name="Validating")
th.daemon = True
th.start()

View File

@ -11,6 +11,7 @@ import constants
log = logging.getLogger("bot")
def get_radio_server_description(url):
global log
@ -92,12 +93,15 @@ def radio_item_builder(bot, **kwargs):
else:
return RadioItem(bot, kwargs['url'], '')
def radio_item_loader(bot, _dict):
return RadioItem(bot, "", "", _dict)
def radio_item_id_generator(**kwargs):
return hashlib.md5(kwargs['url'].encode()).hexdigest()
item_builders['radio'] = radio_item_builder
item_loaders['radio'] = radio_item_loader
item_id_generators['radio'] = radio_item_id_generator
@ -109,7 +113,7 @@ class RadioItem(BaseItem):
super().__init__(bot)
self.url = url
if not name:
self.title = get_radio_server_description(self.url) # The title of the radio station
self.title = get_radio_server_description(self.url) # The title of the radio station
else:
self.title = name
self.id = hashlib.md5(url.encode()).hexdigest()
@ -121,7 +125,7 @@ class RadioItem(BaseItem):
self.type = "radio"
def validate(self):
self.version += 1 # 0 -> 1, notify the wrapper to save me when validate() is visited the first time
self.version += 1 # 0 -> 1, notify the wrapper to save me when validate() is visited the first time
return True
def is_ready(self):
@ -146,8 +150,8 @@ class RadioItem(BaseItem):
def format_song_string(self, user):
return constants.strings("radio_item",
url=self.url,
title=get_radio_title(self.url), # the title of current song
name=self.title, # the title of radio station
title=get_radio_title(self.url), # the title of current song
name=self.title, # the title of radio station
user=user
)

View File

@ -17,15 +17,19 @@ import media.system
log = logging.getLogger("bot")
def url_item_builder(bot, **kwargs):
return URLItem(bot, kwargs['url'])
def url_item_loader(bot, _dict):
return URLItem(bot, "", _dict)
def url_item_id_generator(**kwargs):
return hashlib.md5(kwargs['url'].encode()).hexdigest()
item_builders['url'] = url_item_builder
item_loaders['url'] = url_item_loader
item_id_generators['url'] = url_item_id_generator
@ -97,7 +101,7 @@ class URLItem(BaseItem):
return False
else:
self.ready = "validated"
self.version += 1 # notify wrapper to save me
self.version += 1 # notify wrapper to save me
return True
# Run in a other thread
@ -181,7 +185,7 @@ class URLItem(BaseItem):
"bot: finished downloading url (%s) %s, saved to %s." % (self.title, self.url, self.path))
self.downloading = False
self._read_thumbnail_from_file(base_path + ".jpg")
self.version += 1 # notify wrapper to save me
self.version += 1 # notify wrapper to save me
return True
else:
for f in glob.glob(base_path + "*"):
@ -214,7 +218,6 @@ class URLItem(BaseItem):
return dict
def format_debug_string(self):
return "[url] {title} ({url})".format(
title=self.title,
@ -224,9 +227,9 @@ class URLItem(BaseItem):
def format_song_string(self, user):
if self.ready in ['validated', 'yes']:
return constants.strings("url_item",
title=self.title if self.title else "??",
url=self.url,
user=user)
title=self.title if self.title else "??",
url=self.url,
user=user)
return self.url
def format_current_playing(self, user):
@ -235,7 +238,7 @@ class URLItem(BaseItem):
if self.thumbnail:
thumbnail_html = '<img width="80" src="data:image/jpge;base64,' + \
self.thumbnail + '"/>'
display += "<br />" + thumbnail_html
display += "<br />" + thumbnail_html
return display

View File

@ -6,6 +6,7 @@ import hashlib
from media.item import item_builders, item_loaders, item_id_generators
from media.url import URLItem, url_item_id_generator
def get_playlist_info(url, start_index=0, user=""):
items = []
ydl_opts = {
@ -63,6 +64,7 @@ def playlist_url_item_builder(bot, **kwargs):
def playlist_url_item_loader(bot, _dict):
return PlaylistURLItem(bot, "", "", "", "", _dict)
item_builders['url_from_playlist'] = playlist_url_item_builder
item_loaders['url_from_playlist'] = playlist_url_item_loader
item_id_generators['url_from_playlist'] = url_item_id_generator
@ -98,11 +100,11 @@ class PlaylistURLItem(URLItem):
def format_song_string(self, user):
return constants.strings("url_from_playlist_item",
title=self.title,
url=self.url,
playlist_url=self.playlist_url,
playlist=self.playlist_title,
user=user)
title=self.title,
url=self.url,
playlist_url=self.playlist_url,
playlist=self.playlist_title,
user=user)
def format_current_playing(self, user):
display = constants.strings("now_playing", item=self.format_song_string(user))
@ -110,7 +112,7 @@ class PlaylistURLItem(URLItem):
if self.thumbnail:
thumbnail_html = '<img width="80" src="data:image/jpge;base64,' + \
self.thumbnail + '"/>'
display += "<br />" + thumbnail_html
display += "<br />" + thumbnail_html
return display