Copy favorite last.fm songs using Amarok DB (the masochist way)


Last night's portage sync taught me two things:

  1. Something called `config-protect-if-modified` added to portage-2.1.10.61 FEATURES. It means portage goes one step smarter for cleaning up system of unchanged configuration files. IIRC Debian has something similar for years but disabling CONFIG_PROTECT in portage was not proper way to do this.

  2. Some package called `pylast` added to portage tree.

Now let use pylast for receiving favorite tracks from last.fm account and copying them to another place. We need a simple Python script for retrieving our favorite tracks name from last.fm and then we use Amarok database for finding the path as we did before:

./fetch-from-lastfm.py
api_key = '' # get it from last.fm/api/account
api_secret = '' # get it from last.fm/api/account
last_username = ''
last_password = '' # md5 hashed password. could be made with pylast.md5

from subprocess import call
import pylast
from PyQt4.Qt import QApplication
from PyQt4 import QtSql

if __name__ == '__main__':
        db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
        db.setHostName('localhost')
        db.setUserName('amarok_user')
        db.setPassword('amarok_password')
        db.setDatabaseName('amarok')

        app = QApplication(None)
        db.open()

        query = QtSql.QSqlQuery()
        query.prepare("SELECT `U`.`rpath` from `tracks` as `T`, `artists` AS `A`, `urls` as `U` WHERE `A`.name = ? AND `T`.title = ? AND `T`.`url` = `U`.`id` LIMIT 1")


        network = pylast.LastFMNetwork(api_key, api_secret, '', last_username, last_password)
        user = network.get_user(last_username)
        top_tracks = user.get_top_tracks()

        for track in top_tracks:
                (artist, title) = str(track[0]).split(' - ', 1)
                query.bindValue(0, artist)
                query.bindValue(1, title)
                if query.exec_() and query.next():
                        call(['./copy.sh', query.value(0).toString()])

        db.close()

Store this alongside copy.sh file and run. You can parse top tracks RSS feed more easily. It doesn't need API but has nothing to do with pylast and last night's portage sync! :)