Beispiel #1
0
    def increment_statistics(self):
        if self.__is_loaded:
            sql_insert = [
                'insert into stats_albums (album, tracks) values (?, ?)',
                [self.name, int(self.statistics + 1)]
            ]

            sql_update = [
                'update stats_albums set tracks=:value where album=:album', {
                    'album': self.name,
                    'value': int(self.statistics + 1)
                }
            ]

            sql = SQLite()
            if self.statistics == 0:
                sql.execute(sql_insert[0], sql_insert[1])
            else:
                sql.execute(sql_update[0], sql_update[1])

            self.statistics = int(self.statistics + 1)

            sql.close()
        else:
            raise Exception('[Album] object was not loaded.')
    def load_from_artist(self, artist_name):
        sqlite = SQLite()
        cursor = sqlite.execute(
            'select * from songs where artist=:val ' +
            ' order by album, title', {'val': artist_name})
        songs = cursor.fetchall()
        sqlite.close()

        return songs
    def artist_exists(self, artist_name):
        sqlite = SQLite()
        cursor = sqlite.execute('select count(*) from songs where artist=:val',
                                {'val': artist_name})
        songs = cursor.fetchall()
        sqlite.close()

        answer = songs[0][0]
        if answer > 0:
            return True
Beispiel #4
0
    def __init__(self, **kwargs):
        """Initialization of the Song() model class.

        Usage:
         sng = Song(filename='/foo/whatever.flac')
        or:
         sng = Song(title='Foo', artist='Bar'…)
        """

        self.__is_loaded = False

        if 'filename' in kwargs.keys() and len(kwargs.keys()) == 1:
            filename = kwargs['filename']

            # Try to load a Song() object with the filename.
            sql = SQLite()
            cur_nb = sql.execute('select * from songs where filename=:file',
                                 {'file': filename})
            song_sql = cur_nb.fetchone()

            if song_sql is not None:
                self.__is_loaded = True

                self.title = song_sql[0]
                self.artist = song_sql[1]
                self.album = song_sql[2]
                self.track = song_sql[6]
                self.length = song_sql[7]
                self.comment = song_sql[3]
                self.genre = song_sql[4]
                self.year = song_sql[5]
                self.filename = song_sql[8]
                self.statistics = self.__get_statistics()

            sql.close()
        else:
            keys = ['title', 'artist', 'album', 'track', 'length', 'comment',
                    'genre', 'year', 'filename']

            for key in keys:
                if key not in kwargs.keys():
                    raise Exception('[Song] object was not mappable.')

            self.__is_loaded = True

            self.title = kwargs['title']
            self.artist = kwargs['artist']
            self.album = kwargs['album']
            self.track = kwargs['track']
            self.length = kwargs['length']
            self.comment = kwargs['comment']
            self.genre = kwargs['genre']
            self.year = kwargs['year']
            self.filename = kwargs['filename']
            self.statistics = self.__get_statistics()
    def load(self, force_reload=False):
        if not force_reload and len(self.stored_result) > 0:
            # Return the already loaded songs
            return self.stored_result
        else:
            # Load the songs
            sqlite = SQLite()
            cursor = sqlite.execute('select * from songs order by '
                                    'artist, album, title')
            songs = cursor.fetchall()
            sqlite.close()

            return songs
Beispiel #6
0
    def __get_statistics(self):
        if self.__is_loaded:
            sql = SQLite()
            cur_nb = sql.execute('select * from stats_songs where ' +
                                 'filename=:file', {'file': self.filename})
            song = cur_nb.fetchone()

            if song is not None:
                times_played = song[1]
            else:
                times_played = 0

            sql.close()
            return times_played
        else:
            raise Exception('[Song] object was not loaded.')
    def populate(self, playlist_id):
        if playlist_id in (1, 2):
            # Automatic playlists based on listening stats
            if playlist_id == 1:
                tb = 'stats_songs'
                lm = 50
            elif playlist_id == 2:
                tb = 'stats_albums'
                lm = 10

            result = []
            txt = ('select * from %s order by tracks desc limit %u' % (tb, lm))

            sql = SQLite()
            cur = sql.execute(txt)
            for sg in cur:
                result.append(sg)
            sql.close()

            for item in result:
                if playlist_id == 1:
                    sng = Song(filename=item[0])
                    if hasattr(sng, 'title'):
                        self.on_new_song_queued(sng)
                elif playlist_id == 2:
                    album_name = item[0]
                    for it in self.songs_tree:
                        if album_name in self.songs_tree[it]:
                            self.on_new_album_queued(Album(it, album_name,
                                                           self.songs_tree))
                            break
        elif playlist_id > 3:
            # User-created playlists
            user_plist = self.user_playlists[playlist_id]
            plist = self.playlists_mgmnt.load_playlist(user_plist)

            for item in plist:
                sng = Song(filename=item)
                if hasattr(sng, 'title'):
                    self.on_new_song_queued(sng)
Beispiel #8
0
    def increment_statistics(self):
        if self.__is_loaded:
            sql_insert = [
                'insert into stats_songs (filename, tracks) values (?, ?)',
                [self.filename, int(self.statistics + 1)]
            ]

            sql_update = [
                'update stats_songs set tracks=:value where filename=:file',
                {'file': self.filename, 'value': int(self.statistics + 1)}
            ]

            sql = SQLite()
            if self.statistics == 0:
                sql.execute(sql_insert[0], sql_insert[1])
            else:
                sql.execute(sql_update[0], sql_update[1])

            self.statistics = int(self.statistics + 1)

            sql.close()
        else:
            raise Exception('[Song] object was not loaded.')
    def do_scan(self, wdg=None):
        """This function scan the music directory."""
        songs = list()
        songs_filename = list()
        songs_artists = list()
        songs_albums = list()
        nb_song = 0
        fileregxp = re_compile('.+\.(flac|ogg|oga|mp3)$')

        # Walk in the music folder
        folder = self.folder

        song_files = list()
        for (dir_, rep, files) in walk(folder):
            for file_ in files:
                if fileregxp.match(file_):
                    nb_song += 1
                    song_files.append(join(dir_, file_))

        if wdg is not None:
            idle_add(wdg[0].set_text, _('Found %d songs.' % len(song_files)))
            idle_add(wdg[1].set_fraction, 0)

        id_song = 0
        ok_song = 0
        for song in song_files:
            id_song += 1

            try:
                exif = TagLibFile(song)
                if all(k in exif.tags.keys()
                       for k in ('TITLE', 'ARTIST', 'ALBUM', 'TRACKNUMBER')):
                    ok_song += 1
                    filename = song

                    title = exif.tags['TITLE'][0]
                    artist = exif.tags['ARTIST'][0]
                    album = exif.tags['ALBUM'][0]
                    track = exif.tags['TRACKNUMBER'][0]

                    length = exif.length

                    if 'COMMENT' in exif.tags:
                        try:
                            comment = exif.tags['COMMENT'][0]
                        except IndexError:
                            comment = ''
                    else:
                        comment = ''

                    if 'GENRE' in exif.tags:
                        try:
                            genre = exif.tags['GENRE'][0]
                        except IndexError:
                            genre = ''
                    else:
                        genre = ''

                    if 'DATE' in exif.tags:
                        try:
                            year = exif.tags['DATE'][0]
                        except IndexError:
                            year = ''
                    else:
                        year = ''

                    if wdg is not None and id_song % 5:
                        idle_add(wdg[1].set_fraction,
                                 float(id_song) / float(nb_song))
                        idle_add(wdg[0].set_text,
                                 _('Added %d songs.' % id_song))

                    songs_filename.append(filename)
                    songs_artists.append(artist)
                    songs_albums.append(album)

                    songs.append((title, artist, album, comment, genre, year,
                                  track, length, filename))
                else:
                    raise OSError
            except OSError:
                idle_add(print, '[ERROR] Unable to import %s' % song)

        if wdg is not None:
            idle_add(
                wdg[0].set_text,
                _('Metadata retrieved for %d songs. Updating database…' %
                  len(songs)))

        idle_add(
            print,
            '[RELOAD] Imported %d songs from %d founded.' % (ok_song, id_song))

        # Serialize songs
        sqlite = SQLite()
        sqlite.execute('delete from songs')
        sqlite.executemany(
            'insert into songs (title, artist, album, '
            'comment, genre, year, track, length, filename) '
            'values (?, ?, ?, ?, ?, ?, ?, ?, ?)', songs)

        # Update songs
        cursor = sqlite.execute('select * from stats_songs')
        for song in cursor.fetchall():
            filename = song[0]

            if filename not in songs_filename:
                # Delete this songs from statistics
                sqlite.execute('delete from stats_songs where filename=:val',
                               {'val': filename})

        # Update artists
        cursor = sqlite.execute('select * from stats_artists')
        for artist in cursor.fetchall():
            artist = artist[0]

            if artist not in songs_artists:
                # Delete this artist from statistics
                sqlite.execute('delete from stats_artists where artist=:val',
                               {'val': artist})

        # Update albums
        cursor = sqlite.execute('select * from stats_albums')
        for album in cursor.fetchall():
            album = album[0]

            if album not in songs_albums:
                # Delete this album from statistics
                sqlite.execute('delete from stats_albums where album=:val',
                               {'val': album})

        # The job is ended o/
        sqlite.close()