def get_stats(self): return { "audio_library_update": self.state["last_update"], "songs": Session.query(Song).count(), "albums": Session.query(Album).count(), "artists": Session.query(Song.artist).distinct().count() }
def get_all_files(self, dir_ids): medias = [] folders = Session.query(LibraryFolder)\ .filter(LibraryFolder.id.in_(dir_ids)) \ .all() for f in folders: medias.extend( Session.query(self.OBJECT_CLASS).join(LibraryFolder).filter( LibraryFolder.path.startswith(f.path)).all()) return medias
def add_webradio(self, source, name, urls, cat=None): provided_urls = [] for url in urls: if url.lower().startswith("http://") or \ url.lower().startswith("https://"): try: if url.lower().endswith(".pls"): provided_urls.extend(get_uris_from_pls(url)) elif url.lower().endswith(".m3u"): provided_urls.extend(get_uris_from_m3u(url)) else: provided_urls.append(url) except IOError: log.err(_("Could not parse %s") % url) pass needed_urls = [] for url in provided_urls: try: protocol = url.split(':')[0] if protocol not in ( 'http', 'https', 'rtsp', ): raise ValueError except ValueError: log.err( _("Discarding %s : webradio protocol not supported.") % url) else: if url not in needed_urls: needed_urls.append(url) if len(needed_urls) < 1: raise DeejaydError( _("Given urls %s is not " "supported") % ",".join(urls)) cats = cat is not None and [cat] or [] webradio = Session.query(Webradio)\ .filter(Webradio.source == source)\ .filter(Webradio.name == name)\ .one_or_none() if webradio is not None: raise DeejaydError(_("Webradio %s already exists") % name) webradio = Webradio(source=source, name=name) Session.add(webradio) for c in cats: webradio.categories.append(Session.query(WebradioCategory).get(c)) for url in needed_urls: webradio.entries.append(WebradioEntry(url=url))
def get_file_withids(self, file_ids): if not file_ids: return [] return Session.query(self.OBJECT_CLASS) \ .filter(Media.m_id.in_(file_ids)) \ .order_by(Media.m_id) \ .all()
def _get_file_with_path(self, file_path): folder, filename = os.path.split(file_path) return Session.query(self.OBJECT_CLASS) \ .join(LibraryFolder) \ .filter(LibraryFolder.path == folder) \ .filter(self.OBJECT_CLASS.filename == filename) \ .one_or_none()
def album_details(self, a_id): album = Session.query(Album)\ .filter(Album.id == a_id)\ .one_or_none() if album is not None: return album.to_json(cover=True, songs=True) return None
def load_playlist(self, pl_ids, queue=True): pls_type = with_polymorphic(MediaList, "*") medias = [] for pl_id in pl_ids: pls = Session.query(pls_type).filter(MediaList.id == pl_id).one() medias += pls.get_medias(Session) self._playlist.load(medias, queue) self.dispatch_signame(self.source_signal)
def save(self): db_list = Session.query(StaticMediaList)\ .filter(StaticMediaList.name == "__"+self.source)\ .one() db_list.items = [] for entry in self.medialist: db_list.items.append(StaticMediaListItem(media_id=entry["m_id"])) Session.commit()
def album_list(self, ft=None, cover=False): query = Session.query(Album) if ft is not None: query = query.join(Song)\ .filter(ft.get_filter(Song))\ .order_by(Album.name) return [a.to_json(cover=cover) for a in query.all()]
def get_status(self): source = Session.query(WebradioSource)\ .filter(WebradioSource.name == self.NAME)\ .one() return { "last_modified": self.state["last_modified"], "categories_count": len(source.categories), "webradios_count": len(source.webradios), }
def new_func(*args, **kwargs): self = args[0] source = Session.query(WebradioSource)\ .filter(WebradioSource.name == self.NAME)\ .one() res = func(self, source, *args[1:], **kwargs) self._update_state() Session.commit() return res
def get_content(self, pl_id, first=0, length=None): magic_or_static = with_polymorphic(MediaList, "*") pls = Session.query(magic_or_static)\ .filter(MediaList.id == pl_id)\ .one_or_none() if pls is None: raise DeejaydError(_("Playlist with id %s does not exist")) return [m.to_json() for m in pls.get_medias(Session, first, length)]
def save_state(self): if self.state is None: raise DeejaydError( _("You try to save a state " "which has not been loaded !")) st_name = "%s_state" % self.state_name s = Session.query(State) \ .filter(State.name == st_name) \ .one() s.state = self.state
def add_category(self, source, cat_name): category = Session.query(WebradioCategory)\ .filter(WebradioCategory.source == source)\ .filter(WebradioCategory.name == cat_name)\ .one_or_none() if category is not None: raise DeejaydError(_("Category %s already exists") % cat_name) category = WebradioCategory(source=source, name=cat_name) Session.add(category) return category.to_json()
def erase(self, pl_ids): if len(pl_ids) > 0: magic_or_static = with_polymorphic(MediaList, "*") pls = Session.query(magic_or_static)\ .filter(MediaList.id.in_(pl_ids))\ .all() for pl in pls: Session.delete(pl) Session.commit() self.dispatch_signame('recpls.listupdate')
def set_rating(self, ft, rating): if int(rating) not in list(range(0, 5)): raise DeejaydError(_("Bad rating value")) q = Session.query(self.OBJECT_CLASS) if ft is not None: q = q.filter(ft.get_filter(self.OBJECT_CLASS)) for m in q.all(): m.rating = rating Session.commit()
def get_cover(self, a_id): album = Session.query(Album)\ .filter(Album.id == a_id)\ .one_or_none() if album.cover is not None: return { "data": base64.b64decode(album.cover), "mimetype": album.cover_type } return None
def load_state(self): st_name = "%s_state" % self.state_name s = Session.query(State) \ .filter(State.name == st_name) \ .one_or_none() if s is None: s = State(name=st_name) s.state = self.initial_state Session.add(s) Session.commit() self.state = s.state
def load_playlist_func(self, pl_id, *__args, **__kw): if pls_type == "static": pls = Session.query(StaticMediaList).get(pl_id) elif pls_type == "magic": all_ft = with_polymorphic(Filter, "*", flat=True) pls = Session.query(MagicMediaList)\ .options(subqueryload( MagicMediaList.filters.of_type(all_ft)) )\ .filter(MagicMediaList.id == pl_id)\ .one() if pls is None: raise DeejaydError(_("Playlist %s not found") % str(pl_id)) rs = func(self, pls, *__args, **__kw) if rs is True: Session.commit() self.dispatch_signame('recpls.update', pl_id=pl_id) return None return rs
def __init__(self): super(_BaseWebradioSource, self).__init__() source = Session.query(WebradioSource)\ .filter(WebradioSource.name == self.NAME)\ .one_or_none() if source is None: source = WebradioSource(name=self.NAME) Session.add(source) Session.commit() self.load_state()
def remove(self, file, library): filename = os.path.basename(file) if filename in self.cover_name: dir_obj = library._get_folder(os.path.dirname(file)) if dir_obj is not None: albums = Session.query(Album)\ .join(Song)\ .filter(Song.folder_id == dir_obj.id)\ .all() for album in albums: album.erase_cover()
def walk_directory(self, walk_root, force=False): walk_root = os.path.join(self.root_path, walk_root) walk_root = walk_root.rstrip("/") walked_folders = [] # cache all medias recorded in database media_dict = {} for m in Session.query(self.OBJECT_CLASS).all(): media_dict[m.get_path()] = m for root, subdirs, files in pathutils.walk(walk_root): root = root.rstrip("/") log.debug('library: update crawling %s' % root) if os.path.basename(root).startswith("."): continue # skip hidden folder folder = self._get_folder(root) if folder is None: folder = LibraryFolder(library_id=self.library_id, path=root, name=os.path.basename(root)) Session.add(folder) self.parse_files(folder, files, media_dict, force) subdirs_obj = self.get_subdirs(folder, subdirs) for sd in subdirs_obj: sd.parent_folder = folder walked_folders.append(root) # clean library Session.query(LibraryFolder) \ .filter(LibraryFolder.library_id == self.library_id) \ .filter(LibraryFolder.path.notin_(walked_folders)) \ .delete(synchronize_session='fetch') if len(media_dict) > 0: db_media_ids = [media_dict[k].m_id for k in media_dict] erased_files = Session.query(self.OBJECT_CLASS) \ .filter(self.OBJECT_CLASS.m_id.in_(db_media_ids)) \ .all() for f in erased_files: Session.delete(f) Session.commit()
def get_subdirs(self, parent, subdirs): def subdir_path(subdir): return os.path.join(parent.path, subdir) subdirs = [ subdir_path(sd) for sd in subdirs if subdir_path(sd) is not None ] return subdirs and Session.query(LibraryFolder) \ .filter(LibraryFolder.library_id == self.library_id, LibraryFolder.path.in_(subdirs)) \ .all()
def __find_video(self, sub_path): path, fn = os.path.split(sub_path) sub_name, ext = os.path.splitext(fn) dir_obj = self.library._get_folder(path) if dir_obj is not None: return Session.query(Video)\ .join(LibraryFolder)\ .filter(Video.folder == dir_obj)\ .filter(Video.filename.ilike(sub_name+".%"))\ .one_or_none() return None
def get_webradios(self, cat_id=None, first=0, length=None): if cat_id is None: query = Session.query(Webradio)\ .join(WebradioSource)\ .filter(WebradioSource.name == self.NAME)\ .offset(first) if length is not None: query = query.limit(length) webradios = query.all() else: category = Session.query(WebradioCategory).get(cat_id) if category is None: raise DeejaydError( _("Category with id %s " "is not found") % cat_id) if length is not None: stop = min(first + int(length), len(category.webradios)) else: stop = len(category.webradios) first = min(first, stop) webradios = category.webradios[first:stop] return [w.to_json() for w in webradios]
def parse(self, file, library): filename = os.path.basename(file) if filename in self.cover_name: dir_obj = library._get_folder(os.path.dirname(file)) if dir_obj is not None: mimetype = mimetypes.guess_type(file) albums = Session.query(Album)\ .join(Song)\ .filter(Song.folder_id == dir_obj.id)\ .all() with open(file, 'rb') as c_data: data = c_data.read() for album in albums: album.update_cover(data, mimetype[0])
def search(self, f=None, ords=[], limit=None): ft = And() if f is not None: ft.combine(f) try: db_filter = ft.get_filter(self.OBJECT_CLASS) except AttributeError as ex: raise DeejaydError(str(ex)) ords = ords or self.DEFAULT_SORT medias = Session.query(self.OBJECT_CLASS) \ .filter(db_filter) \ .order_by(ords) \ .all() return [m.to_json() for m in medias]
def save(self, pls_name): pls = Session.query(StaticMediaList)\ .filter(StaticMediaList.name == pls_name)\ .one_or_none() if pls is None: pls = StaticMediaList(name=pls_name) Session.add(pls) pls.items = [ StaticMediaListItem(media_id=it["m_id"]) for it in self._playlist.get() ] Session.commit() self.dispatch_signame('recpls.listupdate') return {"playlist_id": pls.id}
def __update_media(self, attrs): session = Session() video_or_song = with_polymorphic(Media, [Song, Video]) m_obj = Session.query(video_or_song)\ .filter(Media.m_id == self.media["m_id"])\ .one_or_none() if m_obj is None: log.debug('media with id %d is gone, was probably deleted. ' 'Ignoring media update.' % self.media["m_id"]) return for key in attrs: setattr(m_obj, key, attrs[key]) self.media[key] = attrs[key] session.commit() Session.remove()
def create(self, name, p_type): if name == "": raise DeejaydError(_("Set a playlist name")) if p_type not in ("static", "magic"): raise DeejaydError(_("playlist type has to be 'static' or 'magic'")) pls = Session.query(MediaList)\ .filter(MediaList.name == name)\ .one_or_none() if pls is not None: raise DeejaydError(_("This playlist already exists")) pl_cls = p_type == "static" and StaticMediaList or MagicMediaList pls = pl_cls(name=name) Session.add(pls) Session.commit() self.dispatch_signame('recpls.listupdate') return {"pl_id": pls.id, "name": name, "type": p_type}