--- /dev/null
+#!/usr/bin/env python
+
+from lxml import etree
+import os
+import subprocess
+import sys
+import tempfile
+import urllib
+import urlparse
+
+
+def exec_subprocess(cmd):
+ try:
+ p = subprocess.Popen(cmd)
+ ret = p.wait()
+ if ret != 0:
+ print >>sys.stderr, cmd[0], "exited with error code:", ret
+ return False
+ else:
+ return True
+ except OSError, e:
+ print >>sys.stderr, "Failed to run", cmd[0], e
+ except KeyboardInterrupt:
+ print "Cancelled", cmd
+ try:
+ p.terminate()
+ p.wait()
+ except KeyboardInterrupt:
+ p.send_signal(signal.SIGKILL)
+ p.wait()
+ return False
+
+def mplayer_convert(stream, author, title):
+ print "Downloading", stream
+ wmfile = tempfile.NamedTemporaryFile()
+ cmd = [
+ "mplayer",
+ "-nocache",
+ "-noconsolecontrols",
+ "-ao",
+ "pcm:file=" + wmfile.name,
+ stream,
+ ]
+ if not exec_subprocess(cmd):
+ return False
+
+ print "Converting", wmfile.name, "to mp3"
+ cmd = [
+ "lame",
+ "--add-id3v2",
+ "--ta", author,
+ "--tt", title,
+ wmfile.name,
+ os.path.splitext(os.path.basename(stream))[0] + ".mp3",
+ ]
+ if not exec_subprocess(cmd):
+ return False
+
+ return True
+
+
+def grab(u):
+ qs = urlparse.parse_qs(urlparse.urlparse(u).query)
+ wmfile = qs["w"][0]
+ doc = etree.parse(urllib.urlopen(wmfile))
+ streams = doc.xpath("//ref/@href")
+
+ author = qs["pgm"]
+ title = qs["t"]
+
+ for stream in streams:
+ if not stream.startswith("mms://"):
+ continue
+ if mplayer_convert(stream, author, title):
+ return
+
+print "Paste 'Listen Now' URLs from ABC... Press CTRL-D to finish"
+try:
+ for line in sys.stdin:
+ grab(line)
+except KeyboardInterrupt:
+ print "\nExiting..."
+