Beispiel #1
0
 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()
     }
Beispiel #2
0
 def close(self):
     for obj in (self.watcher, self.player, self.sources, self.audiolib,
                 self.videolib, self.webradio):
         if obj is not None:
             obj.close()
     Session.commit()
     Session.remove()
Beispiel #3
0
 def update_in_thread(self, walk_root, force=False):
     # init session for this thread
     DatabaseLock.acquire()
     Session()
     self.walk_directory(walk_root, force)
     # close session to avoid problems
     Session.remove()
     DatabaseLock.release()
Beispiel #4
0
 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()
Beispiel #5
0
 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
Beispiel #6
0
 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')
Beispiel #7
0
    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()
Beispiel #8
0
 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
Beispiel #9
0
 def add_directory(self, path, name):
     parent = self._get_folder(path)
     if parent is not None:
         dir_path = os.path.join(path, name)
         folder = LibraryFolder(name=name,
                                parent_folder=parent,
                                path=dir_path,
                                library_id=self.library_id)
         Session.add(folder)
         self.watcher.watch_dir(dir_path, self)
Beispiel #10
0
 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()
Beispiel #11
0
    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()
Beispiel #12
0
 def _get_file_info(self, file_obj):
     try:
         file_obj = self.parser.parse(file_obj, Session)
     except Exception:
         if util.has_identity(file_obj):
             Session.delete(file_obj)
         else:
             Session.expunge(file_obj)
         log_traceback(level="info")
         return None
     return file_obj
Beispiel #13
0
 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
Beispiel #14
0
    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))
Beispiel #15
0
    def remove_directory(self, path, name):
        dir_path = os.path.join(path, name)
        folder = self._get_folder(dir_path)

        if folder is not None:

            def stop_watchers(d_obj):
                for ch_obj in d_obj.child_folders:
                    stop_watchers(ch_obj)
                self.watcher.stop_watching_dir(d_obj.path)

            stop_watchers(folder)
            Session.delete(folder)
Beispiel #16
0
    def tearDown(self):
        self.deejayd.player.stop()
        self.deejayd.audiopls.clear()
        self.deejayd.videopls.clear()
        self.deejayd.audioqueue.clear()
        # remove recorded playlist
        pl_list = self.deejayd.recpls.get_list()
        self.deejayd.recpls.erase([pl["pl_id"] for pl in pl_list])
        # remove recorded webradio
        self.deejayd.webradio.source_clear_webradios("local")

        # close session
        Session.commit()
        Session.remove()
Beispiel #17
0
    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}
Beispiel #18
0
 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()
Beispiel #19
0
 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()
Beispiel #20
0
 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
Beispiel #21
0
    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()]
Beispiel #22
0
 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)
Beispiel #23
0
    def __init__(self, start_inotify=True, library_update=True):
        super(DeejayDaemonCore, self).__init__()
        config = DeejaydConfig()

        self.player = player.init(config)
        self.put_sub_handler('player', self.player)

        self.audiolib, self.videolib, self.watcher = library.init(self.player,
                                                                  config)
        self.put_sub_handler('audiolib', self.audiolib)
        if self.videolib is not None:
            self.put_sub_handler('videolib', self.videolib)

        self.recpls = DeejaydRecordedPlaylist(self.audiolib)
        self.put_sub_handler('recpls', self.recpls)

        # add audio queue/playlist and video playlist
        self.sources = sources.init(self.player, self.audiolib,
                                    self.videolib, config)
        for source in list(self.sources.sources.values()):
            self.put_sub_handler(source.name, source)
            setattr(self, source.name, source)

        # add webradio if player can play http stream
        if self.player.is_supported_uri("http"):
            self.webradio = DeejaydWebradio(self.player)
            self.put_sub_handler('webradio', self.webradio)
        else:
            log.err(_("Player is not able to play http streams"))
            self.webradio = None

        if library_update:
            self.audiolib.update()
            if self.videolib is not None:
                self.videolib.update()

        # enable JSON-RPC introspection
        self.put_sub_handler('introspection', JSONRPCIntrospection(self))

        # start inotify thread when we are sure that all init stuff are ok
        if self.watcher and start_inotify:
            log.debug(_("Start inotify watcher"))
            self.watcher.start()
        # record changes and close session after the initialization
        Session.commit()
        Session.remove()
Beispiel #24
0
    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)]
Beispiel #25
0
    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}
Beispiel #26
0
 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),
     }
Beispiel #27
0
 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
Beispiel #28
0
 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
Beispiel #29
0
 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()
Beispiel #30
0
        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