Last active
August 29, 2015 14:26
-
-
Save jorticus/12f9b0bd5467524876e5 to your computer and use it in GitHub Desktop.
Script to retrieve the complete list of di.fm channels, allowing them to be saved as pls files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib2 | |
import json | |
import sys | |
from random import randint | |
def get_channel_list(): | |
print "Requesting channel list..." | |
req = urllib2.urlopen('http://listen.di.fm/public%d' % randint(1, 3)) | |
return json.loads(req.read()) | |
def get_channel(name): | |
channels = get_channel_list() | |
for channel in channels: | |
if str(channel['id']) == name: | |
return channel | |
elif channel['key'] == name: | |
return channel | |
elif channel['name'] == name: | |
return channel | |
raise RuntimeError("Channel '%s' not found" % name) | |
def list_channels(): | |
channels = get_channel_list() | |
channels = sorted(channels, key=lambda k: k['id']) | |
print "{count} channels found:".format(count=len(channels)) | |
for channel in channels: | |
print " {id: >4}: {name}".format(**channel) | |
def save_channel(channel): | |
#filename = channel['playlist'].split('/')[-1] | |
filename = channel['name'] + '.pls' | |
print "Saving {name} : {playlist}".format(**channel) | |
req = urllib2.urlopen(channel['playlist']) | |
with open(filename, 'wb') as f: | |
f.write(req.read()) | |
req.close() | |
def save_channels(): | |
channels = get_channel_list() | |
for channel in channels: | |
save_channel(channel) | |
try: | |
if len(sys.argv) == 1: | |
list_channels() | |
else: | |
action = sys.argv[1] | |
if action == "save": | |
if len(sys.argv) == 2: | |
save_channels() | |
elif len(sys.argv) == 3: | |
channel = get_channel(sys.argv[2]) | |
save_channel(channel) | |
else: | |
raise RuntimeError("Invalid number of arguments for 'save'") | |
else: | |
raise RuntimeError("Unknown action") | |
except RuntimeError as e: | |
print "Error processing args: %s" % str(e) | |
print "Usage: %s [action [channel_name|channel_id|channel_title]]" % sys.argv[0] | |
print "Actions: " | |
print "save channel_name : Save the channel's pls" | |
print "save : Save all channel pls" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment