Initial commit of PostTunes.
[~jspiros/PostTunes.git] / PostTunesAppDelegate.py
1 #
2 #  PostTunesAppDelegate.py
3 #  PostTunes
4 #
5 #  Created by Joseph Spiros on 3/5/09.
6 #  Copyright iThink Software 2009. All rights reserved.
7 #
8
9 import objc
10 from urllib import urlencode
11 from urllib2 import urlopen, URLError
12 from base64 import b64encode
13 from Foundation import *
14 from AppKit import *
15 from ScriptingBridge import *
16
17 class PostTunesAppDelegate(NSObject):
18         preferencesWindow = objc.IBOutlet()
19         warnPreferences = objc.ivar(u"warnPreferences")
20         warnFailure = objc.ivar(u"warnFailure")
21         lastPersistentID = objc.ivar(u"lastPersistentID")
22         handlerURL = objc.ivar(u"handlerURL")
23         secretKey = objc.ivar(u"secretKey")
24         
25         def init(self):
26                 self = super(PostTunesAppDelegate, self).init()
27                 if not self:
28                         return None
29                 self.warnPreferences = True
30                 self.warnFailure = True
31                 self.lastPersistentID = None
32                 self.handlerURL = None
33                 self.secretKey = None
34                 self.observeNote()
35                 return self
36         
37         def observeNote(self):
38                 NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "gotNotification:", "com.apple.iTunes.playerInfo", None)
39         
40         def gotNotification_(self, notification):
41                 self.handlerURL = NSUserDefaults.standardUserDefaults().stringForKey_("handlerURL")
42                 self.secretKey = NSUserDefaults.standardUserDefaults().stringForKey_("secretKey")
43                 if notification:
44                         noteInfo = notification.userInfo()
45                         playerState = noteInfo["Player State"]
46                         if "PersistentID" in noteInfo:
47                                 persistentID = noteInfo["PersistentID"]
48                                 if (persistentID != self.lastPersistentID) and ("Name" in noteInfo):
49                                         if playerState == "Playing":
50                                                 if self.handlerURL:
51                                                         # started playing a new track
52                                                         # get the applescript track and make sure it's the same (compare name)
53                                                         iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
54                                                         iTunesTrack = iTunes.currentTrack()
55                                                         if iTunesTrack.name() == noteInfo["Name"]:
56                                                                 self.trackChanged_iTunesTrack_(noteInfo, iTunesTrack)
57                                                                 self.lastPersistentID = persistentID
58                                                 else:
59                                                         NSLog(u"Track Not Posted: You have not provided PostTunes with the Handler URL to use.")
60                                                         if self.warnPreferences:
61                                                                 alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_("Track Not Posted", "Open PostTunes Preferences", "Ignore", None, u"You have not provided PostTunes with the Handler URL to use.")
62                                                                 if alert.runModal() == NSAlertDefaultReturn:
63                                                                         self.preferencesWindow.makeKeyAndOrderFront_(self)
64                                                                 elif alert.runModal() == NSAlertAlternateReturn:
65                                                                         self.warnPreferences = False
66                                                                 
67                         else:
68                                 self.lastPersistentID = None
69                                 # stopped playing
70         
71         def trackChanged_iTunesTrack_(self, noteInfo, iTunesTrack):
72                 trackData = {"title": noteInfo["Name"]}
73                 if self.secretKey:
74                         trackData["key"] = self.secretKey
75                 if "Artist" in noteInfo:
76                         trackData["artist"] = noteInfo["Artist"]
77                 if "Album" in noteInfo:
78                         trackData["album"] = noteInfo["Album"]
79                 if "Store URL" in noteInfo:
80                         trackData["url"] = noteInfo["Store URL"]
81                 iTunesArtworks = iTunesTrack.artworks()
82                 if len(iTunesArtworks) >= 1:
83                         artwork = iTunesArtworks[0]
84                         artworkTIFF = artwork.data().TIFFRepresentation()
85                         artworkPNG = NSBitmapImageRep.imageRepWithData_(artworkTIFF).representationUsingType_properties_(NSPNGFileType, None)
86                         trackData["artpng"] = b64encode(artworkPNG.bytes())
87                 try:
88                         urlopen(self.handlerURL, urlencode(trackData))
89                 except URLError:
90                         NSLog(u"PostTunes encountered an error when attempting to submit a track to: %s" % self.handlerURL)
91                         if self.warnFailure:
92                                 alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_("Track Not Posted", "Open PostTunes Preferences", "Ignore", None, (u"PostTunes encountered an error when attempting to submit a track to:\n%s" % self.handlerURL))
93                                 if alert.runModal() == NSAlertDefaultReturn:
94                                         self.preferencesWindow.makeKeyAndOrderFront_(self)
95                                 elif alert.runModal() == NSAlertAlternateReturn:
96                                         self.warnFailure = False