Skip to content

Instantly share code, notes, and snippets.

@thevar1able
Last active August 29, 2015 14:19
Show Gist options
  • Save thevar1able/60248d016bae5019b77c to your computer and use it in GitHub Desktop.
Save thevar1able/60248d016bae5019b77c to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from gi.repository import GObject
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import datetime
import time
import pylast
class TinyScrobbler():
def __init__(self):
self.api_key = "" #Fill
self.api_secret = "" #All
self.username = "" #These
self.hash_password = "" #Lines
not_connected = True
while(not_connected):
try:
self.lastfm = pylast.LastFMNetwork( api_key = self.api_key,
api_secret = self.api_secret,
username = self.username,
password_hash = self.hash_password )
not_connected = False
print "Connected"
except:
pass
DBusGMainLoop(set_as_default=True)
self.bus = dbus.SessionBus()
self.bus.add_signal_receiver(self.mainHandler,
dbus_interface="org.freedesktop.DBus.Properties",
signal_name="PropertiesChanged")
self.bus.add_signal_receiver(self.seekHandler,
dbus_interface="org.mpris.MediaPlayer2.Player",
signal_name="Seeked")
self.nowPlaying = { 'Artist': None,
'Track': None,
'Duration': 0,
'CurrentTime': 0,
'Scrobbled': False,
}
self.status = None
self.lastAction = None
def mainHandler(self, sender, message, dummy):
if(self.status == "Playing"):
diff = datetime.datetime.now() - self.lastAction
self.nowPlaying['CurrentTime'] += diff.total_seconds()
self.lastAction = datetime.datetime.now()
self.scrobble()
if(sender == "org.mpris.MediaPlayer2.Player"):
if 'Metadata' in message:
self.nowPlaying['Artist'] = str(message['Metadata']['xesam:artist'][0])
self.nowPlaying['Track'] = str(message['Metadata']['xesam:title'])
self.nowPlaying['Duration'] = int(message['Metadata']['mpris:length']) / 1000000
self.nowPlaying['CurrentTime'] = 0
self.nowPlaying['Scrobbled'] = False
print self.nowPlaying
elif 'PlaybackStatus' in message:
self.status = message['PlaybackStatus']
print self.status
def seekHandler(self, time):
if(self.status == "Playing"):
diff = datetime.datetime.now() - self.lastAction
self.nowPlaying['CurrentTime'] += diff.total_seconds()
self.lastAction = datetime.datetime.now()
self.scrobble()
def scrobble(self):
if(self.nowPlaying['Duration'] <= 30 or self.nowPlaying['Scrobbled']):
print "Nope."
elif( self.nowPlaying['CurrentTime'] > 240 or
self.nowPlaying['CurrentTime'] / self.nowPlaying['Duration'] > 0.5 ):
try:
self.lastfm.scrobble( artist = self.nowPlaying['Artist'],
title = self.nowPlaying['Track'],
timestamp = int(time.time()) )
self.nowPlaying['Scrobbled'] = True
print "Scrobbled"
except:
pass
else:
try:
self.lastfm.update_now_playing( artist = self.nowPlaying['Artist'],
title = self.nowPlaying['Track'] )
print "Now Playing set"
except:
pass
if __name__ == '__main__':
TinyScrobbler()
loop = GObject.MainLoop()
loop.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment