first working version, but not used now
[enigma2-plugins.git] / lastfm / src / scrobbler.py
1 import socket,urllib,urllib2,re,time,datetime,md5
2 from twisted.internet import reactor
3
4 from enigma import iServiceInformation
5 from Components.config import config
6
7
8
9 class LastFMScrobbler(object):
10     client="tst" # this must be changed to a own ID
11     version="1.0"
12     url="http://post.audioscrobbler.com/"
13
14     def __init__(self,user,password):
15         self.user = user
16         self.password = password
17
18     def handshake(self):
19         url = self.url+"?"+urllib.urlencode({
20             "hs":"true",
21             "p":"1.1",
22             "c":self.client,
23             "v":self.version,
24             "u":self.user
25             })
26         result = urllib2.urlopen(url).readlines()
27         if result[0].startswith("BADUSER"):
28             return self.baduser(result[1:])
29         if result[0].startswith("UPTODATE"):
30             return self.uptodate(result[1:])
31         if result[0].startswith("FAILED"):
32             return self.failed(result)
33
34     def uptodate(self,lines):
35         self.md5 = re.sub("\n$","",lines[0])
36         self.submiturl = re.sub("\n$","",lines[1])
37         self.interval(lines[2])
38     def baduser(self,lines):
39         print "Bad user"
40     def failed(self,lines):
41         print "FAILD",lines[0]
42         self.interval(lines[1])
43     def interval(self,line):
44         match = re.match("INTERVAL (\d+)",line)
45         if match is not None:
46             print "[audioscrobbler] Sleeping for",match.group(1),"secs"
47             #time.sleep(int(match.group(1)))
48             
49     def submit(self,tracks):
50         print "[audioscrobbler] Submitting"
51         md5response = md5.md5(md5.md5(self.password).hexdigest()+self.md5).hexdigest()
52         post = "u="+self.user+"&s="+md5response
53         count = 0
54         for track in tracks:
55             post += "&"
56             post += track.urlencoded(count)
57             count += 1
58         post = unicode(post)
59         result = urllib2.urlopen(self.submiturl,post)
60         results = result.readlines()
61         print results
62         if results[0].startswith("OK"):
63             print "OK"
64             self.interval(results[1])
65         if results[0].startswith("FAILED"):
66             self.failed([results[0],"INTERVAL 0"])
67
68 ############
69
70 class Track(object):
71     def __init__(self,artist,name,album,length=232,mbid=None,tracktime=None):
72         self.params = {}
73         self.artist = artist
74         self.name = name
75         self.album = album
76         self.length = length
77         self.mbid = mbid
78         self.tracktime = tracktime
79         self.date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
80         
81     def __repr__(self):
82         return "'"+self.name+"' by '"+self.artist+"' from '"+self.album+"'"
83
84     def urlencoded(self,num):
85         encode = ""
86         encode += "a["+str(num)+"]="+urllib.quote_plus(self.artist)
87         encode += "&t["+str(num)+"]="+urllib.quote_plus(self.name)
88         if self.length is not None:
89             encode += "&l["+str(num)+"]="+urllib.quote_plus(str(self.length))
90         else:
91             encode += "&l["+str(num)+"]="            
92         encode += "&i["+str(num)+"]="+urllib.quote_plus(self.date)
93         if self.mbid is not None:
94             encode += "&m["+str(num)+"]="+urllib.quote_plus(self.mbid)
95         else:
96             encode += "&m["+str(num)+"]="
97         encode += "&b["+str(num)+"]="+urllib.quote_plus(self.album)
98         return encode
99 ##########
100 class EventListener:
101     time2wait4submit = 30
102     def __init__(self,session):
103         self.session = session
104         
105     def onEvent(self,event):
106         if event == 4:
107             track = self.getCurrentServiceType()
108             if track is not False:
109                 print "waiting",self.time2wait4submit,"until checking if the track is still playing"
110                 reactor.callLater(self.time2wait4submit, self.checkTrack, track)
111
112     def startListenToEvents(self):
113         self.session.nav.event.append(self.onEvent)
114
115     def stopListentoEvents(self):
116         self.session.nav.event.remove(self.onEvent)
117     
118     def getCurrentServiceType(self):
119         print "getCurrentServiceType"
120         currPlay = self.session.nav.getCurrentService()
121         sref=self.session.nav.getCurrentlyPlayingServiceReference()
122         if sref is None:
123             return False
124         elif sref.toString().startswith("4097:0:0:0:0:0:0:0:0:0:") is not True:
125             return False
126         elif sref.toString().endswith("lastfm.mp3") is True:
127             return False
128         elif currPlay is not None:
129             return self.getTrack( artist = currPlay.info().getInfoString(iServiceInformation.sArtist),
130                                   title = currPlay.info().getInfoString(iServiceInformation.sTitle),
131                                   album = currPlay.info().getInfoString(iServiceInformation.sAlbum),
132                                  )
133              
134              
135     def getTrack(self , artist = None, title = None, album = None):
136         print "updateMusicInformation",artist,title,album
137         if artist == "" or artist is None:
138             return False
139         elif title == "" or title is None:
140             return False
141         else:
142             return Track(artist,title,album)
143             
144     
145     def checkTrack(self,track):
146         print "checkTrack",track
147         trackcurrent = self.getCurrentServiceType()
148         print "currentTrack",trackcurrent
149         if str(track) == str(trackcurrent):
150             print "Tracks match!!!"
151             submitTrack(trackcurrent)
152             
153         
154 def submitTrack(track):
155     c = LastFMScrobbler(config.plugins.LastFM.username.value,config.plugins.LastFM.password.value)
156     print "HANDSHAKE",c.handshake() 
157     #tracks.append(Track(artist,name,album))
158     print "SUBMIT",c.submit([track])
159
160 #c = LastFMScrobbler("hanshase","ftgz67")
161 #hr= c.handshake() 
162 #print "HANDSHAKE",hr
163 #sr=c.submit([Track("ArtistArtist","namename","AlbumAlbum")])
164 #print "SUBMIT",sr