示例#1
0
    def handle_get_playlist(self, requestType):
        params = getQueryStringMap(
            self.path) if requestType == 'GET' else self.getpostvariables()

        if params is None:
            self.handleerror()
            return

        ip = params.get('ip')
        if ip: ip = ip[0]

        type = params.get('type')
        if type: type = type[0]

        if type == 'folder':
            id = params.get('id')
            if id: id = int(id[0])

            rec = params.get('rec')
            if rec: rec = True
            else: rec = False

            self._sendm3u(
                PyMusicManager.get_instance().getm3ufromfolder(id, ip, rec),
                'plf_%d.m3u' % id)
        elif type == 'playlist':
            name = params.get('name')
            if name: name = name[0]
            self._sendm3u(
                PyMusicManager.get_instance().getm3ufromplaylist(name, ip),
                'plp_%s.m3u' % name)
        else:
            self.handleerror()
    def _handlePlaylistView(self, playlistName):
        """ Shows a playlist """
        manager = PyMusicManager.get_instance()
        playlist = manager.getPlaylists().get(playlistName)

        res = writehtmlheader()

        if playlist is None:
            res += writehtmlhead(
                'Playlist not found'
            ) + '<h3>Playlist not found</h3>' + writehtmlend()
        else:
            res += writehtmlhead('Playlist view')
            res += writehostnameplaylistfunction(playlistName)
            res += '<h2>' + playlist.name + '</h2>' + writetableheader(['P'])
            for sid in playlist.songs:
                song = manager.getsong(sid)
                if song is not None:
                    res += (writetablerow([
                        '<a href=\"/getsong?id=%d\">%s</a>' %
                        (song.oid, song.name)
                    ]))
        res += (writetableend())

        res += '<a href="javascript:void(0)" onClick="getPl();">Get m3u file</a>'

        res += writehtmlend()
        self._response = res
    def _handlesearchview(self, data):
        manager = PyMusicManager.get_instance()
        res = writehtmlheader() + writehtmlhead(
            'Search results') + '<h2>Search results</h2>'

        res += writetableheader(['Title', 'Artist', 'Name'])
        ss = manager.searchsong(data)
        for s in ss:
            res += writetablerow([
                s.title, s.artist,
                '<a href=\"/getsong?id=%d\">%s</a>' % (s.oid, s.name)
            ])

        res += writetableheader(['Name'])
        ss = manager.searchfolder(data)
        for s in ss:
            res += writetablerow(
                ['<a href=\"?type=folder&id=%d\">%s</a>' % (s.oid, s.name)])

        res += writetableheader(['Name'])
        ss = manager.searchplaylist(data)
        for s in ss:
            res += writetablerow(
                ['<a href=\"?type=playlist&name=%s\">%s</a>' % (s, s)])

        res += writetableend() + writehtmlend()

        self._response = res
    def _handleRandomSongView(self):
        manager = PyMusicManager.get_instance()
        sid = manager.getrandomsongid()
        songitem = manager.getsong(sid)

        res = writehtmlheader() + writehtmlhead('Random song')
        res += '<h3>Random song</h3><p>Title ' + songitem.title + '</p><p>Artist: ' + songitem.artist + '</p>'
        res += '<embed src="/getsong?id=' + str(sid) + '"/>'

        res += writehtmlend()
        self._response = res
    def _handleFolderView(self, folderid, public=False):
        manager = PyMusicManager.get_instance()
        folder = manager.getfolder(folderid)

        res = writehtmlheader() + writehtmlhead('Folder View')
        if not public:
            res += writehostnamefolderfunction(folderid)
            res += writehostnamefolderfunction(folderid, True)
            res += '<h2>Folder: ' + (str(folder.name) if folder.parentId != 0
                                     else 'Root') + '</h2>'

        if folder is not None:
            (s, f) = manager.listfolder(folderid)

            # Write folders
            if not public:
                res += writetableheader(['Name'])
                # Switch to parent
                if folder.parentId != 0:
                    res += (writetablerow([
                        '<a href=\"?type=folder&id=%d\">..</a>' %
                        (folder.parentId)
                    ]))

                if f != []:
                    for fid in f:
                        res += (writetablerow([
                            '<a href=\"?type=folder&id=%d\">%s</a>' %
                            (fid.oid, fid.name)
                        ]))
                    res += (writetableend())

            # Write songs
            if s != []:
                # res += u'<h3>Songs</h3>'
                res += writetableheader(['Title', 'Artist', 'Name'])
                for song in s:
                    res += (writetablerow([
                        song.title, song.artist,
                        '<a href=\"/getsong?id=%d\">%s</a>' %
                        (song.oid, song.name)
                    ]))
                res += (writetableend())

            if not public:
                res += writePublicUrlFunction(folder.getPublicUrl())
                res += '<a href="javascript:void(0)" onClick="moveToPublic();">Public link</a><br>'

        if not public:
            res += '<a href="javascript:void(0)" onClick="getFol();">Get m3u file</a><br>'
            res += '<a href="javascript:void(0)" onClick="getFolR();">Get m3u file for all songs!</a>'

        res += writehtmlend()
        self._response = res
    def _handlePlaylistsView(self):
        """ Shows playlists """
        manager = PyMusicManager.get_instance()
        res = writehtmlheader() + writehtmlhead(
            'Playlists') + '<h2>Playlists</h2>' + writetableheader(
                ['Playlist'])
        for n in manager.listplaylists():
            res += writetablerow(
                ['<a href=\"?type=playlist&name=%s\">%s</a>' % (n, n)])
        res += writetableend()
        res += writehtmlend()

        self._response = res
示例#7
0
    def _sendsong(self, songid):
        smanager = PyMusicManager.get_instance()
        if songid == 0:
            songid = smanager.getrandomsongid()

        path = smanager._getsongpath(songid)
        if path is not None and isfile(path):
            # open file
            try:
                with open(path, 'rb') as fd:
                    size = getsize(path)
                    filename_header = rfc6266.build_header(
                        basename(path), 'inline')  # Fix for encoding!
                    self.send_response(206 if "Range" in self.headers else 200)
                    self.send_header("Content-type", guess_type(path)[0])
                    self.send_header("Pragma", 'public')
                    self.send_header('Expires', '-1')
                    self.send_header(
                        'Cache-Control',
                        'public, must-revalidate, post-check=0, pre-check=0')
                    self.send_header('Content-Disposition', filename_header)
                    self.send_header('Content-Transfer-Encoding', 'binary')
                    self.send_header('Accept-Ranges', 'bytes')

                    if "Range" in self.headers:
                        d = self._getsongbytesbound(size)
                        # logging.debug("[HTTPSERVER] Range headers: %s, start: %d, end: %d" %
                        # (self.headers['Range'], d[0], d[1]))
                        start_range = d[0]
                        end_range = d[1]
                        self.send_header(
                            "Content-Range", 'bytes ' + str(start_range) +
                            '-' + str(end_range - 1) + '/' + str(size))
                        self.send_header("Content-Length",
                                         end_range - start_range)
                        # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
                        self.end_headers()

                        size = end_range - start_range
                        fd.seek(start_range)  # discard first bytes
                    else:
                        self.send_header("Content-length", size)

                    self.end_headers()
                    copyfileobj(fd, self.wfile, size)  # Send file
            except ConnectionResetError as cre:
                pass
        else:
            self.send_error(500)
    def _handleSongsView(self):
        manager = PyMusicManager.get_instance()
        songs = manager.listsongsorderedbyname()

        res = writehtmlheader() + writehtmlhead(
            'Song View') + '<h2>Songs</h2>' + writetableheader(
                ['Title', 'Artist', 'Name'])
        for sid in songs:
            res += (writetablerow([
                sid.title, sid.artist,
                '<a href=\"/getsong?id=%d\">%s</a>' % (sid.oid, sid.name)
            ]))
        res += (writetableend())

        res += writehtmlend()
        self._response = res
    def _handleUpdateView(self):
        if self._role < 5:
            self._response = "Forbidden!"
            return

        manager = PyMusicManager.get_instance()

        manager.updateDb()

        res = writehtmlheader() + writehtmlhead(
            'Update') + '<h3>Updating...</h3>'

        res += '<br><a href=\"/songs/\">Back</a>'

        res += writehtmlend()

        self._response = res
    def _handleDownloadView(self, url):
        if self._role < 5:
            self._response = "Forbidden!"
            return

        manager = PyMusicManager.get_instance()

        res = writehtmlheader() + writehtmlhead(
            'Download') + '<h3>Download</h3>'

        if manager.downloadsong(url):
            res += '<p>Song is downloading...</p>'
        else:
            res += '<p>Cannot download song! Server error</p>'
        res += '<br><a href=\"/songs/\">Back</a>'

        res += writehtmlend()

        self._response = res
    def _handleUploadView(self, name, data):
        if self._role < 5:
            self._response = "Forbidden!"
            return

        manager = PyMusicManager.get_instance()

        res = writehtmlheader() + writehtmlhead('Upload')

        if manager.addRemoteSong(name, data):
            res += '<h3>Upload succesful</h3>'
            res += '<p>Song %s uploaded!</p>' % name
        else:
            res += '<h3>Upload unsuccesful!</h3>'
            res += '<p>Cannot upload %s!</p>' % name

        res += '<br><a href=\"/songs/\">Back</a>'
        res += writehtmlend()

        self._response = res
