Beispiel #1
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 #2
0
    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()
Beispiel #3
0
    def lineReceived(self, line):
        # use str instead of bytes to decode json commands
        # and return answer
        line = line.strip(b"\r").decode("utf-8")
        delimiter = self.delimiter.decode("utf-8")

        try:
            parsed = loads_request(line)
            args, function_path = parsed['params'], parsed["method"]
            if function_path.startswith("signal"):
                # it's a command linked with this connection
                method = function_path.split(self.separator, 1)[1]
                function = self.get_function(method)
            elif function_path == "close":
                function = self.close
            else:
                function = self.deejayd_core.get_function(function_path)
        except Fault as f:
            try:
                r_id = parsed["id"]
            except:
                r_id = None
            ans = JSONRPCResponse(f, r_id)
        else:
            # explicitly init session for this request
            Session()
            try:
                result = function(*args)
                Session.commit()
            except Exception as ex:
                Session.rollback()
                if not isinstance(ex, Fault):
                    log.err(traceback.format_exc())
                    result = Fault(self.FAILURE, _("error, see deejayd log"))
                else:
                    result = ex
            finally:
                Session.remove()
            ans = JSONRPCResponse(result, parsed["id"])

        self.send_buffer(ans.to_json()+delimiter)
        if self.__need_to_close:
            self.transport.loseConnection()
            self.__need_to_close = False
Beispiel #4
0
    def process_event(self, ignore, filepath, mask, library, dir_path):
        # Raised events use real paths, and in the libraries, paths follow
        # symlinks on directories. Therefore, paths must be fixed to use
        # symlinks before being passed on to the library. This is why
        # the library dir_path is passed and used here.
        session = Session()
        filename = filepath.basename().decode("utf-8")
        fpath = os.path.join(dir_path, filename)

        log.debug("inotify: %s event on '%s'" %
                  (twisted.internet.inotify.humanReadableMask(mask), fpath))

        path, name = os.path.split(fpath)

        if mask & twisted.internet.inotify.IN_CREATE:
            if self.__isdir_event(mask)\
                    or self.__occured_on_dirlink(library, fpath):
                library.crawl_directory(path, name)
        elif mask & twisted.internet.inotify.IN_DELETE:
            if self.__isdir_event(mask)\
                    or self.__occured_on_dirlink(library, fpath):
                library.remove_directory(path, name)
            elif not self.__isdir_event(mask):
                library.remove_file(path, name)
        elif mask & twisted.internet.inotify.IN_MOVED_FROM:
            if not self.__isdir_event(mask):
                library.remove_file(path, name)
            else:
                library.remove_directory(path, name)
        elif mask & twisted.internet.inotify.IN_MOVED_TO:
            if not self.__isdir_event(mask):
                library.update_file(path, name)
            else:
                library.crawl_directory(path, name)
        elif mask & twisted.internet.inotify.IN_CLOSE_WRITE:
            library.update_file(path, name)

        session.commit()
        session.close()
Beispiel #5
0
        return None


if __name__ == "__main__":
    import sys
    import pprint
    from deejayd.ui.i18n import DeejaydTranslations
    from deejayd.db import connection
    from deejayd.db.models import Equals

    pp = pprint.PrettyPrinter(indent=2)
    # init filter and audio library
    f = Equals(tag="artist", pattern="J.A.H.O.")
    DeejaydTranslations().install()
    connection.init("sqlite://")
    Session()
    library = AudioLibrary(sys.argv[1])
    library.update(sync=True)

    # display root content
    print("------------ Library content -------------")
    pp.pprint(library.get_dir_content(''))

    # display album list
    print("------------ Album list -------------")
    pp.pprint(library.album_list())
    print(library.album_details(2))
    # test simple filter
    print("------------ Simple equal filter -------------")
    pp.pprint(library.album_list(f))
    pp.pprint(library.search(f))
Beispiel #6
0
    def __reload_list(self):
        log.msg(_("Start to reload icecast webradio source"))
        url = DeejaydConfig().get("webradio", "icecast_url")
        try:
            page_handle = urllib.request.urlopen(url, timeout=TIMEOUT)
            xml_page = page_handle.read()
        except Exception:
            raise DeejaydError(_("Unable to connect to icecast website"))

        # try to parse result
        try:
            root = ET.fromstring(xml_page)
        except ET.XMLSyntaxError:
            raise DeejaydError(_("Unable to parse icecast webradio list"))
        except Exception:
            raise DeejaydError(
                _("Unable to read result from icecast "
                  "webradio list"))
        finally:
            page_handle.close()

        DatabaseLock.acquire()
        session = Session()
        source = session.query(WebradioSource)\
                        .filter(WebradioSource.name == self.NAME)\
                        .one()
        # delete old entries from the database
        session.query(Webradio)\
               .filter(Webradio.source_id == source.id)\
               .delete(synchronize_session='fetch')
        session.query(WebradioCategory)\
               .filter(WebradioCategory.source_id == source.id)\
               .delete(synchronize_session='fetch')

        categories = {}
        webradios = {}
        for station in root:
            try:
                server_type = station.find("server_type").text
                listen_url = station.find("listen_url").text
                genres = station.find("genre").text
                name = station.find("server_name").text
            except TypeError:
                continue

            if server_type.startswith("audio") or \
                    (server_type == "application/ogg" and
                     not listen_url.endswith("ogv")):
                if name not in webradios:
                    genres = genres.split(" ")
                    webradios[name] = Webradio(source=source, name=name)
                    for genre in genres:
                        if len(genre) <= 2 or genre.startswith("."):
                            continue
                        genre = genre.capitalize()
                        if genre not in categories:
                            categories[genre] = WebradioCategory(name=genre,
                                                                 source=source)
                        webradios[name].categories.append(categories[genre])
                    session.add(webradios[name])
                webradios[name].entries.append(WebradioEntry(url=listen_url))
                log.debug('Added icecast webradio %s' % name)
        session.commit()
        Session.remove()
        DatabaseLock.release()

        log.msg(_("Finish to reload icecast webradio source"))
        return {
            "wb_count": len(webradios),
            "cat_count": len(categories),
        }