7 import variables as var
8 from media.file import FileItem
9 from media.url import URLItem
10 from media.url_from_playlist import PlaylistURLItem
11 from media.radio import RadioItem
12 from database import MusicDatabase
13 from media.library import MusicLibrary
15 class PlaylistItemWrapper:
16 def __init__(self, lib, id, type, user):
21 self.log = logging.getLogger("bot")
25 return self.lib[self.id]
28 dict = self.item().to_dict()
29 dict['user'] = self.user
33 ret = self.item().validate()
34 if ret and self.item().version > self.version:
35 self.version = self.item().version
36 self.lib.save(self.id)
40 ret = self.item().prepare()
41 if ret and self.item().version > self.version:
42 self.version = self.item().version
43 self.lib.save(self.id)
46 def async_prepare(self):
47 th = threading.Thread(
48 target=self.item().prepare, name="Prepare-" + self.id[:7])
50 "%s: start preparing item in thread: " % self.item().type + self.format_debug_string())
56 return self.item().uri()
58 def add_tag(self, tag):
59 self.item().add_tag(tag)
60 if self.item().version > self.version:
61 self.version = self.item().version
62 self.lib.save(self.id)
64 def remove_tag(self, tag):
65 self.item().remove_tag(tag)
66 if self.item().version > self.version:
67 self.version = self.item().version
68 self.lib.save(self.id)
71 return self.item().is_ready()
74 return self.item().is_failed()
76 def format_current_playing(self):
77 return self.item().format_current_playing(self.user)
79 def format_song_string(self):
80 return self.item().format_song_string(self.user)
82 def format_short_string(self):
83 return self.item().format_short_string()
85 def format_debug_string(self):
86 return self.item().format_debug_string()
88 def display_type(self):
89 return self.item().display_type()
92 def get_item_wrapper(bot, **kwargs):
93 item = var.library.get_item(bot, **kwargs)
94 return PlaylistItemWrapper(var.library, item.id, kwargs['type'], kwargs['user'])
96 def get_item_wrapper_by_id(bot, id, user):
97 item = var.library.get_item_by_id(bot, id)
99 return PlaylistItemWrapper(var.library, item.id, item.type, user)
103 def get_item_wrappers_by_tags(bot, tags, user):
104 items = var.library.get_items_by_tags(bot, tags)
107 ret.append(PlaylistItemWrapper(var.library, item.id, item.type, user))
110 def get_playlist(mode, _list=None, index=None):
111 if _list and index is None:
112 index = _list.current_index
115 if mode == "one-shot":
116 return OneshotPlaylist()
117 elif mode == "repeat":
118 return RepeatPlaylist()
119 elif mode == "random":
120 return RandomPlaylist()
121 elif mode == "autoplay":
122 return AutoPlaylist()
124 if mode == "one-shot":
125 return OneshotPlaylist().from_list(_list, index)
126 elif mode == "repeat":
127 return RepeatPlaylist().from_list(_list, index)
128 elif mode == "random":
129 return RandomPlaylist().from_list(_list, index)
130 elif mode == "autoplay":
131 return AutoPlaylist().from_list(_list, index)
134 class BasePlaylist(list):
137 self.current_index = -1
138 self.version = 0 # increase by one after each change
139 self.mode = "base" # "repeat", "random"
140 self.pending_items = []
141 self.log = logging.getLogger("bot")
142 self.validating_thread_lock = threading.Lock()
145 return True if len(self) == 0 else False
147 def from_list(self, _list, current_index):
151 self.current_index = current_index
155 def append(self, item: PlaylistItemWrapper):
158 self.pending_items.append(item)
159 self.start_async_validating()
163 def insert(self, index, item):
167 index = self.current_index
169 super().insert(index, item)
171 if index <= self.current_index:
172 self.current_index += 1
174 self.pending_items.append(item)
175 self.start_async_validating()
179 def extend(self, items):
181 super().extend(items)
182 self.pending_items.extend(items)
183 self.start_async_validating()
192 if self.current_index < len(self) - 1:
193 self.current_index += 1
194 return self[self.current_index]
198 def point_to(self, index):
200 if -1 <= index < len(self):
201 self.current_index = index
204 for index, wrapper in enumerate(self):
205 if wrapper.item.id == id:
209 def __delitem__(self, key):
210 return self.remove(key)
212 def remove(self, index):
214 if index > len(self) - 1:
217 removed = self[index]
218 super().__delitem__(index)
220 if self.current_index > index:
221 self.current_index -= 1
223 var.library.free(removed.id)
226 def remove_by_id(self, id):
229 for index, wrapper in enumerate(self):
231 to_be_removed.append(index)
233 for index in to_be_removed:
238 def current_item(self):
242 return self[self.current_index]
244 def next_index(self):
245 if self.current_index < len(self) - 1:
246 return self.current_index + 1
251 if self.current_index < len(self) - 1:
252 return self[self.current_index + 1]
257 # current_index will lose track after shuffling, thus we take current music out before shuffling
258 #current = self.current_item()
259 #del self[self.current_index]
263 #self.insert(0, current)
264 self.current_index = -1
269 self.current_index = -1
270 var.library.free_all()
274 var.db.remove_section("playlist_item")
275 var.db.set("playlist", "current_index", self.current_index)
277 for index, music in enumerate(self):
278 var.db.set("playlist_item", str(index), json.dumps({'id': music.id, 'user': music.user }))
281 current_index = var.db.getint("playlist", "current_index", fallback=-1)
282 if current_index == -1:
285 items = var.db.items("playlist_item")
288 items.sort(key=lambda v: int(v[0]))
290 item = json.loads(item[1])
291 music_wrapper = get_item_wrapper_by_id(var.bot, item['id'], item['user'])
293 music_wrappers.append(music_wrapper)
294 self.from_list(music_wrappers, current_index)
296 def _debug_print(self):
297 print("===== Playlist(%d)=====" % self.current_index)
298 for index, item_wrapper in enumerate(self):
299 if index == self.current_index:
300 print("-> %d %s" % (index, item_wrapper.format_debug_string()))
302 print("%d %s" % (index, item_wrapper.format_debug_string()))
303 print("===== End =====")
305 def start_async_validating(self):
306 if not self.validating_thread_lock.locked():
307 th = threading.Thread(target=self._check_valid, name="Validating")
311 def _check_valid(self):
312 self.log.debug("playlist: start validating...")
313 self.validating_thread_lock.acquire()
314 while len(self.pending_items) > 0:
315 item = self.pending_items.pop()
316 self.log.debug("playlist: validating %s" % item.format_debug_string())
317 if not item.validate() or item.is_failed():
318 self.log.debug("playlist: validating failed.")
319 self.remove_by_id(item.id)
320 var.library.delete(item.item())
322 self.log.debug("playlist: validating finished.")
323 self.validating_thread_lock.release()
326 class OneshotPlaylist(BasePlaylist):
329 self.mode = "one-shot"
330 self.current_index = -1
332 def from_list(self, _list, current_index):
333 for i in range(current_index):
335 return super().from_list(_list, -1)
344 if self.current_index != -1:
345 super().__delitem__(self.current_index)
349 self.current_index = 0
356 def next_index(self):
368 def point_to(self, index):
370 self.current_index = -1
371 for i in range(index + 1):
372 super().__delitem__(0)
375 class RepeatPlaylist(BasePlaylist):
386 if self.current_index < len(self) - 1:
387 self.current_index += 1
388 return self[self.current_index]
390 self.current_index = 0
393 def next_index(self):
394 if self.current_index < len(self) - 1:
395 return self.current_index + 1
400 return self[self.next_index()]
403 class RandomPlaylist(BasePlaylist):
408 def from_list(self, _list, current_index):
410 random.shuffle(_list)
411 return super().from_list(_list, -1)
419 if self.current_index < len(self) - 1:
420 self.current_index += 1
421 return self[self.current_index]
424 self.current_index = 0
428 class AutoPlaylist(BasePlaylist):
431 self.mode = "autoplay"
435 ids = var.music_db.query_all_ids()
437 _list.append(get_item_wrapper_by_id(var.bot, ids[random.randint(0, len(ids)-1)], 'AutoPlay'))
438 self.from_list(_list, -1)
440 # def from_list(self, _list, current_index):
455 if self.current_index < len(self) - 1:
456 self.current_index += 1
457 return self[self.current_index]
460 self.current_index = 0