示例#12
0
def createHTTPSServer():
    server = SecureThreadedXMLRPCHTTPServer(HttpsHandler)
    server.register_instance(PyMusicManager.get_instance())
    # server.register_introspection_functions() # Unsecure!
    return server
示例#13
0
def main():
    parse_arguments()

    logging.info('PyMusicServer3 %s Marco Panato - %s' %
                 (globals.REVISION, globals.DATE))

    logging.info('[MAIN] Loading settings')
    SettingsProvider.get_instance()

    logging.info('[MAIN] Initializing DbManager')
    DbManager.get_instance()

    logging.info('[MAIN] Initializing DataManager')
    DataManager.get_instance()

    logging.info('[MAIN] Initializing MusicManager')
    PyMusicManager.get_instance()

    logging.info('[MAIN] Initializing youtube-dl updater')
    ydlupdater = YoutubeDlUpdater()
    ydlupdater.start()

    logging.info('[MAIN] Creating HTTP frontend')
    httpfrontend = createHTTPServer()

    logging.info('[MAIN] Creating HTTPS frontend')
    httpsfrontend = createHTTPSServer()

    logging.info(
        '[MAIN] Waiting for clients on port %s and %s...' %
        (SettingsProvider.get_instance().readsetting('listenporthttp'),
         SettingsProvider.get_instance().readsetting('listenporthttps')))
    threadhttp = runinanotherthread(httpfrontend.serve_forever)
    threadhttps = runinanotherthread(httpsfrontend.serve_forever)

    try:
        while True:
            sleep(500)
    except KeyboardInterrupt:
        logging.info("[MAIN] CTRL-C catched! Closing...")
    finally:
        logging.info("[MAIN] Closing server")
        httpfrontend.shutdown()
        httpsfrontend.shutdown()

        threadhttp.join(2)
        threadhttps.join(2)

        del httpfrontend
        del httpsfrontend

        logging.info('[MAIN] Closing youtube-dl updater')
        ydlupdater.stop()

        logging.info("[MAIN] Closing settings manager")
        SettingsProvider.del_instance()

        logging.info("[MAIN] Closing MusicManager")
        PyMusicManager.del_instance()

        logging.info("[MAIN] Closing DataManager")
        DataManager.del_instance()

        logging.info("[MAIN] Closing DbManager")
        DbManager.del_instance()

    logging.info("[MAIN] Bye")
 def _handlePublicUrlView(self, publicUrl):
     manager = PyMusicManager.get_instance()
     self._handleFolderView(manager.getFolderIdFromPublicUrl(publicUrl),
                            True)