-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrepear.py
More file actions
2015 lines (1781 loc) · 69.8 KB
/
repear.py
File metadata and controls
2015 lines (1781 loc) · 69.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# rePear, the iPod database management tool
# Copyright (C) 2006-2008 Martin J. Fiedler <martin.fiedler@gmx.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
__title__ = "rePear"
__version__ = "0.4.1"
__author__ = "Martin J. Fiedler"
__email__ = "martin.fiedler@gmx.net"
banner = "Welcome to %s, version %s" % (__title__, __version__)
"""
TODO: preserve .m3u playlists on update
0.4.1:
- added artwork formats for nano 4G
- added support for the 'mhii link' field, required for artwork on nano 4G
0.4.0:
- added command-line options to override master playlist and scrobble config
file names (either relative to the root directory or relative to the
working directory from which rePear is being run)
- fixed crash bug for rare broken ID3v2 tags
- added 'help' action
0.4.0-rc2:
- fixed crash after scrobbling
0.4.0-rc1:
- added configuration actions
- root directory auto-detection now checks current working directory, too
- fixed time calculations (required for proper scrobbling)
- fixed artwork processing if an artwork file is broken
- fixed broken sort function
0.4.0-beta1:
- added support for 2007 models (nano 3G, classic)
- added support for MPEG-4 audio files
- added experimental support for MPEG-4 video files
- added Play Counts import to update play and skip counts and ratings
- added last.fm scrobble support
- added 'update' action
- added playlist sort functionality
- added global playlist option "skip album playlists = no" to disable
pruning of album playlists
- added global playlist option "directory playlists = yes" to turn every
directory into a playlist
- fixed iTunesDB parser so it reads post-iTunes 7.1 files
- sped up MP3 parser by using Xing/LAME or FhG info tags, where available
- ^C menu asks whether to skip a single track or completely cancel freezing
- added --nowait option to bypass Win32 keypress waiting on quit
- made the freeze process much more error robust -- I/O errors in single
files won't stop the whole process any longer
- added crash handler
- fixed crash in the directory playlist construction code for Ogg->MP3
transcoded files
- fixed ID3v2.3.0 parser (thanks to Ian Camaclang for the patch!)
- added msvcr71.dll to Win32 distribution
- model list in help screen is now sorted
- unfreezing empty databases now works
- improved mtime comparison
- not importing dot-files and directories any longer
0.3.0:
- added playlist support -- two methods are availabe:
- the "master playlist file" in /repear_playlists.ini
- every *.m3u is collected and converted to a playlist, unless it exactly
covers an album (in which case it would be pointless)
- added Balanced Shuffle feature
- MP3 detection code is now more error-tolerant (doesn't clip the file at the
first broken frame any longer)
- added automatic inference of the compilation flag: if the album tag of all
files in a directory is the same, but the artists differ, the whole
directory will be marked as a compilation
- fixed crash when OggDec was not present
- added a filename allocator; should improve big (>10GB) iPod compatibility
- now guessing the track number from the file name even if there is an ID3v1.0
tag available
- when freezing, the cache file is now saved as early as possible to minimize
data loss if rePear crashes at a later point (e.g. playlist processing)
0.2.2:
- fixed endianness issue
- filename-based metadata guessing now includes track numbers
0.2.1:
- fixed album sort order
0.2.0:
- Artwork support
- limited automatic pathfinding on Windows systems: rePear needs to be
installed somewhere on the iPod volume, but not necessarily in the root
directory
0.1.1:
- make dissect less destructive (keep filenames)
- accept all full-hour time differences
- auto-create an iTunesDB backup
- create iTunesSD et al. -> iPod shuffle support
- automatic transcoding of Ogg Vorbis tracks
- some bugfixes
"""
DISSECT_BASE_DIR = "Dissected Tracks/"
DIRECTORY_COUNT = 10
DEFAULT_LAME_OPTS = "--quiet -h -V 5"
MASTER_PLAYLIST_FILE = "repear_playlists.ini"
SCROBBLE_CONFIG_FILE = "repear_scrobble.ini"
SUPPORTED_FILE_FORMATS = (".mp3", ".ogg", ".m4a", ".m4b", ".mp4")
MUSIC_DIR = "iPod_Control/Music/"
CONTROL_DIR = "iPod_Control/iTunes/"
ARTWORK_DIR = "iPod_Control/Artwork/"
DB_FILE = CONTROL_DIR + "iTunesDB"
CACHE_FILE = CONTROL_DIR + "repear.cache"
MODEL_FILE = CONTROL_DIR + "repear.model"
FWID_FILE = CONTROL_DIR + "fwid"
SCROBBLE_QUEUE_FILE = CONTROL_DIR + "repear.scrobble_queue"
ARTWORK_CACHE_FILE = ARTWORK_DIR + "repear.artwork_cache"
ARTWORK_DB_FILE = ARTWORK_DIR + "ArtworkDB"
def OLDNAME(x): return x.replace("repear", "retune")
import sys, optparse, os, fnmatch, stat, string, time, types, cPickle, random
import re, warnings, traceback, getpass, md5
warnings.filterwarnings('ignore', category=RuntimeWarning) # for os.tempnam()
import iTunesDB, mp3info, hash58, scrobble
Options = {}
################################################################################
## Some internal management functions ##
################################################################################
broken_log = False
homedir = ""
def open_log():
global logfile
Options['log'] = os.path.abspath(Options['log'])
try:
logfile = open(Options['log'], "w")
except IOError:
logfile = None
def log(line, flush=True):
global logfile
sys.stdout.write(line)
if flush: sys.stdout.flush()
if logfile:
try:
logfile.write(line)
if flush: logfile.flush()
except IOError:
broken_log = True
iTunesDB.log = log
def quit(code=1):
global logfile, broken_log
if logfile:
try:
logfile.close()
except IOError:
broken_log = True
logfile = None
log("\nLog written to `%s'\n" % Options['log'])
if broken_log:
log("WARNING: there were errors while writing the log file\n")
if not Options.get('nowait', True): # Windows: wait for keypress
log("Press ENTER to close this window. ", True)
try:
raw_input()
except (IOError, EOFError, KeyboardInterrupt):
pass # I don't care at this point, we're going to leave anyway
sys.exit(code)
def fatal(line):
log("FATAL: %s\n" % line)
quit()
def confirm(prompt):
sys.stdout.write("%sDo you really want to continue? (y/N) " % prompt)
sys.stdout.flush()
try:
answer = raw_input()
except (IOError, EOFError, KeyboardInterrupt):
answer = ""
if answer.strip().lower() in ("y", "yes"):
return
log("Action aborted by user.\n")
quit()
def goto_root_dir():
global homedir
homedir = os.path.abspath(os.path.split(sys.argv[0])[0]).replace("\\", "/")
if homedir[-1] != '/': homedir += '/'
if Options['root']:
rootdir = Options['root'].replace("\\", "/")
if rootdir[-1] != '/': rootdir += '/'
else:
# no root directory specified -- try the current directory
rootdir = os.getcwd().replace("\\", "/")
if rootdir[-1] != '/': rootdir += '/'
if not os.path.isfile(rootdir + "iPod_Control/iTunes/iTunesDB"):
# not found? then try the executable's directory
rootdir = homedir
# special case on Windows: if the current directory doesn't contain
# a valid iPod directory structure, reduce the pathname to the first
# three characters, as in 'X:/', which is usually the root directory
if (os.name == 'nt') and not(os.path.isfile(rootdir + DB_FILE)):
rootdir = rootdir[:3]
if os.path.isfile(rootdir + DB_FILE):
log("iPod root directory is `%s'\n" % rootdir)
else:
fatal("root directory `%s' contains no iPod database" % rootdir)
try:
os.chdir(rootdir)
except OSError, e:
fatal("can't change to the iPod root directory: %s" % e.strerror)
def load_cache(return_on_error=None):
try:
f = open(CACHE_FILE, "rb")
except IOError:
try:
f = open(OLDNAME(CACHE_FILE), "rb")
except IOError:
return return_on_error
try:
content = cPickle.load(f)
f.close()
except (IOError, EOFError, cPickle.PickleError):
return return_on_error
return content
def save_cache(content=None):
try:
f = open(CACHE_FILE, "wb")
cPickle.dump(content, f)
f.close()
delete(OLDNAME(CACHE_FILE), True)
except (IOError, EOFError, cPickle.PickleError):
log("ERROR: can't save the rePear cache\n")
def execute(program, args):
global homedir
if os.name == "nt":
spawn = os.spawnv
path = homedir + program + ".exe"
args = ["\"%s\"" % arg for arg in args]
else:
spawn = os.spawnvp
path = program
try:
return spawn(os.P_WAIT, path, [program] + args)
except OSError, e:
log("ERROR: can't execute %s: %s\n" % (program, e.strerror))
except KeyboardInterrupt:
return -2
################################################################################
## Some generic tool functions ##
################################################################################
def printable(x, kill_chars=""):
if type(x)==types.UnicodeType:
x = x.encode(sys.getfilesystemencoding(), 'replace')
x = str(x)
for c in kill_chars:
x = x.replace(c, "_")
return x
def move_file(src, dest):
# check if source file exists
if not os.path.isfile(src):
log("[FAILED]\nERROR: source file `%s' doesn't exist\n" %
printable(src), True)
return 'missing'
# don't clobber files (wouldn't work on Windows anyway)
if os.path.isfile(dest):
log("[FAILED]\nERROR: destination file `%s' already exists\n" %
printable(dest), True)
return 'exists'
# create parent directories if necessary
dest_dir = os.path.split(dest)[0]
if dest_dir and not(os.path.isdir(dest_dir)):
try:
os.makedirs(dest_dir)
except OSError, e:
log("[FAILED]\nERROR: can't create destination directory `%s': %s\n" %
(printable(dest_dir), e.strerror), True)
return 'mkdir'
# finally rename it
try:
os.rename(src, dest)
except OSError, e:
log(" [FAILED]\nERROR: can't move `%s' to `%s': %s\n" %
(printable(src), printable(dest), e.strerror), True)
return 'move'
log("[OK]\n", True)
return None
def backup(filename):
dest = "%s.repear_backup" % filename
if os.path.exists(dest): return
try:
os.rename(filename, dest)
return True
except OSError, e:
log("WARNING: Cannot backup `%s': %s\n" % (filename, e.strerror))
return False
def delete(filename, may_fail=False):
if not os.path.exists(filename): return
try:
os.remove(filename)
return True
except OSError, e:
if not may_fail:
log("ERROR: Cannot delete `%s': %s\n" % (filename, e.strerror))
return False
class ExceptionLogHelper:
def write(self, s):
log(s)
Logger = ExceptionLogHelper()
# path and file name sorting routines
re_digit = re.compile(r'(\d+)')
def tryint(s):
try: return int(s)
except ValueError: return s.lower()
def fnrep(fn):
return tuple(map(tryint, re_digit.split(fn)))
def fncmp(a, b):
return cmp(fnrep(a), fnrep(b))
def pathcmp(a, b):
a = a.split(u'/')
b = b.split(u'/')
# compare base directories
for i in xrange(min(len(a), len(b)) - 1):
r = fncmp(a[i], b[i])
if r: return r
# subdirectories first
r = len(b) - len(a)
if r: return r
# finally, compare leaf file name
return fncmp(a[-1], b[-1])
def trackcmp(a, b):
return pathcmp(a.get('original path', None) or a.get('path', '???'), \
b.get('original path', None) or b.get('path', '???'))
################################################################################
## Filename Allocator ##
################################################################################
class Allocator:
def __init__(self, root, files_per_dir=100, max_dirs=100):
self.root = root
self.files_per_dir = files_per_dir
self.max_dirs = max_dirs
self.names = {}
self.files = {}
digits = []
digits = []
try:
dirs = os.listdir(root)
except OSError:
os.mkdir(root)
dirs = []
for elem in dirs:
try:
index = self.getindex(elem)
except ValueError:
continue
self.names[index] = elem
self.files[index] = self.scandir(os.path.join(root, elem))
digits.append(len(elem) - 1)
if digits:
digits.sort()
self.fmt = "F%%0%dd" % (digits[len(digits) / 2])
else:
self.fmt = "F%02d"
if not self.files:
self.mkdir(0)
self.current_dir = min(self.files.iterkeys())
def getindex(self, name):
if not name: raise ValueError
if name[0].upper() != 'F': raise ValueError
return int(name[1:], 10)
def scandir(self, root):
try:
dir_contents = os.listdir(root)
except OSError:
return []
dir_contents = [os.path.splitext(x)[0].upper() for x in dir_contents if x[0] != '.']
return dict(zip(dir_contents, [None] * len(dir_contents)))
def __len__(self):
return sum(map(len, self.files.itervalues()))
def __repr__(self):
return "<Allocator: %d files in %d directories>" % (len(self), len(self.files))
def allocate_ex(self, index):
while True:
name = "".join([random.choice(string.ascii_uppercase) for x in range(4)])
if not(name in self.files[index]):
break
self.files[index][name] = None
return self.names[index] + '/' + name
def mkdir(self, index):
if index in self.files:
return
name = self.fmt % index
try:
os.mkdir(os.path.join(self.root, name))
except OSError:
pass
self.names[index] = name
self.files[index] = {}
def allocate(self):
count, index = min([(len(d[1]), d[0]) for d in self.files.iteritems()])
# need to allocate a new directory
if (count >= self.files_per_dir) and (len(self.files) < self.max_dirs):
available = [i for i in range(self.max_dirs) if not i in self.files]
index = available[0]
self.mkdir(index)
# generate a file name
while True:
name = "".join([random.choice(string.ascii_uppercase) for x in range(4)])
if not(name in self.files[index]):
break
self.files[index][name] = None
return self.root + '/' + self.names[index] + '/' + name
def add(self, fullname):
try:
dirname, filename = fullname.split('/')[-2:]
index = self.getindex(dirname)
except ValueError:
return
filename = os.path.splitext(filename)[0]
if not index in self.files:
self.names[index] = dirname
self.files[index] = {}
self.files[index][filename] = None
################################################################################
## Balanced Shuffle ##
################################################################################
class BalancedShuffle:
def __init__(self):
self.root = { None: [] }
def add(self, path, data):
if type(path) == types.UnicodeType:
path = path.encode('ascii', 'replace')
path = path.replace("\\", "/").lower().split("/")
if path and not(path[0]):
path.pop(0)
if not path:
return # broken path
root = self.root
while True:
if len(path) == 1:
# tail reached
root[None].append(data)
break
component = path.pop(0)
if not component in root:
root[component] = { None: [] }
root = root[component]
def shuffle(self, root=None):
if not root:
root = self.root
# shuffle the files of the root node
random.shuffle(root[None])
# build a list of directories to shuffle
subdirs = filter(None, [root[None]] + \
[self.shuffle(root[key]) for key in root if key])
# check for "tail" cases
if not subdirs:
return []
if len(subdirs) == 1:
return subdirs[0]
# pad subdirectory list to a common length
dircount = len(subdirs)
maxlen = max(map(len, subdirs))
subdirs = [self.fill(sd, maxlen) for sd in subdirs]
# collect all items
res = []
last = -1
for i in xrange(maxlen):
# determine the directory order for this "column"
order = range(dircount)
random.shuffle(order)
if (len(order) > 1) and (order[0] == last):
order.append(order.pop(0))
while len(order) > 1: # = if len(order) > 1: while True:
random.shuffle(order)
if last != order[0]: break
last = order[-1]
# produce a result
res.extend(filter(lambda x: x is not None, \
[subdirs[j][i] for j in order]))
return res
def fill(self, data, total):
ones = len(data)
invert = (ones > (total / 2))
if invert:
ones = total - ones
bitmap = [0] * total
remain = total
for fraction in xrange(ones, 0, -1):
bitmap[total - remain] = 1
skip = float(remain) / fraction
skip = random.randrange(int(0.9 * skip), int(1.1 * skip) + 2)
remain -= min(max(1, skip), remain - fraction + 1)
if invert:
bitmap = [1-x for x in bitmap]
offset = random.randrange(0, total)
bitmap = bitmap[offset:] + bitmap[:offset]
def decide(x):
if x: return data.pop(0)
return None
return map(decide, bitmap)
################################################################################
## Play Counts import and Scrobbling ##
################################################################################
def ImportPlayCounts(cache, index, scrobbler=None):
log("Updating play counts and ratings ... ", True)
# open Play Counts file
try:
pc = iTunesDB.PlayCountsReader()
except IOError:
log("\n0 track(s) updated.\n")
return False
except iTunesDB.InvalidFormat:
log("\n-- Error in Play Counts file, import failed.\n")
return False
# parse old iTunesDB
try:
db = iTunesDB.DatabaseReader()
files = [printable(item.get('path', u'??')[1:].replace(u':', u'/')).lower() for item in db]
db.f.close()
del db
except (IOError, iTunesDB.InvalidFormat):
log("\n-- Error in iTunesDB, import failed.\n")
return False
# plausability check
if len(files) != pc.entry_count:
log("\n-- Mismatch between iTunesDB and Play Counts file, import failed.\n")
return False
# walk through Play Counts file
update_count = 0
try:
for item in pc:
path = files[item.index]
try:
track = cache[index[path]]
except (KeyError, IndexError):
continue
updated = False
if item.play_count:
track['play count'] = track.get('play count', 0) + item.play_count
updated = True
if item.last_played:
track['last played time'] = item.last_played
updated = True
if item.skip_count:
track['skip count'] = track.get('skip count', 0) + item.skip_count
updated = True
if item.last_skipped:
track['last skipped time'] = item.last_skipped
updated = True
if item.bookmark:
track['bookmark time'] = item.bookmark * 0.001
updated = True
if item.rating:
track['rating'] = item.rating
updated = True
if updated:
update_count += 1
if item.play_count and scrobbler:
scrobbler += track
pc.f.close()
del pc
except (IOError, iTunesDB.InvalidFormat):
log("\n-- Error in Play Counts file, import failed.\n")
return False
log("%d track(s) updated.\n" % update_count)
return update_count
################################################################################
## DISSECT action ##
################################################################################
def Dissect():
state, cache = load_cache((None, None))
if (state is not None) and not(Options['force']):
if state=="frozen": confirm("""
WARNING: This action will put all the music files on your iPod into a completely
new directory structure. All previous file and directory names will be lost.
This also means that any iTunesDB backups you have will NOT work any longer!
""")
if state=="unfrozen": confirm("""
WARNING: The database is currently unfrozen, so the following operations will
almost completely fail.
""")
cache = []
try:
db = iTunesDB.DatabaseReader()
for info in db:
if not info.get('path', None):
log("ERROR: track lacks path attribute\n")
continue
src = printable(info['path'])[1:].replace(":", "/")
if not os.path.isfile(src):
log("ERROR: file `%s' is found in database, but doesn't exist\n" % src)
continue
if not info.get('title', None):
info.update(iTunesDB.GuessTitleAndArtist(info['path']))
ext = os.path.splitext(src)[1]
base = DISSECT_BASE_DIR
if info.get('artist', None):
base += printable(info['artist'], "<>/\\:|?*\"") + '/'
if info.get('album', None):
base += printable(info['album'], "<>/\\:|?*\"") + '/'
if info.get('track number', None):
base += "%02d - " % info['track number']
base += printable(info['title'], "<>/\\:|?*\"")
# move the file, but avoid filename collisions
serial = 1
dest = base + ext
while os.path.exists(dest):
serial += 1
dest = base + " (%d)"%serial + ext
log("%s => %s " % (src, dest), True)
if move_file(src, dest):
continue # move failed
# create a placeholder cache entry
cache.append({
'path': src,
'original path': unicode(dest, sys.getfilesystemencoding(), 'replace')
})
except IOError:
fatal("can't read iTunes database file")
except iTunesDB.InvalidFormat:
raise
fatal("invalid iTunes database format")
# clear the cache
save_cache(("unfrozen", cache))
################################################################################
## FREEZE utilities ##
################################################################################
g_freeze_error_count = 0
def check_file(base, fn):
if fn.startswith('.'):
return None # skip dot-files and -directories
key, ext = [component.lower() for component in os.path.splitext(fn)]
fullname = base + fn
try:
s = os.stat(fullname)
except OSError:
log("ERROR: directory entry `%s' is inaccessible\n" % fn)
return None
isfile = int(not(stat.S_ISDIR(s[stat.ST_MODE])))
if isfile and not(stat.S_ISREG(s[stat.ST_MODE])):
return None # no directory and no normal file -> skip this crap
if not(isfile) and (fullname=="iPod_Control" or fullname=="iPod_Control/Music"):
isfile = -1 # trick the sort algorithm to move iPC/Music to front
return (isfile, fnrep(fn), fullname, s, ext, key)
def make_cache_index(cache):
index = {}
for i in xrange(len(cache)):
for path in [cache[i][f] for f in ('path', 'original path') if f in cache[i]]:
key = printable(path).lower()
if key in index:
log("ERROR: `%s' is cached multiple times\n" % printable(path))
else:
index[key] = i
return index
def find_in_cache(cache, index, path, s):
i = index.get(printable(path).lower(), None)
if i is None:
return (False, None) # not found
info = cache[i]
# check size and modification time
if info.get('size', None) != s[stat.ST_SIZE]:
return (False, info) # mismatch
if not iTunesDB.compare_mtime(info.get('mtime', 0), s[stat.ST_MTIME]):
return (False, info) # mismatch
# all checks passed => correct file
return (True, info)
def move_music(src, dest, info):
global g_freeze_error_count
format = info.get('format', "mp3-cbr")
if format == "ogg":
src = printable(src)
dest = os.path.splitext(printable(dest))[0] + ".mp3"
tmp = os.tempnam(None, "repear") + ".wav"
# generate new source filename (replace .ogg by .mp3)
newsrc = info.get('original path', src)
if type(newsrc) != types.UnicodeType:
newsrc = unicode(newsrc, sys.getfilesystemencoding(), 'replace')
newsrc = u'.'.join(newsrc.split(u'.')[:-1]) + u'.mp3'
# decode the Ogg file
res = execute("oggdec", ["-Q", "-o", tmp, src])
if res != 0:
g_freeze_error_count += 1
log("[FAILED]\nERROR: cannot execute OggDec ... result '%s'\n" % res)
delete(tmp, may_fail=True)
return None
else:
log("[decoded] ", True)
# build LAME option list
lameopts = Options['lameopts'].split(' ')
for key, optn in (('title','tt'), ('artist','ta'), ('album','tl'), ('year','ty'), ('comment','tc'), ('track number','tn')):
if key in info:
lameopts.extend(["--"+optn, printable(info[key])])
if 'genre' in info:
ref_genre = printable(info['genre']).lower().replace(" ","")
for number, genre in mp3info.ID3v1Genres.iteritems():
if genre.lower().replace(" ","") == ref_genre:
lameopts.extend(["--tg", str(number)])
break
# encode to MP3
res = execute("lame", lameopts + [tmp, dest])
delete(tmp)
if res != 0:
g_freeze_error_count += 1
log("[FAILED]\nERROR: cannot execute LAME ... result code %d\n" % res)
return None
else:
log("[encoded] ", True)
# check the resulting file
info = mp3info.GetAudioFileInfo(dest)
if not info:
g_freeze_error_count += 1
log("[FAILED]\nERROR: generated MP3 file is invalid\n")
delete(dest)
return None
delete(src)
info['original path'] = newsrc
info['changed'] = 2
log("[OK]\n", True)
return info
else: # no Ogg file -> move directly
if move_file(src, dest):
g_freeze_error_count += 1
return None # failed
else:
return info
def freeze_dir(cache, index, allocator, playlists=[], base="", artwork=None):
global g_freeze_error_count
try:
flist = filter(None, [check_file(base, fn) for fn in os.listdir(base or ".")])
except KeyboardInterrupt:
raise
except:
g_freeze_error_count += 1
log(base + "/\n" + " runtime error, traceback follows ".center(79, '-') + "\n")
traceback.print_exc(file=Logger)
log(79*'-' + "\n")
return []
# generate directory list
directories = filter(lambda x: x[0] < 1, flist)
directories.sort()
# add playlist files
playlists.extend([x[2] for x in flist if (x[0] > 0) and (x[4] == ".m3u")])
# generate music file list
music = filter(lambda x: (x[0] > 0) and (x[4] in SUPPORTED_FILE_FORMATS), flist)
music.sort()
# if there are no subdirs and no music files here, prune this directory
if not(directories) and not(music):
return []
# generate name -> artwork file associations
image_assoc = dict([(x[5], x[2]) for x in flist if (x[0] > 0) and (x[4] in (".jpg", ".png"))])
# find artwork files that are not associated to a file or directory
unassoc_images = image_assoc.copy()
for d0,d1,d2,d3,d4,key in directories:
if key in unassoc_images:
del unassoc_images[key]
for d0,d1,d2,d3,d4,key in music:
if key in unassoc_images:
del unassoc_images[key]
unassoc_images = unassoc_images.values()
unassoc_images.sort()
# use one of the unassociated artwork files as this directory's artwork,
# unless the inherited artwork file name is already a perfect match (i.e.
# the directory name and the artwork name are identical)
if unassoc_images:
if not(artwork) or not(artwork.lower().startswith(base[:-1].lower())):
artwork = find_good_artwork(unassoc_images, base)
# now that the artwork problem is solved, we start processing:
# recurse into subdirectories first
res = []
for isfile, dummy, fullname, s, ext, key in directories:
res.extend(freeze_dir(cache, index, allocator, playlists, fullname + '/', artwork))
# now process the local files
locals = []
unique_artist = None
unique_album = None
for isfile, dummy, fullname, s, ext, key in music:
try:
# we don't need to move this file if it's already in the Music directory
already_there = fullname.startswith(MUSIC_DIR)
# is this track cached?
log(fullname + ' ', True)
valid, info = find_in_cache(cache, index, fullname, s)
if valid:
info['changed'] = 0
log("[cached] ", True)
else:
if info:
# cache entry present, but invalid => save iPod_Control location
path = info['path']
changed = 1
else:
path = fullname
changed = 2
info = mp3info.GetAudioFileInfo(fullname)
iTunesDB.FillMissingTitleAndArtist(info)
info['changed'] = changed
if not already_there:
if type(info['path']) == types.UnicodeType:
info['original path'] = info['path']
else:
info['original path'] = unicode(info['path'], sys.getfilesystemencoding(), 'replace')
info['path'] = path
# move the track to where it belongs
if not already_there:
path = info.get('path', None)
if not(path) or os.path.exists(path) or not(os.path.isdir(os.path.split(path)[0])):
# if anything is wrong with the path, generate a new one
path = allocator.allocate() + ext
else:
allocator.add(path)
info['path'] = path
info = move_music(fullname, path, info)
if not info: continue # something failed
else:
allocator.add(fullname)
log("[OK]\n", True)
# associate artwork to the track
info['artwork'] = image_assoc.get(key, artwork)
# check for unique artist and album
check = info.get('artist', None)
if not locals:
unique_artist = check
elif check != unique_artist:
unique_artist = False
check = info.get('album', None)
if not locals:
unique_album = check
elif check != unique_album:
unique_album = False
# finally, append the track to the track list
locals.append(info)
except KeyboardInterrupt:
log("\nInterrupted by user.\nContinue with next file or abort? [c/A] ")
try:
answer = raw_input()
except (IOError, EOFError, KeyboardInterrupt):
answer = ""
if not answer.lower().startswith("c"):
raise
except:
g_freeze_error_count += 1
log("\n" + " runtime error, traceback follows ".center(79, '-') + "\n")
traceback.print_exc(file=Logger)
log(79*'-' + "\n")
# if all files in this directory share the same album title, but differ
# in the artist name, we assume it's a compilation
if unique_album and not(unique_artist):
for info in locals:
info['compilation'] = 1
# combine the lists and return them
res.extend(locals)
return res
################################################################################
## playlist sorting ##
################################################################################
def cmp_lst(a, b, order, empty_pos):
a = max(a.get('last played time', 0), a.get('last skipped time', 0))
b = max(b.get('last played time', 0), b.get('last skipped time', 0))
if not a:
if not b: return 0
return empty_pos
else:
if not b: return -empty_pos
return order * cmp(a, b)
def cmp_path(a, b, order, empty_pos):
return order * trackcmp(a, b)