7 from media.item import item_builders, item_id_generators, dict_to_item
8 from database import MusicDatabase
9 import variables as var
13 class MusicCache(dict):
14 def __init__(self, db: MusicDatabase):
17 self.log = logging.getLogger("bot")
20 self.file_id_lookup = {}
21 self.dir_lock = threading.Lock()
23 def get_item_by_id(self, bot, id): # Why all these functions need a bot? Because it need the bot to send message!
27 # if not cached, query the database
28 item = self.fetch(bot, id)
31 self.log.debug("library: music found in database: %s" % item.format_debug_string())
36 # raise KeyError("Unable to fetch item from the database! Please try to refresh the cache by !recache.")
38 def get_item(self, bot, **kwargs):
39 # kwargs should provide type and id, and parameters to build the item if not existed in the library.
44 id = item_id_generators[kwargs['type']](**kwargs)
49 # if not cached, query the database
50 item = self.fetch(bot, id)
53 self.log.debug("library: music found in database: %s" % item.format_debug_string())
56 # if not in the database, build one
57 self[id] = item_builders[kwargs['type']](bot, **kwargs) # newly built item will not be saved immediately
60 def get_items_by_tags(self, bot, tags):
61 music_dicts = self.db.query_music_by_tags(tags)
64 for music_dict in music_dicts:
66 self[id] = dict_to_item(bot, music_dict)
67 items.append(self[id])
71 def fetch(self, bot, id):
72 music_dicts = self.db.query_music(id=id)
74 music_dict = music_dicts[0]
75 self[id] = dict_to_item(bot, music_dict)
81 self.log.debug("library: music save into database: %s" % self[id].format_debug_string())
82 self.db.insert_music(self[id].to_dict())
84 def free_and_delete(self, id):
85 item = self.get_item_by_id(None, id)
87 self.log.debug("library: DELETE item from the database: %s" % item.format_debug_string())
89 if item.type == 'file' and item.path in self.file_id_lookup:
90 if item.path in self.file_id_lookup:
91 del self.file_id_lookup[item.path]
92 self.files.remove(item.path)
94 elif item.type == 'url':
99 self.db.delete_music(id=item.id)
103 self.log.debug("library: cache freed for item: %s" % self[id].format_debug_string())
107 self.log.debug("library: all cache freed")
110 def build_dir_cache(self, bot):
111 self.dir_lock.acquire()
112 self.log.info("library: rebuild directory cache")
114 files = util.get_recursive_file_list_sorted(var.music_folder)
115 self.dir = util.Dir(var.music_folder)
117 item = self.fetch(bot, item_id_generators['file'](path=file))
119 item = item_builders['file'](bot, path=file)
120 self.log.debug("library: music save into database: %s" % item.format_debug_string())
121 self.db.insert_music(item.to_dict())
123 self.dir.add_file(file)
124 self.files.append(file)
125 self.file_id_lookup[file] = item.id
127 self.save_dir_cache()
128 self.dir_lock.release()
130 def save_dir_cache(self):
131 var.db.set("dir_cache", "files", json.dumps(self.file_id_lookup))
133 def load_dir_cache(self, bot):
134 self.dir_lock.acquire()
135 self.log.info("library: load directory cache from database")
136 loaded = json.loads(var.db.get("dir_cache", "files"))
137 self.files = loaded.keys()
138 self.file_id_lookup = loaded
139 self.dir = util.Dir(var.music_folder)
140 for file, id in loaded.items():
141 self.dir.add_file(file)
142 self.dir_lock.release()
145 class CachedItemWrapper:
146 def __init__(self, lib, id, type, user):
151 self.log = logging.getLogger("bot")
155 return self.lib[self.id]
158 dict = self.item().to_dict()
159 dict['user'] = self.user
163 ret = self.item().validate()
164 if ret and self.item().version > self.version:
165 self.version = self.item().version
166 self.lib.save(self.id)
170 ret = self.item().prepare()
171 if ret and self.item().version > self.version:
172 self.version = self.item().version
173 self.lib.save(self.id)
176 def async_prepare(self):
177 th = threading.Thread(
178 target=self.prepare, name="Prepare-" + self.id[:7])
180 "%s: start preparing item in thread: " % self.item().type + self.format_debug_string())
186 return self.item().uri()
188 def add_tags(self, tags):
189 self.item().add_tags(tags)
190 if self.item().version > self.version:
191 self.version = self.item().version
192 self.lib.save(self.id)
194 def remove_tags(self, tags):
195 self.item().remove_tags(tags)
196 if self.item().version > self.version:
197 self.version = self.item().version
198 self.lib.save(self.id)
200 def clear_tags(self):
201 self.item().clear_tags()
202 if self.item().version > self.version:
203 self.version = self.item().version
204 self.lib.save(self.id)
207 return self.item().is_ready()
210 return self.item().is_failed()
212 def format_current_playing(self):
213 return self.item().format_current_playing(self.user)
215 def format_song_string(self):
216 return self.item().format_song_string(self.user)
218 def format_short_string(self):
219 return self.item().format_short_string()
221 def format_debug_string(self):
222 return self.item().format_debug_string()
224 def display_type(self):
225 return self.item().display_type()
228 # Remember!!! Get wrapper functions will automatically add items into the cache!
229 def get_cached_wrapper_from_scrap(bot, **kwargs):
230 item = var.cache.get_item(bot, **kwargs)
231 if 'user' not in kwargs:
232 raise KeyError("Which user added this song?")
233 return CachedItemWrapper(var.cache, item.id, kwargs['type'], kwargs['user'])
236 def get_cached_wrapper_from_dict(bot, dict_from_db, user):
237 item = dict_to_item(bot, dict_from_db)
238 var.cache[dict_from_db['id']] = item
239 return CachedItemWrapper(var.cache, item.id, item.type, user)
242 def get_cached_wrapper_by_id(bot, id, user):
243 item = var.cache.get_item_by_id(bot, id)
245 return CachedItemWrapper(var.cache, item.id, item.type, user)
250 def get_cached_wrappers_by_tags(bot, tags, user):
251 items = var.cache.get_items_by_tags(bot, tags)
254 ret.append(CachedItemWrapper(var.cache, item.id, item.type, user))