SomaFM Integration for WiiMC

This Python script takes your apps/wiimc/onlinemedia.xml file and adds all current SomaFM stations as streaming sources. If stations are added or removed, rerun the script to update.

#!/usr/bin/env python
"""usage: wiimc-somafm ONLINEMEDIA"""

from cStringIO import StringIO

from requests import get
from docopt import docopt
from lxml import etree
from lxml.builder import E

NAME = "SomaFM"
CHANNELS_URL = "http://somafm.com/channels.xml"
XML_HEADER = "<?xml version='1.0' encoding='utf-8'?>\n"
filename = docopt(__doc__)["ONLINEMEDIA"]

def main():
    fp = file(filename)
    onlinemedia = etree.parse(fp)
    fp.close()

    root = onlinemedia.getroot()
    rm = onlinemedia.xpath("/file/folder[@name='%s']" % NAME)
    if rm:
        print "Removing existing SomaFM installation..."
        rm[0].getparent().remove(rm[0])

    print "Downloading channels..."
    channels = etree.parse(StringIO(get(CHANNELS_URL).text))
    channels_iter = channels.xpath('/channels/channel')
    folder = E.folder({"name": NAME})

    for c in channels_iter:
        url = c.xpath('fastpls[@format="mp3"]/text()')[0]
        title = c.xpath('title/text()')[0]
        folder.append(E.link({"name": title, "addr": url}))

    root.append(folder)

    print "Installing SomaFM to WiiMC..."
    fp = file(filename, "w")
    fp.write(XML_HEADER + etree.tostring(root, pretty_print=True))
    fp.close()

    print "Done!"

if __name__ == "__main__":
    main()