/usr/share/pyshared/freevo/util/audioscrobbler.py is in python-freevo 1.9.2b2-4.2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | # -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# Audioscrobbler Realtime Submission Protocol v1.2 interface
# http://www.audioscrobbler.net/development/protocol/
# -----------------------------------------------------------------------------
# $Id: audioscrobbler.py 11408 2009-04-11 14:58:01Z duncan $
#
# -----------------------------------------------------------------------------
# Copyright (C) 2008 Krister Lagerstrom, et al.
#
# First Edition: Duncan Webb <duncan@freevo.org>
# Maintainer: Duncan Webb <duncan@freevo.org>
#
# Please see the file AUTHORS for a complete list of authors.
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version
# 2.1 as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# -----------------------------------------------------------------------------
__all__ = ['Audioscrobbler', 'AudioscrobblerException', 'DEBUG' ]
import time
import hashlib
import urllib
from threading import Thread, RLock
DEBUG = False
DEBUG = True
class AudioscrobblerException(Exception):
""" AudioscrobblerException class """
def __init__(self, why, url=None):
self.why = why
self.url = url
def __str__(self):
if self.url:
return repr(self.url+': '+self.why)
else:
return repr(self.why)
class AudioscrobblerWorker(Thread):
"""
Audioscrobbler Realtime Submission Protocol worker class
"""
def __init__(self, user, password, cachefilename):
"""
Initialise an instance of AudioscrobblerWorker
@ivar username: Is the name of the user.
@ivar password: Is the password for the user.
@ivar cachefilename: Is the cache file name of the Audioscrobbler handshake.
@ivar handshake: Indicates that a handshake is requested. Hits to
post.audioscrobbler.com without this variable set will return a
human-readable informational message, default true
@ivar clientid: Is an identifier for the client, default tst
@ivar clientver: Is the version of the client being used, default 1.0
@ivar timestamp: Is the current UNIX Timestamp, in seconds.
@ivar auth: md5(md5(password) + timestamp)
"""
Thread.__init__(self)
self.user = user
self.password = password
self.cachefilename = cachefilename
self.clientid = 'fvo'
self.clientver = '1.1'
self.timestamp = None
self.auth = None
self.cachedlines = []
try:
self.cachefd = open(self.cachefilename, 'r')
Audioscrobbler.sessionid = self.cachefd.readline().strip('\n')
Audioscrobbler.nowplayingurl = self.cachefd.readline().strip('\n')
Audioscrobbler.submissionurl = self.cachefd.readline().strip('\n')
for line in self.cachefd.readlines():
self.cachedlines += line.strip()
except IOError, why:
self._login()
def run(self):
"""
Execute the Audioscrobbler action
"""
try:
if self.action == 'nowplaying':
self.nowplaying(self.artist, self.track, self.album, self.secs, self.tracknumber, self.mbtrackid)
elif self.action == 'submit':
self.submit(self.artist, self.track, self.starttime, self.source, self.rating, self.secs,
self.album, self.tracknumber, self.mbtrackid)
else:
print 'unknown action!'
except AudioscrobblerException, why:
print 'AudioscrobblerException: %s' % (why,)
def _urlopen(self, url, data=None, lines=True):
"""
Wrapper to see what is sent and received
@param url: Is the URL to read.
@param data: Is the POST data.
@param lines: return a list of lines, otherwise data block.
@returns: reply from request
@raise AudioscrobblerException: when a problem has been detected.
"""
if DEBUG:
print 'url=%r, data=%r' % (url, data)
if lines:
reply = []
try:
f = urllib.urlopen(url, data)
if f is None:
raise AudioscrobblerException('Cannot open url', url)
lines = f.readlines()
f.close()
if lines is None:
return []
for line in lines:
reply.append(line.strip('\n'))
except Exception, why:
if DEBUG:
print '%s: %s' % (url, why)
raise
if DEBUG:
print 'reply=%r' % (reply,)
return reply
else:
reply = ''
try:
reply = urllib.urlopen(url, data).read()
except Exception, why:
if DEBUG:
print why
raise
if DEBUG:
print 'reply=%r' % (reply,)
return reply
def _login(self):
"""
Login to audioscrobbler.com, this is called when needed.
@raise AudioscrobblerException: when a problem has been detected.
"""
now = time.time()
if DEBUG:
print 'login: gm=%s lt=%r' % (
time.strftime('%d.%m.%Y %H:%M:%S', time.gmtime(now)),
time.strftime('%d.%m.%Y %H:%M:%S', time.localtime(now)))
#self.timestamp = time.strftime('%s', time.gmtime(now))
self.timestamp = time.strftime('%s')
self.auth = hashlib.md5(hashlib.md5(self.password).hexdigest()+self.timestamp).hexdigest()
url = 'http://post.audioscrobbler.com/?hs=true&p=1.2&c=%(clientid)s&v=%(clientver)s' % self.__dict__ + \
'&u=%(user)s&t=%(timestamp)s&a=%(auth)s' % self.__dict__
reply = self._urlopen(url)
if reply[0] != 'OK':
raise AudioscrobblerException(reply[0], url)
Audioscrobbler.sessionid = reply[1]
Audioscrobbler.nowplayingurl = reply[2]
Audioscrobbler.submissionurl = reply[3]
# Save the Audioscrobbler session information
fd = open(self.cachefilename, 'w')
print >>fd, Audioscrobbler.sessionid
print >>fd, Audioscrobbler.nowplayingurl
print >>fd, Audioscrobbler.submissionurl
fd.close()
def nowplaying(self, artist, track, album, secs, tracknumber, mbtrackid):
"""
Send what is now playing to audioscrobbler.com
"""
if Audioscrobbler.sessionid is None:
self._login()
data = {}
data['s'] = Audioscrobbler.sessionid
data['a'] = artist
data['t'] = track
data['b'] = album or ''
data['l'] = secs or ''
data['n'] = tracknumber or ''
data['m'] = mbtrackid or ''
url = Audioscrobbler.nowplayingurl
reply = self._urlopen(url, urllib.urlencode(data))
if reply[0] == 'BADSESSION':
self._login()
data['s'] = Audioscrobbler.sessionid
reply = self._urlopen(url, urllib.urlencode(data))
if reply[0] != 'OK':
raise AudioscrobblerException(reply[0], url)
def _prepare(self, num, artist, track, starttime, source, rating=None, secs=None,
album=None, tracknumber=None, mbtrackid=None):
"""
Prepares the track information to Audioscrobbler Realtime.
@raise AudioscrobblerException: when a problem has been detected.
@param num: Item number to submit.
@param artist: The artist name, required.
@param track: The track title, required.
@param starttime: The time the track started playing.
@param source: The source of the track, required.
@param rating: A single character denoting the rating of the track.
@param secs: The length of the track in seconds, required.
@param album: The album title, or None if not known.
@param tracknumber: The position of the track on the album, or None.
@param mbtrackid: The MusicBrainz Track ID, or None if not known.
@returns: dict of items for submission
"""
if DEBUG:
print '_prepare: num=%r, artist=%r, track=%r, starttime=%r, source=%r, rating=%r, secs=%r, album=%r, tracknumber=%r, mbtrackid=%r' % (num, artist, track, starttime, source, rating, secs, album, tracknumber, mbtrackid)
if source == 'P' and secs < 30:
raise AudioscrobblerException('FAILED track too short')
played = int(time.time() - starttime)
if played < 240 and played < int(secs) / 2:
raise AudioscrobblerException('FAILED too early to submit')
data = {}
data['a[%d]' % num] = artist
data['t[%d]' % num] = track
#data['i[%d]' % num] = time.strftime('%s', time.gmtime(starttime))
data['i[%d]' % num] = time.strftime('%s')
data['o[%d]' % num] = source
data['r[%d]' % num] = rating or 'L'
data['l[%d]' % num] = int(secs) or ''
data['b[%d]' % num] = album or ''
data['n[%d]' % num] = tracknumber or ''
data['m[%d]' % num] = mbtrackid or ''
if DEBUG:
print '%s: gm=%s lt=%r' % (track,
time.strftime('%d.%m.%Y %H:%M:%S', time.gmtime(float(starttime))),
time.strftime('%d.%m.%Y %H:%M:%S', time.localtime(float(starttime))))
return data
def submit(self, artist, track, starttime, source, rating, secs, album, tracknumber, mbtrackid):
"""
Submit one or more tracks to Audioscrobbler Realtime.
"""
if DEBUG:
print 'submit: artist=%r, track=%r, starttime=%r, source=%r, rating=%r, secs=%r, album=%r, tracknumber=%r, mbtrackid=%r' % (artist, track, starttime, source, rating, secs, album, tracknumber, mbtrackid)
if Audioscrobbler.sessionid is None:
self._login()
data = {}
data['s'] = Audioscrobbler.sessionid
if isinstance(artist, (list, tuple)):
for i in range(len(artist)):
s_artist = artist[i]
s_track = track[i]
s_starttime = starttime[i]
s_source = source[i]
s_rating = rating is not None and rating[i] or 'L'
s_secs = secs is not None and secs[i] or 0
s_album = album is not None and album[i] or ''
s_tracknumber = tracknumber is not None and tracknumber[i] or ''
s_mbtrackid = mbtrackid is not None and mbtrackid[i] or ''
data.update(self._prepare(i, s_artist, s_track, s_starttime, s_source, s_rating, s_secs,
s_album, s_tracknumber, s_mbtrackid))
else:
data.update(self._prepare(0, artist, track, starttime, source, rating, secs, album, tracknumber, mbtrackid))
url = Audioscrobbler.submissionurl
reply = self._urlopen(url, urllib.urlencode(data))
if reply[0] == 'BADSESSION':
self._login()
data['s'] = Audioscrobbler.sessionid
reply = self._urlopen(url, urllib.urlencode(data))
if reply[0] != 'OK':
raise AudioscrobblerException(reply[0], url)
class Audioscrobbler(object):
"""
Audioscrobbler Realtime Submission Protocol class
"""
sessionid = None
nowplayingurl = None
submissionurl = None
def __init__(self, username, password, cachefilename):
"""
Initialise an instance of Audioscrobbler
@ivar username: Is the name of the user.
@ivar password: Is the password for the user.
@ivar cachefilename: Is the cache file name of the Audioscrobbler handshake.
"""
if DEBUG:
print 'Audioscrobbler.__init__(username=%r, password=%r, cachefilename=%r' % \
(username, '*' * len(password), cachefilename)
self.username = username
self.password = password
self.cachefilename = cachefilename
def nowplaying(self, artist, track, album=None, secs=None, tracknumber=None, mbtrackid=None):
"""
Send what is now playing to audioscrobbler.com
@raise AudioscrobblerException: when a problem has been detected.
@param artist: The artist name, required.
@param track: The track name, required.
@param album: The album title, or None if not known.
@param secs: The length of the track in seconds, or None if not known.
@param tracknumber: The position of the track on the album, or None if not known.
@param mbtrackid: The MusicBrainz Track ID, or None if not known.
"""
if DEBUG:
print 'Audioscrobbler.nowplaying'
self.np_worker = AudioscrobblerWorker(self.username, self.password, self.cachefilename)
self.np_worker.action = 'nowplaying'
self.np_worker.artist = artist
self.np_worker.track = track
self.np_worker.album = album
self.np_worker.secs = secs
self.np_worker.tracknumber = tracknumber
self.np_worker.mbtrackid = mbtrackid
self.np_worker.start()
def submit(self, artist, track, starttime, source, rating, secs=None,
album=None, tracknumber=None, mbtrackid=None):
"""
Submit one or more tracks to Audioscrobbler Realtime.
The parameters may be either a single item or a list, when a list then
each list must have the same number of items.
The submission takes place as a HTTP/1.1 POST transaction with the
server, using the URL provided during the handshake phase of the
protocol. The submission body may contain the details for up to 50
tracks which are being submitted. Under normal circumstances only a
single track will be submitted, however, clients should cache
submissions in case of failure.
The request takes the form of a group of form encoded key-value pairs
which are submitted to the server as the body of the HTTP POST request,
using the URL provided in the handshake. All specified parameters must
be present; they should be left empty if not known.
@raise AudioscrobblerException: when a problem has been detected.
@param artist: The artist name, required.
@param track: The track title, required.
@param starttime: The time the track started playing, in UNIX timestamp
format (integer number of seconds since 00:00:00, January 1st 1970
UTC). This must be in the UTC time zone, required.
@param source: The source of the track, required, must be one of the
following codes:
- P Chosen by the user
- R Non-personalised broadcast (e.g. Shoutcast, BBC Radio 1)
- E Personalised recommendation except Last.fm (e.g. Pandora,
Launchcast)
- L Last.fm (any mode). In this case, the 5-digit Last.fm
recommendation key must be appended to this source ID to prove
the validity of the submission (for example, "o[0]=L1b48a").
- U Source unknown
Please note, for the time being, sources other than P and L are not
supported.
@param rating: A single character denoting the rating of the track.
Empty if not applicable.
- L Love (on any mode if the user has manually loved the track).
This implies a listen.
- B Ban (only if source=L). This implies a skip, and the client
should skip to the next track when a ban happens.
- S Skip (only if source=L)
Note: Currently, a web-service must also be called to set love/ban
status. We anticipate that this will be phased out soon, and the
submission service will handle the whole process.
@param secs: The length of the track in seconds, required when the
source is P, optional otherwise.
@param album: The album title, or None if not known.
@param tracknumber: The position of the track on the album, or None if
not known.
@param mbtrackid: The MusicBrainz Track ID, or None if not known.
"""
if DEBUG:
print 'Audioscrobbler.submit'
self.sm_worker = AudioscrobblerWorker(self.username, self.password, self.cachefilename)
self.sm_worker.action = 'submit'
self.sm_worker.artist = artist
self.sm_worker.track = track
self.sm_worker.starttime = starttime
self.sm_worker.source = source
self.sm_worker.rating = rating
self.sm_worker.secs = secs
self.sm_worker.album = album
self.sm_worker.tracknumber = tracknumber
self.sm_worker.mbtrackid = mbtrackid
self.sm_worker.start()
if __name__ == '__main__':
DEBUG = True
# import username and password
from astestdata import *
# now playing test data
np_artist='Nora Jones'
np_track='Seven Years'
np_album='Come Away With Me'
# single track submission
one_artist = 'Nora Jones'
one_track = 'Humble Me'
one_album = None
one_starttime = time.time() - 30*60
one_source = 'P'
one_rating = 'L'
one_secs = 276
one_tracknumber = 9
# mulitple track submission
artist = ('Nora Jones', 'Nora Jones')
track = ('Seven Years', 'In The Morning')
album = ('come away with me', 'feels like home')
starttime = (time.time() - 20*60, time.time() - 6*60)
source = ('P', 'P')
rating = ('L', 'L')
secs = (145.319183673, 247.379591837)
tracknumber = (None, 5)
fn = '/tmp/as.cache'
audioscrobbler = Audioscrobbler(user, password, fn)
audioscrobbler.nowplaying(np_artist, np_track, np_album)
try:
#audioscrobbler.submit(one_artist, one_track, one_starttime, one_source, one_rating, one_secs, one_album, one_tracknumber)
pass
except AudioscrobblerException, why:
print why
try:
#audioscrobbler.submit(artist, track, starttime, source, rating, secs, album, tracknumber)
pass
except AudioscrobblerException, why:
print why
artisttrackurl = "http://ws.audioscrobbler.com/1.0/artist/%s/toptracks.xml"
url = artisttrackurl % (urllib.quote(np_artist))
#print audioscrobbler._urlopen(url)
|