2009-08-05 08:59:46 +00:00
|
|
|
# Created By: Virgil Dupras
|
|
|
|
# Created On: 2006/11/16
|
2012-03-15 18:28:40 +00:00
|
|
|
# Copyright 2012 Hardcoded Software (http://www.hardcoded.net)
|
2009-08-05 08:59:46 +00:00
|
|
|
#
|
2010-09-30 10:17:41 +00:00
|
|
|
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
|
2009-08-05 08:59:46 +00:00
|
|
|
# which should be included with this package. The terms are also available at
|
2010-09-30 10:17:41 +00:00
|
|
|
# http://www.hardcoded.net/licenses/bsd_license
|
2009-08-05 08:59:46 +00:00
|
|
|
|
2009-06-01 09:55:11 +00:00
|
|
|
import logging
|
2012-02-21 15:23:23 +00:00
|
|
|
import plistlib
|
2009-06-01 09:55:11 +00:00
|
|
|
import time
|
2011-09-20 22:40:27 +00:00
|
|
|
import os.path as op
|
2012-07-07 19:44:13 +00:00
|
|
|
from appscript import app, its, k, CommandError, ApplicationNotFoundError
|
|
|
|
from . import tunes
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2012-02-21 15:23:23 +00:00
|
|
|
from cocoa import as_fetch, proxy
|
2012-02-27 15:12:36 +00:00
|
|
|
from hscommon.trans import trget
|
2012-02-21 15:23:23 +00:00
|
|
|
from hscommon.path import Path
|
2012-06-13 17:11:48 +00:00
|
|
|
from hscommon.util import remove_invalid_xml
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2012-02-21 15:23:23 +00:00
|
|
|
from core import directories
|
2011-09-21 17:55:26 +00:00
|
|
|
from core.app import JobType
|
2012-01-16 15:30:45 +00:00
|
|
|
from core.scanner import ScanType
|
2011-09-21 20:02:13 +00:00
|
|
|
from core_me.app import DupeGuru as DupeGuruBase
|
2012-02-21 15:23:23 +00:00
|
|
|
from core_me import fs
|
2012-01-16 15:30:45 +00:00
|
|
|
from .app import JOBID2TITLE, PyDupeGuruBase
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2012-02-27 15:12:36 +00:00
|
|
|
tr = trget('ui')
|
|
|
|
|
2011-09-21 17:55:26 +00:00
|
|
|
JobType.RemoveDeadTracks = 'jobRemoveDeadTracks'
|
|
|
|
JobType.ScanDeadTracks = 'jobScanDeadTracks'
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2009-10-23 14:35:51 +00:00
|
|
|
JOBID2TITLE.update({
|
2011-09-21 17:55:26 +00:00
|
|
|
JobType.RemoveDeadTracks: tr("Removing dead tracks from your iTunes Library"),
|
|
|
|
JobType.ScanDeadTracks: tr("Scanning the iTunes Library"),
|
2009-06-01 09:55:11 +00:00
|
|
|
})
|
|
|
|
|
2012-02-21 15:23:23 +00:00
|
|
|
ITUNES = 'iTunes'
|
|
|
|
ITUNES_PATH = Path('iTunes Library')
|
|
|
|
|
|
|
|
def get_itunes_library(a):
|
|
|
|
try:
|
|
|
|
[source] = [s for s in a.sources(timeout=0) if s.kind(timeout=0) == k.library]
|
|
|
|
[library] = source.library_playlists(timeout=0)
|
|
|
|
return library
|
|
|
|
except ValueError:
|
|
|
|
logging.warning('Some unexpected iTunes configuration encountered')
|
|
|
|
return None
|
|
|
|
|
|
|
|
class ITunesSong(fs.MusicFile):
|
|
|
|
def __init__(self, song_data):
|
|
|
|
path = Path(proxy.url2path_(song_data['Location']))
|
|
|
|
fs.MusicFile.__init__(self, path)
|
|
|
|
self.id = song_data['Track ID']
|
|
|
|
|
|
|
|
def remove_from_library(self):
|
|
|
|
try:
|
2012-07-07 19:44:13 +00:00
|
|
|
a = app(ITUNES, terms=tunes)
|
2012-02-21 15:23:23 +00:00
|
|
|
library = get_itunes_library(a)
|
|
|
|
if library is None:
|
|
|
|
return
|
|
|
|
[song] = library.file_tracks[its.database_ID == self.id]()
|
|
|
|
a.delete(song, timeout=0)
|
|
|
|
except ValueError:
|
2012-03-17 16:13:58 +00:00
|
|
|
msg = "Could not find song '{}' (trackid: {}) in iTunes Library".format(str(self.path), self.id)
|
2012-02-21 15:23:23 +00:00
|
|
|
raise EnvironmentError(msg)
|
|
|
|
except (CommandError, RuntimeError) as e:
|
|
|
|
raise EnvironmentError(str(e))
|
|
|
|
|
|
|
|
display_folder_path = ITUNES_PATH
|
|
|
|
|
|
|
|
def get_itunes_database_path():
|
|
|
|
plisturls = proxy.prefValue_inDomain_('iTunesRecentDatabases', 'com.apple.iApps')
|
|
|
|
if not plisturls:
|
|
|
|
raise directories.InvalidPathError()
|
|
|
|
plistpath = proxy.url2path_(plisturls[0])
|
|
|
|
return Path(plistpath)
|
|
|
|
|
|
|
|
def get_itunes_songs(plistpath):
|
2012-08-09 14:53:24 +00:00
|
|
|
if not plistpath.exists():
|
2012-02-21 15:23:23 +00:00
|
|
|
return []
|
2012-08-09 14:53:24 +00:00
|
|
|
s = plistpath.open('rt', encoding='utf-8').read()
|
2012-06-13 17:11:48 +00:00
|
|
|
# iTunes sometimes produces XML files with invalid characters in it.
|
|
|
|
s = remove_invalid_xml(s, replace_with='')
|
|
|
|
plist = plistlib.readPlistFromBytes(s.encode('utf-8'))
|
2012-02-21 15:23:23 +00:00
|
|
|
result = []
|
|
|
|
for song_data in plist['Tracks'].values():
|
2012-04-13 19:21:48 +00:00
|
|
|
try:
|
2012-08-09 14:01:44 +00:00
|
|
|
if song_data['Track Type'] != 'File':
|
|
|
|
continue
|
2012-04-13 19:21:48 +00:00
|
|
|
song = ITunesSong(song_data)
|
2012-08-09 14:01:44 +00:00
|
|
|
except KeyError: # No "Track Type", "Location" or "Track ID" key in track
|
2012-04-13 19:21:48 +00:00
|
|
|
continue
|
2012-08-09 14:53:24 +00:00
|
|
|
if song.path.exists():
|
2012-02-21 15:23:23 +00:00
|
|
|
result.append(song)
|
|
|
|
return result
|
|
|
|
|
|
|
|
class Directories(directories.Directories):
|
|
|
|
def __init__(self, fileclasses):
|
|
|
|
directories.Directories.__init__(self, fileclasses)
|
|
|
|
try:
|
|
|
|
self.itunes_libpath = get_itunes_database_path()
|
|
|
|
except directories.InvalidPathError:
|
|
|
|
self.itunes_libpath = None
|
|
|
|
|
|
|
|
def _get_files(self, from_path, j):
|
|
|
|
if from_path == ITUNES_PATH:
|
|
|
|
if self.itunes_libpath is None:
|
|
|
|
return []
|
|
|
|
is_ref = self.get_state(from_path) == directories.DirectoryState.Reference
|
|
|
|
songs = get_itunes_songs(self.itunes_libpath)
|
|
|
|
for song in songs:
|
|
|
|
song.is_ref = is_ref
|
|
|
|
return songs
|
|
|
|
else:
|
|
|
|
return directories.Directories._get_files(self, from_path, j)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_subfolders(path):
|
|
|
|
if path == ITUNES_PATH:
|
|
|
|
return []
|
|
|
|
else:
|
|
|
|
return directories.Directories.get_subfolders(path)
|
|
|
|
|
|
|
|
def add_path(self, path):
|
|
|
|
if path == ITUNES_PATH:
|
|
|
|
if path not in self:
|
|
|
|
self._dirs.append(path)
|
|
|
|
else:
|
|
|
|
directories.Directories.add_path(self, path)
|
|
|
|
|
|
|
|
def has_itunes_path(self):
|
|
|
|
return any(path == ITUNES_PATH for path in self._dirs)
|
|
|
|
|
|
|
|
def has_any_file(self):
|
|
|
|
# If we don't do that, it causes a hangup in the GUI when we click Start Scanning because
|
|
|
|
# checking if there's any file to scan involves reading the whole library. If we have the
|
|
|
|
# iTunes library, we assume we have at least one file.
|
|
|
|
if self.has_itunes_path():
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return directories.Directories.has_any_file(self)
|
|
|
|
|
|
|
|
|
2009-10-23 14:35:51 +00:00
|
|
|
class DupeGuruME(DupeGuruBase):
|
2011-09-20 22:40:27 +00:00
|
|
|
def __init__(self, view, appdata):
|
|
|
|
appdata = op.join(appdata, 'dupeGuru Music Edition')
|
|
|
|
DupeGuruBase.__init__(self, view, appdata)
|
2012-02-21 15:23:23 +00:00
|
|
|
# Use fileclasses set in DupeGuruBase.__init__()
|
|
|
|
self.directories = Directories(fileclasses=self.directories.fileclasses)
|
2009-06-01 09:55:11 +00:00
|
|
|
self.dead_tracks = []
|
|
|
|
|
2012-08-01 16:36:23 +00:00
|
|
|
def _do_delete(self, j, *args):
|
2012-02-21 15:23:23 +00:00
|
|
|
# XXX If I read correctly, Python 3.3 will allow us to go fetch inner function easily, so
|
|
|
|
# we'll be able to replace "op" below with DupeGuruBase._do_delete.op.
|
|
|
|
def op(dupe):
|
|
|
|
j.add_progress()
|
2012-08-01 16:36:23 +00:00
|
|
|
return self._do_delete_dupe(dupe, *args)
|
2012-02-21 15:23:23 +00:00
|
|
|
|
|
|
|
marked = [dupe for dupe in self.results.dupes if self.results.is_marked(dupe)]
|
|
|
|
j.start_job(self.results.mark_count, tr("Sending dupes to the Trash"))
|
|
|
|
if any(isinstance(dupe, ITunesSong) for dupe in marked):
|
|
|
|
j.add_progress(0, desc=tr("Talking to iTunes. Don't touch it!"))
|
|
|
|
try:
|
2012-07-07 19:44:13 +00:00
|
|
|
a = app(ITUNES, terms=tunes)
|
2012-02-21 15:23:23 +00:00
|
|
|
a.activate(timeout=0)
|
|
|
|
except (CommandError, RuntimeError, ApplicationNotFoundError):
|
|
|
|
pass
|
|
|
|
self.results.perform_on_marked(op, True)
|
|
|
|
|
2012-08-01 16:36:23 +00:00
|
|
|
def _do_delete_dupe(self, dupe, *args):
|
2012-02-21 15:23:23 +00:00
|
|
|
if isinstance(dupe, ITunesSong):
|
|
|
|
dupe.remove_from_library()
|
2012-08-01 16:36:23 +00:00
|
|
|
DupeGuruBase._do_delete_dupe(self, dupe, *args)
|
2012-02-21 15:23:23 +00:00
|
|
|
|
|
|
|
def _create_file(self, path):
|
|
|
|
if (self.directories.itunes_libpath is not None) and (path in self.directories.itunes_libpath[:-1]):
|
2012-03-17 16:13:58 +00:00
|
|
|
if not hasattr(self, 'itunes_songs'):
|
|
|
|
songs = get_itunes_songs(self.directories.itunes_libpath)
|
|
|
|
self.itunes_songs = {song.path: song for song in songs}
|
|
|
|
if path in self.itunes_songs:
|
|
|
|
return self.itunes_songs[path]
|
|
|
|
else:
|
|
|
|
pass # We'll return the default file type, as per the last line of this method
|
2012-02-21 15:23:23 +00:00
|
|
|
return DupeGuruBase._create_file(self, path)
|
|
|
|
|
2012-03-09 16:34:08 +00:00
|
|
|
def _job_completed(self, jobid, exc):
|
|
|
|
if (jobid in {JobType.RemoveDeadTracks, JobType.ScanDeadTracks}) and (exc is not None):
|
|
|
|
msg = tr("There were communication problems with iTunes. The operation couldn't be completed.")
|
|
|
|
self.view.show_message(msg)
|
|
|
|
return True
|
|
|
|
if jobid == JobType.ScanDeadTracks:
|
|
|
|
dead_tracks_count = len(self.dead_tracks)
|
|
|
|
if dead_tracks_count > 0:
|
|
|
|
msg = tr("Your iTunes Library contains %d dead tracks ready to be removed. Continue?")
|
|
|
|
if self.view.ask_yes_no(msg % dead_tracks_count):
|
|
|
|
self.remove_dead_tracks()
|
|
|
|
else:
|
|
|
|
msg = tr("You have no dead tracks in your iTunes Library")
|
|
|
|
self.view.show_message(msg)
|
2012-03-17 16:13:58 +00:00
|
|
|
if jobid == JobType.Load:
|
|
|
|
if hasattr(self, 'itunes_songs'):
|
|
|
|
# If we load another file, we want a refresh song list
|
|
|
|
del self.itunes_songs
|
2012-03-09 16:34:08 +00:00
|
|
|
DupeGuruBase._job_completed(self, jobid, exc)
|
|
|
|
|
2012-02-21 15:23:23 +00:00
|
|
|
def copy_or_move(self, dupe, copy, destination, dest_type):
|
|
|
|
if isinstance(dupe, ITunesSong):
|
|
|
|
copy = True
|
|
|
|
return DupeGuruBase.copy_or_move(self, dupe, copy, destination, dest_type)
|
|
|
|
|
|
|
|
def start_scanning(self):
|
|
|
|
if self.directories.has_itunes_path():
|
|
|
|
try:
|
2012-07-07 19:44:13 +00:00
|
|
|
app(ITUNES, terms=tunes)
|
2012-02-21 15:23:23 +00:00
|
|
|
except ApplicationNotFoundError:
|
|
|
|
self.view.show_message(tr("The iTunes application couldn't be found."))
|
|
|
|
return
|
|
|
|
DupeGuruBase.start_scanning(self)
|
|
|
|
|
2009-06-01 09:55:11 +00:00
|
|
|
def remove_dead_tracks(self):
|
|
|
|
def do(j):
|
2012-07-07 19:44:13 +00:00
|
|
|
a = app(ITUNES, terms=tunes)
|
2009-06-10 13:54:24 +00:00
|
|
|
a.activate(timeout=0)
|
2009-06-01 09:55:11 +00:00
|
|
|
for index, track in enumerate(j.iter_with_progress(self.dead_tracks)):
|
|
|
|
if index % 100 == 0:
|
|
|
|
time.sleep(.1)
|
|
|
|
try:
|
2009-06-10 13:54:24 +00:00
|
|
|
track.delete(timeout=0)
|
2009-06-01 09:55:11 +00:00
|
|
|
except CommandError as e:
|
2010-08-11 14:39:06 +00:00
|
|
|
logging.warning('Error while trying to remove a track from iTunes: %s' % str(e))
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2011-09-21 17:55:26 +00:00
|
|
|
self.view.start_job(JobType.RemoveDeadTracks, do)
|
2009-06-01 09:55:11 +00:00
|
|
|
|
|
|
|
def scan_dead_tracks(self):
|
|
|
|
def do(j):
|
2012-07-07 19:44:13 +00:00
|
|
|
a = app(ITUNES, terms=tunes)
|
2009-06-10 13:54:24 +00:00
|
|
|
a.activate(timeout=0)
|
2012-02-21 15:23:23 +00:00
|
|
|
library = get_itunes_library(a)
|
|
|
|
if library is None:
|
2009-06-01 09:55:11 +00:00
|
|
|
return
|
|
|
|
self.dead_tracks = []
|
|
|
|
tracks = as_fetch(library.file_tracks, k.file_track)
|
|
|
|
for index, track in enumerate(j.iter_with_progress(tracks)):
|
|
|
|
if index % 100 == 0:
|
|
|
|
time.sleep(.1)
|
2009-06-10 13:54:24 +00:00
|
|
|
if track.location(timeout=0) == k.missing_value:
|
2009-06-01 09:55:11 +00:00
|
|
|
self.dead_tracks.append(track)
|
|
|
|
logging.info('Found %d dead tracks' % len(self.dead_tracks))
|
|
|
|
|
2011-09-21 17:55:26 +00:00
|
|
|
self.view.start_job(JobType.ScanDeadTracks, do)
|
2009-06-01 09:55:11 +00:00
|
|
|
|
2012-01-16 15:30:45 +00:00
|
|
|
class PyDupeGuru(PyDupeGuruBase):
|
|
|
|
def __init__(self):
|
|
|
|
self._init(DupeGuruME)
|
|
|
|
|
|
|
|
def scanDeadTracks(self):
|
|
|
|
self.model.scan_dead_tracks()
|
|
|
|
|
|
|
|
#---Properties
|
|
|
|
def setMinMatchPercentage_(self, percentage: int):
|
|
|
|
self.model.scanner.min_match_percentage = percentage
|
|
|
|
|
|
|
|
def setScanType_(self, scan_type: int):
|
|
|
|
try:
|
|
|
|
self.model.scanner.scan_type = [
|
|
|
|
ScanType.Filename,
|
|
|
|
ScanType.Fields,
|
|
|
|
ScanType.FieldsNoOrder,
|
|
|
|
ScanType.Tag,
|
|
|
|
ScanType.Contents,
|
|
|
|
ScanType.ContentsAudio,
|
|
|
|
][scan_type]
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def setWordWeighting_(self, words_are_weighted: bool):
|
|
|
|
self.model.scanner.word_weighting = words_are_weighted
|
|
|
|
|
|
|
|
def setMatchSimilarWords_(self, match_similar_words: bool):
|
|
|
|
self.model.scanner.match_similar_words = match_similar_words
|
|
|
|
|
|
|
|
def enable_scanForTag_(self, enable: bool, scan_tag: str):
|
|
|
|
if enable:
|
|
|
|
self.model.scanner.scanned_tags.add(scan_tag)
|
|
|
|
else:
|
|
|
|
self.model.scanner.scanned_tags.discard(scan_tag)
|