/
playlistsync.py
executable file
·213 lines (177 loc) · 5.3 KB
/
playlistsync.py
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
#!/usr/bin/env python
import sys, os, re, shutil
from songfile import SongFile
from progress import ProgressBar
from optparse import OptionParser
from mutagen.mp3 import HeaderNotFoundError
import json
import unicodedata
cacheDir = os.path.join(os.getcwdu(), 'cache')
if not os.path.exists(cacheDir):
os.mkdir(cacheDir)
def sanitize(s):
s = unicodedata.normalize('NFKD', s).encode('ascii','ignore')
s = re.sub(r'[\/:\?]', '_', s)
return s
def getMetaData(songPath):
cachePath = os.path.join(cacheDir, str(abs(hash(songPath))))
song = SongFile()
try:
f = open(cachePath, 'r')
jsonData = json.load(f)
f.close()
if jsonData['path'] == songPath:
song.fromJson(jsonData)
else:
# Hash collision !
# TODO: Do something better about this
raise LookupError()
except Exception as e:
try:
song.load(songPath)
f = open(cachePath,'w')
f.write(song.toJson())
f.close()
except (IOError):
print "IOError", IOError
return song
def main(plistpath, dest, options=None, flat=False, quiet=False, verbose=False):
if options:
flat = options.flat
quiet = options.quiet
verbose = options.verbose
plist = open(plistpath)
srcset = set()
destset = set()
print "Parsing playlist."
playlistpaths = []
for line in plist:
if line[0] == '#':
continue
if line[-1] == '\n':
path = line[:-1] # strip the new line
else:
path = line
playlistpaths.append(path)
if len(playlistpaths) == 0:
print("Playlist is empty!")
sys.exit()
print "Loading metadata from playlist files."
bar = ProgressBar(len(playlistpaths),"numbers")
bar.draw()
i = 0
totalbytes=0
for path in playlistpaths:
song = getMetaData(path)
totalbytes += os.path.getsize(path)
srcset.add(song)
i += 1
bar.update(i)
print "{0} files, {1} MB".format(len(playlistpaths), totalbytes/(1024.0*1024.0))
print "Loading existing files"
existingFilePaths = []
for dirpath, dirnames, filenames in os.walk(dest):
for path in filenames:
if path[-3:] == 'mp3':
fullpath = os.path.join(dirpath, path)
existingFilePaths.append(fullpath)
if len(existingFilePaths) > 0:
print "Loading metadata from existing files."
bar = ProgressBar(len(existingFilePaths),"numbers")
bar.draw()
i = 0
for path in existingFilePaths:
try:
song = getMetaData(path)
destset.add(song)
except (HeaderNotFoundError):
# This is when the mp3 file in place is malformed, like when it is
# only a partial file
os.remove(path)
i += 1
bar.update(i)
else:
print "No existing files"
toAdd = srcset - destset
toDel = destset - srcset
# we can't just take the intersection, because we need the version from dest
toCheck = set()
for song in destset:
if song in srcset:
toCheck.add(song)
if len(toDel) > 0:
print "Deleting songs"
for song in toDel:
os.remove(song.mp3path)
if len(toAdd) > 0:
print "Copying songs"
bar = ProgressBar(len(toAdd),"numbers")
bar.draw()
i = 0
for song in toAdd:
data = song.data(root=dest)
data['artist'] = sanitize(data['artist'])
data['album'] = sanitize(data['album'])
data['title'] = sanitize(data['title'])
newPath = ""
if flat == False:
artistDir = u"{0[root]}/{0[artist]}".format(data)
albumDir = artistDir + u"/{0[album]}".format(data)
newPath = albumDir + u"/{0[track]:0>2} {0[title]}.mp3".format(data)
if not os.path.exists(artistDir):
os.mkdir(artistDir)
if not os.path.exists(albumDir):
os.mkdir(albumDir)
else:
newPath = u"{0[root]}/{0[artist]} - {0[album]} - {0[track]:0>2} {0[title]}.mp3".format(data)
try:
shutil.copyfile(song.mp3path, newPath)
except (IOError):
print "Error copying {0}".format(newPath)
i += 1
bar.update(i)
else:
print "All songs already there!"
first = False
if len(toCheck) > 0:
for song in toCheck:
data = song.data(root=dest)
data['artist'] = sanitize(data['artist'])
data['album'] = sanitize(data['album'])
data['title'] = sanitize(data['title'])
newFile = ""
if flat == False:
artistDir = u"{0[root]}/{0[artist]}".format(data)
albumDir = artistDir + u"/{0[album]}".format(data)
newFile = albumDir + u"/{0[track]:0>2} {0[title]}.mp3".format(data)
if not os.path.exists(artistDir):
os.mkdir(artistDir)
if not os.path.exists(albumDir):
os.mkdir(albumDir)
else:
newFile = u"{0[root]}/{0[artist]} - {0[album]} - {0[track]:0>2} {0[title]}.mp3".format(data)
if not song.mp3path == newFile:
if first:
first = False
print "Organizing old songs"
shutil.move(song.mp3path, newFile)
print
print "Done."
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage " + sys.argv[0] + " playlist destination")
sys.exit()
parser = OptionParser()
parser.set_defaults(flat=False)
parser.add_option("-f", "--flat", action="store_true", dest="flat",
help="Copies files to a single directory, instead of structured into folders.")
parser.add_option("-s", "--structured", action="store_false", dest="flat",
help="Copies files to a structured hierarchy, with folders for artists and albums.")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
help="Silences all output.")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
help="Gives extra output.")
options, args = parser.parse_args()
plistpath = args[0]
dest = args[1]
main(args[0],args[1],options)