In [1]:
import os
import json
In [2]:
from ScriptingBridge import SBApplication
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
In [3]:
def encode(obj):
if obj is not None and not isinstance(obj, (int, basestring, float)):
obj = unicode(obj)
return obj
In [4]:
def mkdir_p(dirpath):
if not os.path.exists(dirpath):
os.makedirs(dirpath)
return dirpath
In [5]:
def clean_filename(filename):
return filename.replace('/', '-').replace(':', '-').replace('&', ' and ').replace(' ', ' ')
In [6]:
def track_json(track):
keys = [
'album',
'albumArtist',
'artist',
'bitRate',
'dateAdded',
'duration',
'modificationDate',
'name',
'time',
'size',
'year',
'playedCount',
'playedDate',
'skippedCount',
'skippedDate',
'rating',
]
return {key: value for key, value in track.properties().items() if key in keys}
In [7]:
def serialize_playlist(playlist, dirpath):
name = playlist.name()
tracks = [track_json(track) for track in playlist.tracks()]
mkdir_p(dirpath)
filepath = os.path.join(dirpath, clean_filename(name + '.json'))
with open(filepath, 'w') as fp:
json.dump(tracks, fp, indent=2, default=encode)
In [9]:
def serialize_source(source, root='/Users/chbrown/Desktop'):
print 'Source', source.name()
dirname = clean_filename(source.name())
dirpath = os.path.join(root, dirname)
for playlist in source.playlists():
print 'Playlist', playlist.name()
serialize_playlist(playlist, dirpath)
In [11]:
sources = iTunes.sources()
for source in sources:
print source.name()
In [12]:
source = sources[0]
In [13]:
serialize_source(source)
In [69]:
# track_json(track)
# inspector.dump(track)