Skip to content

Instantly share code, notes, and snippets.

@zaim
Created July 8, 2009 05:05
Show Gist options
  • Save zaim/142595 to your computer and use it in GitHub Desktop.
Save zaim/142595 to your computer and use it in GitHub Desktop.
Grabs the current song title and artist name playing on hitz.fm and save it in a playlist log file
#!/usr/bin/python
"Grabs the current song title and artist name playing on hitz.fm and save it in a playlist log file"
import os
import re
import sys
import time
import urllib2
from email import utils
REGEX = re.compile('^var\s+([^\s]+)\s*="([^"]*)"$', re.MULTILINE)
SONG_LIST_FILE = 'songs'
CURRENT_SONG_FILE = 'current_song'
def read_url(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) \
AppleWebKit/530.5 (KHTML, like Gecko) Chrome/2.0.172.33 Safari/530.5')
f = urllib2.urlopen(req)
c = f.read()
f.close()
return c, f.info()
def parse_js(js):
"Parses a 'now playing' javascript returing a tuple of artist, song, album"
matches = dict(REGEX.findall(js))
for k, v in matches.items():
matches[k] = v.strip().replace("\t", "").replace("_", " ")
default = {
'strthesong' : '',
'strartist' : '',
'stralbumcover': ''
}
default.update(matches)
return (default['strthesong'], default['strartist'], default['stralbumcover'])
def update():
"Main function"
c, info = read_url('http://www.hitz.fm/cgi-bin/dvr/inc_nowplaying_hitz.js')
c = c.replace("\r", "") # fix windows newline
now_playing = "%s\t%s\t%s" % parse_js(c)
played_at_t = utils.parsedate(info['last-modified'])
played_at = time.mktime(played_at_t)
last_song = ''
last_modified = 0
for line in open(CURRENT_SONG_FILE):
last_modified = float(line.split("\t")[0].strip())
last_song = "\t".join(line.split("\t")[1:]).strip()
break # the file is just 1 line
if played_at > last_modified and now_playing.strip() != last_song:
for n in [(SONG_LIST_FILE, 'a'), (CURRENT_SONG_FILE, 'w')]:
f = open(n[0], n[1])
f.write("%f\t%s\n" % (played_at, now_playing))
f.close()
print "%s - %s" % (time.strftime("%x %X", played_at_t), now_playing)
if __name__ == '__main__':
curdir = os.path.dirname(os.path.abspath(sys.argv[0]))
SONG_LIST_FILE = os.path.join(curdir, SONG_LIST_FILE)
CURRENT_SONG_FILE = os.path.join(curdir, CURRENT_SONG_FILE)
for n in (SONG_LIST_FILE, CURRENT_SONG_FILE):
if not os.path.isfile(n):
f = open(n, 'w')
f.close()
try:
while 1:
update()
time.sleep(180)
except KeyboardInterrupt:
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment