Source

VPlayer / directoryscanner.py

Full commit
# -*- coding: utf-8 -*-

import os

import chardet
import mutagen

from PyQt4 import QtCore, QtSql

from track import Track
from logger import log
from tagreader import TagReader
from vplayer import queries

class DirectoryScanner(QtCore.QThread):

    def __init__(self, directories, action = 'scan', cache = False):
        QtCore.QThread.__init__(self)
        self.directories = directories
        self.end = False
        self.files = []
        self.action = action
        self.cache = cache

    def run(self):
        self.emit(QtCore.SIGNAL('status'), 'start')
        if self.action == 'scan':
            log.debug('Creating list of files...')
            self.emit(QtCore.SIGNAL('progress'), 2)
            for directory in self.directories:
                os.path.walk(directory, self.filecount, directory)
            self.emit(QtCore.SIGNAL('progress'), 5)
            log.debug('Found %d files, scanning them...' % len(self.files))
            self.processor()
            self.end = True
        elif self.action == 'clean':
            self.clear_not_existing()
        self.emit(QtCore.SIGNAL('status'), 'end')

    def filecount(self, start, current, files):
        for filename in files:
            absname = os.path.join(current,filename)
            if os.path.isfile(absname):
                self.files.append(absname)
        log.debug('Found %d files' % len(self.files))

    def processor(self):
        reader = TagReader()
        done = 0
        for filename in self.files:
            tags = reader.read(filename)

            if tags['artist'] == 'Unknown' and tags['title'] == 'Unknown' \
               and tags['length'] == 0:
                continue
            track = Track(**tags)

            self.write_to_db(track)
            done += 1
            percent = int((float(done)/len(self.files))*(100-7))+7
            self.emit(QtCore.SIGNAL('progress'), percent)

    def write_to_db(self, track = None):
        if track:
            if queries.check_track_existance(track.url):
                log.debug('Updating track %s - already in db' % unicode(track))
                queries.insert_track(track, cache = self.cache)
            else:
                log.debug('Adding track %s' % unicode(track))
                queries.update_track(track)

    def clear_not_existing(self):
        if self.cache:
            files = queries.get_all_cached_files()
        else:
            files = queries.get_all_collection_files()
        done = 0
        for url in files:
            if not os.path.exists(url):
                queries.delete_track(url)
            done += 1
            self.emit(QtCore.SIGNAL('progress'), done)



#from sqlcollection import database
#db = database()

#d = DirectoryScanner(['/home/a2k/Music/Ария'])
#d.start()
#import time
#while True:
    #time.sleep(1)