2 # Copyright 2009 James Bunton <jamesbunton@fastmail.fm>
3 # Licensed for distribution under the GPL version 2, check COPYING for details
11 from Foundation
import *
14 def read_plist(filename
):
16 data
= buffer(open(filename
).read())
19 plist
, fmt
, err
= NSPropertyListSerialization
.propertyListFromData_mutabilityOption_format_errorDescription_(data
, NSPropertyListMutableContainers
, None, None)
21 errStr
= err
.encode("utf-8")
22 err
.release() # Doesn't follow Cocoa conventions for some reason
23 raise TypeError(errStr
)
26 class Playlist(NSObject
):
30 def set(self
, name
, pid
, ptype
, tracks
, parent
):
37 if parent
is not None:
38 parent
.children
.append(self
)
40 class ITunesLibrary(NSObject
):
41 def load_(self
, filename
):
43 filename
= "~/Music/iTunes/iTunes Music Library.xml"
44 filename
= os
.path
.expanduser(filename
)
45 yield "Reading library..."
46 plist
= read_plist(os
.path
.expanduser(filename
))
47 self
.folder
= self
.loc2name(plist
["Music Folder"])
48 pl_tracks
= plist
["Tracks"]
50 for pl_playlist
in plist
["Playlists"]:
51 playlist
= self
.make_playlist(pl_playlist
, pl_tracks
)
54 yield "Read playlist: " + playlist
.name
55 self
.playlists
[playlist
.pid
] = playlist
57 def loc2name(self
, location
):
58 return urllib
.splithost(urllib
.splittype(urllib
.unquote(location
))[1])[1]
60 def make_playlist(self
, pl_playlist
, pl_tracks
):
61 if int(pl_playlist
.get("Master", 0)):
63 kind
= int(pl_playlist
.get("Distinguished Kind", -1))
68 name
= pl_playlist
["Name"]
69 pid
= pl_playlist
["Playlist Persistent ID"]
80 }.get(kind
, "playlist")
81 elif pl_playlist
.has_key("Smart Info"):
82 ptype
= "smart-playlist"
83 elif int(pl_playlist
.get("Folder", 0)):
90 parent_pid
= pl_playlist
["Parent Persistent ID"]
91 parent
= self
.playlists
.get(parent_pid
)
95 for item
in pl_playlist
.get("Playlist Items", []):
96 trackID
= item
["Track ID"]
97 filename
= str(pl_tracks
[str(trackID
)]["Location"])
98 filename
= self
.loc2name(filename
)
99 filename
= filename
.decode("utf-8")
100 if not filename
.startswith(self
.folder
):
101 logging
.warn("Skipping: " + filename
)
103 filename
= strip_prefix(filename
, self
.folder
)
104 tracks
.append(filename
)
105 playlist
= Playlist
.alloc().init()
106 playlist
.set(name
, pid
, ptype
, tracks
, parent
)
109 def has_playlist_name(self
, name
):
110 for p
in self
.get_playlists():
115 def get_playlist_name(self
, name
):
116 for playlist
in self
.get_playlists():
117 if playlist
.name
== name
:
120 def get_playlist_pid(self
, pid
):
121 for playlist
in self
.get_playlists():
122 if playlist
.pid
== pid
:
125 def get_playlists(self
):
126 return self
.playlists
.values()
130 valid_chars
= frozenset("\\/-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
131 def encode_filename(filename
):
133 return encoded_names
[filename
]
136 orig_filename
= filename
137 filename
= filename
.encode("ascii", "ignore")
138 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
139 if filename
in encoded_names
:
140 a
, b
= os
.path
.splitext(filename
)
143 encoded_names
[orig_filename
] = filename
146 def strip_prefix(s
, prefix
):
147 assert s
.startswith(prefix
)
149 if s
.startswith("/"):
154 if os
.path
.isdir(path
):
158 path
= os
.path
.split(path
)[0]
160 for path
in reversed(paths
):
166 def export_m3u(dry_run
, dest
, path_prefix
, playlist_name
, files
):
171 playlist_file
= os
.path
.join(dest
, "-Playlists-", playlist_name
) + ".m3u"
172 mkdirhier(os
.path
.dirname(playlist_file
))
173 logging
.info("Writing: " + playlist_file
)
174 f
= open(playlist_file
, "w")
175 for filename
in files
:
176 if path_prefix
.find("\\") > 0:
177 filename
= filename
.replace("/", "\\")
178 filename
= encode_filename(filename
)
179 f
.write("%s%s\n" % (path_prefix
, filename
))
182 def sync(dry_run
, source
, dest
, files_to_copy
):
185 logging
.info("Calculating files to sync and deleting old files")
186 source
= source
.encode("utf-8")
187 dest
= dest
.encode("utf-8")
189 class SyncFile(object): pass
190 for f
in files_to_copy
:
192 sf
.orig_filename
= f
.encode("utf-8")
193 sf
.encoded_filename
= encode_filename(f
)
194 filemap
[sf
.encoded_filename
.lower()] = sf
195 files_to_copy
= set(filemap
)
197 for dirpath
, dirnames
, filenames
in os
.walk(dest
):
198 full_dirpath
= dirpath
199 dirpath
= strip_prefix(dirpath
, dest
)
201 for filename
in filenames
:
202 filename
= join(dirpath
, filename
)
204 # Whenever 'file' is deleted OSX will helpfully remove '._file'
205 if not os
.path
.exists(join(dest
, filename
)):
208 if filename
.lower() in files_to_copy
:
209 source_filename
= filemap
[filename
.lower()].orig_filename
210 sourcestat
= os
.stat(join(source
, source_filename
))
211 deststat
= os
.stat(join(dest
, filename
))
212 same_time
= abs(sourcestat
.st_mtime
- deststat
.st_mtime
) < 5
213 same_size
= sourcestat
.st_size
== deststat
.st_size
214 if same_time
and same_size
:
215 files_to_copy
.remove(filename
.lower())
216 yield "Keep: " + filename
218 yield "Update: " + filename
220 elif not filename
.startswith("-Playlists-"):
221 yield "Delete: " + filename
223 os
.unlink(join(dest
, filename
))
225 if len(os
.listdir(full_dirpath
)) == 0:
226 yield "Delete: " + dirpath
228 os
.rmdir(full_dirpath
)
231 logging
.info("Copying new files")
232 files_to_copy
= list(files_to_copy
)
234 for filename
in files_to_copy
:
235 yield "Copy: " + filemap
[filename
].orig_filename
237 source_file
= join(source
, filemap
[filename
].orig_filename
)
238 dest_file
= join(dest
, filemap
[filename
].encoded_filename
)
239 mkdirhier(os
.path
.dirname(dest_file
))
240 shutil
.copy2(source_file
, dest_file
)