def isAuthorized(self): try: sessionUsername = cherrypy.session.get('username', None) sessionUserId = cherrypy.session.get('userid', -1) nameById = self.userdb.getNameById(sessionUserId) except (UnicodeDecodeError, ValueError) as e: # workaround for python2/python3 jump, filed bug in cherrypy # https://bitbucket.org/cherrypy/cherrypy/issue/1216/sessions-python2-3-compability-unsupported log.w(_(''' Dropping all sessions! Try not to change between python 2 and 3, everybody has to relogin now.''')) cherrypy.session.delete() sessionUsername = None if sessionUsername is None: if self.autoLoginActive(): cherrypy.session['username'] = self.userdb.getNameById(1) cherrypy.session['userid'] = 1 cherrypy.session['admin'] = True return True else: return False elif sessionUsername != nameById: self.api_logout(value=None) return False return True
def __enter__(self): global PERFORMANCE_TEST if PERFORMANCE_TEST: self.time = time() Performance.indentation += 1 log.w('| ' * (Performance.indentation - 1) + '/ˉˉ' + self.text)
def ensure_current_version(dbname=None, autoconsent=False, consentcallback=None): """Make sure all defined databases exist and are up to date. Will connect to all these databases and try to update their layout, if necessary, possibly asking the user for consent. dbname : str When given, only make sure of the database with that name. autoconsent : bool When ``True``, don't ask for consent, ever. consentcallback: callable Called when an update requires user consent; if the return value does not evaluate to ``True``, abort don't run any updates and return ``False``. If no callback is given or autoconsent == True, the value of autoconsent will be used to decide if the update should run. Returns : bool ``True`` if requirements are met. """ if autoconsent or consentcallback is None: consentcallback = lambda _: autoconsent with MultiUpdater(dbname) as update: if update.needed: if update.requires_consent and not consentcallback(update.prompts): return False log.w("Database schema update; don't turn off the program!") update.run() log.i("Database schema update complete.") return True
def __exit__(self, type, value, traceback): global PERFORMANCE_TEST if PERFORMANCE_TEST: duration = (time() - self.time) * 1000 log.w('│ ' * (Performance.indentation-1) + '╰──%g ms' % (duration,)) Performance.indentation -= 1
def __enter__(self): global PERFORMANCE_TEST if PERFORMANCE_TEST: self.time = time() Performance.indentation += 1 log.w('| ' * (Performance.indentation - 1) + '/ˉˉ' + self.text) return self
def ensure_current_version(dbname=None, autoconsent=False, consentcallback=None): '''Make sure all defined databases exist and are up to date. Will connect to all these databases and try to update their layout, if necessary, possibly asking the user for consent. dbname : str When given, only make sure of the database with that name. autoconsent : bool When ``True``, don't ask for consent, ever. consentcallback: callable Called when an update requires user consent; if the return value does not evaluate to ``True``, abort don't run any updates and return ``False``. If no callback is given or autoconsent == True, the value of autoconsent will be used to decide if the update should run. Returns : bool ``True`` if requirements are met. ''' if autoconsent or consentcallback is None: consentcallback = lambda _: autoconsent with MultiUpdater(dbname) as update: if update.needed: if update.requires_consent and not consentcallback(update.prompts): return False log.w("Database schema update; don't turn off the program!") update.run() log.i('Database schema update complete.') return True
def __exit__(self, type, value, traceback): global PERFORMANCE_TEST if PERFORMANCE_TEST: duration = (time() - self.time) * 1000 log.w('| ' * (Performance.indentation - 1) + '\__ %g ms' % (duration, )) Performance.indentation -= 1
def create_and_alter_tables(self, suppressWarning=False): tableChanged = False tableChanged |= self.filestable.createOrAlterTable(self.conn) tableChanged |= self.dictionarytable.createOrAlterTable(self.conn) tableChanged |= self.searchtable.createOrAlterTable(self.conn) if tableChanged and not suppressWarning: log.w('The database layout has changed, please run "cherrymusic --update" to make sure everthing is up to date.') return tableChanged
def decode(filepath): try: return subprocess.Popen(Decoders[filetype(filepath)]+[filepath], stdout=subprocess.PIPE, stderr=devnull) except OSError: log.w("Cannot decode {}, no decoder available, trying fallback decoder!".format(filepath)) try: return subprocess.Popen(Decoders[filetype(filepath)]+[filepath], stdout=subprocess.PIPE, stderr=devnull) except OSError: log.w("Fallback failed, cannot decode {}!".format(filepath)) raise
def encode(newformat, fromdecoder): try: enc = Encoders[newformat] if 'BITRATE_OGG' in enc: enc[enc.index('BITRATE_OGG')] = str(BITRATE_OGG) if 'BITRATE_MP3' in enc: enc[enc.index('BITRATE_MP3')] = str(BITRATE_MP3) return subprocess.Popen(enc, stdin=fromdecoder.stdout, stdout=subprocess.PIPE, stderr=devnull) except OSError: log.w("Cannot encode to {}, no encoder available!") raise
def children(self, sort=True, reverse=True): '''If self.isdir and self.exists, return an iterable of fileobjects corresponding to its direct content (non-recursive). Otherwise, log a warning and return (). ''' try: content = os.listdir(self.fullpath) if sort: content = sorted(content, reverse=reverse) return (File(name, parent=self) for name in content) except OSError as error: log.w('cannot listdir: %s', error) return ()
def id_fileobj(self, fileobj): '''fetches the db id for fileobj and saves it in fileobj.uid''' if fileobj.parent is None: pid = -1 else: if fileobj.parent.uid == -1: self.id_fileobj(fileobj.parent) pid = fileobj.parent.uid res = self.lookup_filename(fileobj.basename, pid) if res is None: if fileobj != fileobj.root: # testdir itself is not in db log.w('fileobj not in database: %s', fileobj) return uid = res[0] fileobj.uid = uid
def transcode(filepath, newformat): log.i("""Transcoding file {} {} ---[{}]---> {}""".format(filepath,filetype(filepath),Encoders[newformat][0],newformat)) try: fromdecoder = decode(filepath) encoder = encode(newformat, fromdecoder) while True: data = encoder.stdout.read(TRANSCODE_BUFFER) if not data: break yield data except OSError: log.w("Transcode of file '{}' to format '{}' failed!".format(filepath,newformat)) finally: encoder.terminate() fromdecoder.terminate()
def getResourcePath(path): #check share first resourceprefix = os.path.join(sys.prefix, 'share', 'cherrymusic') respath = os.path.join(resourceprefix, path) if not os.path.exists(respath): log.w("Couldn't find " + respath + ". Trying local install path.") #otherwise check local install resourceprefix = os.path.dirname(os.path.dirname(__file__)) respath = os.path.join(resourceprefix, path) if not os.path.exists(respath): log.w("Couldn't find " + respath + ". Trying home dir.") #lastly check homedir resourceprefix = os.path.join(os.path.expanduser('~'), '.cherrymusic') respath = os.path.join(resourceprefix, path) if not os.path.exists(respath): raise ResourceNotFound("Couldn't locate '" + path + "'!") return os.path.join(resourceprefix, path)
def createMusicEntryByFilePath(file): """DEPRECATED, files are checked using isValidMediaFile(MusicEntry) now""" strippedpath = strippath(file) #let only playable files appear in the search results playable = isplayable(strippedpath) fullpath = os.path.join(cherry.config['media.basedir'], file) if not os.path.exists(fullpath): log.w('search found inexistent file: %r', file) return [] isfile = os.path.isfile(fullpath) if isfile and not playable: return [] if isfile: return [MusicEntry(strippedpath)] else: return [MusicEntry(strippedpath, dir=True)]
def getSongInfo(filepath): if has_stagger: try: tag = stagger.read_tag(filepath) except Exception: tag = MockTag() else: tag = MockTag() if has_audioread: try: with audioread.audio_open(filepath) as f: audiolength = f.duration except Exception as e: log.w("audioread fail: unable to fetch duration of '%s' (%s)", filepath, type(e).__name__) audiolength = 0 else: audiolength = 0 return Metainfo(tag.artist, tag.album, tag.title, tag.track, audiolength)
def getSongInfo(filepath): if has_stagger: try: tag = stagger.read_tag(filepath) except Exception: tag = MockTag() elif has_mutagen: try: tag = MockTag() file_info = mutagen.File(filepath, easy=True) # NOTE: Joining in order to emulate stagger's formatting of # multiple frames. tag.artist = " / ".join(file_info.get('artist', [tag.artist])) tag.album = " / ".join(file_info.get('album', [tag.album])) tag.title = " / ".join(file_info.get('title', [tag.title])) # NOTE: Splitting out the actual track number since mutagen returns # a total as well. tag.track = file_info.get('tracknumber', [tag.track])[0].split('/')[0] except Exception: tag = MockTag() else: tag = MockTag() if has_audioread: try: with audioread.audio_open(filepath) as f: audiolength = f.duration except Exception as e: log.w("audioread fail: unable to fetch duration of %(file)r (%(exception)s)", {'file': filepath, 'exception': type(e).__name__}) audiolength = 0 else: audiolength = 0 return Metainfo(tag.artist, tag.album, tag.title, tag.track, audiolength)
# along with this program. If not, see <http://www.gnu.org/licenses/> # from cherrymusicserver import log import sys has_stagger = has_mutagen = has_audioread = False #check for meta info libraries if sys.version_info >= (3,): #stagger is only for python 3 try: import stagger has_stagger = True except ImportError: log.w(_('''python library "stagger" not found: There will be no ID-tag support!''')) else: try: import mutagen has_mutagen = True except ImportError: log.w(_('''python library "mutagen" not found: There will be no ID-tag support!''')) try: import audioread has_audioread = True except ImportError: log.w(_('''python library "audioread" not found! -Audio file length can't be determined without it!'''))
def log(self, text): global PERFORMANCE_TEST if PERFORMANCE_TEST: for line in text.split('\n'): log.w('| ' * (Performance.indentation) + line)
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # from cherrymusicserver import log import sys #check for meta info libraries if sys.version_info >= (3, ): #stagger is only for python 3 try: import stagger has_stagger = True except ImportError: log.w( '''python library "stagger" not found: There will be no ID-tag support!''' ) has_stagger = False else: has_stagger = False try: import audioread has_audioread = True except ImportError: log.w('''python library "audioread" not found! -Audio file length can't be determined without it!''') has_audioread = False class Metainfo():
def log(text): for line in text.split('\n'): log.w('| ' * (Performance.indentation) + line)