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
, tracks
, parent
):
36 if parent
is not None:
37 parent
.children
.append(self
)
39 class ITunesLibrary(NSObject
):
40 def load_(self
, filename
):
42 filename
= "~/Music/iTunes/iTunes Music Library.xml"
43 filename
= os
.path
.expanduser(filename
)
44 yield "Reading library..."
45 plist
= read_plist(os
.path
.expanduser(filename
))
46 self
.folder
= self
.loc2name(plist
["Music Folder"])
47 pl_tracks
= plist
["Tracks"]
49 for pl_playlist
in plist
["Playlists"]:
50 playlist
= self
.make_playlist(pl_playlist
, pl_tracks
)
51 yield "Read playlist: " + playlist
.name
52 self
.playlists
[playlist
.pid
] = playlist
54 def loc2name(self
, location
):
55 return urllib
.splithost(urllib
.splittype(urllib
.unquote(location
))[1])[1]
57 def make_playlist(self
, pl_playlist
, pl_tracks
):
58 name
= pl_playlist
["Name"]
59 pid
= pl_playlist
["Playlist Persistent ID"]
62 parent_pid
= pl_playlist
["Parent Persistent ID"]
63 parent
= self
.playlists
.get(parent_pid
)
67 for item
in pl_playlist
.get("Playlist Items", []):
68 trackID
= item
["Track ID"]
69 filename
= str(pl_tracks
[str(trackID
)]["Location"])
70 filename
= self
.loc2name(filename
)
71 filename
= filename
.decode("utf-8")
72 if not filename
.startswith(self
.folder
):
73 logging
.warn("Skipping: " + filename
)
75 filename
= strip_prefix(filename
, self
.folder
)
76 tracks
.append(filename
)
77 playlist
= Playlist
.alloc().init()
78 playlist
.set(name
, pid
, tracks
, parent
)
81 def has_playlist_name(self
, name
):
82 for p
in self
.get_playlists():
87 def get_playlist_name(self
, name
):
88 for playlist
in self
.get_playlists():
89 if playlist
.name
== name
:
92 def get_playlist_pid(self
, pid
):
93 for playlist
in self
.get_playlists():
94 if playlist
.pid
== pid
:
97 def get_playlists(self
):
98 return self
.playlists
.values()
100 def outlineView_numberOfChildrenOfItem_(self
, view
, item
):
102 return len(self
.playlists
)
106 def outlineView_isItemExpandable_(self
, view
, item
):
109 def outlineView_child_ofItem_(self
, view
, index
, item
):
111 return self
.playlists
[index
]
115 def outlineView_objectValueForTableColumn_byItem_(self
, view
, column
, item
):
120 valid_chars
= frozenset("\\/-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
121 def encode_filename(filename
):
123 return encoded_names
[filename
]
126 orig_filename
= filename
127 filename
= filename
.encode("ascii", "ignore")
128 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
129 if filename
in encoded_names
:
130 a
, b
= os
.path
.splitext(filename
)
133 encoded_names
[orig_filename
] = filename
136 def strip_prefix(s
, prefix
):
137 assert s
.startswith(prefix
)
139 if s
.startswith("/"):
144 if os
.path
.isdir(path
):
148 path
= os
.path
.split(path
)[0]
150 for path
in reversed(paths
):
156 def export_m3u(dry_run
, dest
, path_prefix
, playlist_name
, files
):
161 playlist_file
= os
.path
.join(dest
, "-Playlists-", playlist_name
) + ".m3u"
162 mkdirhier(os
.path
.dirname(playlist_file
))
163 logging
.info("Writing: " + playlist_file
)
164 f
= open(playlist_file
, "w")
165 for filename
in files
:
166 if path_prefix
.find("\\") > 0:
167 filename
= filename
.replace("/", "\\")
168 filename
= encode_filename(filename
)
169 f
.write("%s%s\n" % (path_prefix
, filename
))
172 def sync(dry_run
, source
, dest
, files_to_copy
):
175 logging
.info("Calculating files to sync and deleting old files")
176 source
= source
.encode("utf-8")
177 dest
= dest
.encode("utf-8")
179 class SyncFile(object): pass
180 for f
in files_to_copy
:
182 sf
.orig_filename
= f
.encode("utf-8")
183 sf
.encoded_filename
= encode_filename(f
)
184 filemap
[sf
.encoded_filename
.lower()] = sf
185 files_to_copy
= set(filemap
)
187 for dirpath
, dirnames
, filenames
in os
.walk(dest
):
188 full_dirpath
= dirpath
189 dirpath
= strip_prefix(dirpath
, dest
)
191 for filename
in filenames
:
192 filename
= join(dirpath
, filename
)
194 # Whenever 'file' is deleted OSX will helpfully remove '._file'
195 if not os
.path
.exists(join(dest
, filename
)):
198 if filename
.lower() in files_to_copy
:
199 source_filename
= filemap
[filename
.lower()].orig_filename
200 sourcestat
= os
.stat(join(source
, source_filename
))
201 deststat
= os
.stat(join(dest
, filename
))
202 same_time
= abs(sourcestat
.st_mtime
- deststat
.st_mtime
) < 5
203 same_size
= sourcestat
.st_size
== deststat
.st_size
204 if same_time
and same_size
:
205 files_to_copy
.remove(filename
.lower())
206 yield "Keep: " + filename
208 yield "Update: " + filename
210 elif not filename
.startswith("-Playlists-"):
211 yield "Delete: " + filename
213 os
.unlink(join(dest
, filename
))
215 if len(os
.listdir(full_dirpath
)) == 0:
216 yield "Delete: " + dirpath
218 os
.rmdir(full_dirpath
)
221 logging
.info("Copying new files")
222 files_to_copy
= list(files_to_copy
)
224 for filename
in files_to_copy
:
225 yield "Copy: " + filemap
[filename
].orig_filename
227 mkdirhier(os
.path
.dirname(join(dest
, filename
)))
229 join(source
, filemap
[filename
].orig_filename
),
230 join(dest
, filemap
[filename
].encoded_filename
)