//depot/projects/podgrab/podgrab.py#2 – edit change 91 (xtext) ·revision history
| 1 | #!/usr/bin/env python |
| 2 | """podgrab - fetch podcast enclosures and drop them on the iPod. |
| 3 | |
| 4 | usage: podgrab.py [feeds.opml] |
| 5 | |
| 6 | ksimpson, oct 2004. needs Python 2.3. |
| 7 | """ |
| 8 | |
| 9 | import os |
| 10 | import shutil |
| 11 | import sys |
| 12 | import urllib |
| 13 | from xml.dom import minidom |
| 14 | |
| 15 | IPOD = "/Volumes/IPOD" |
| 16 | CACHE = os.path.expanduser("~/.podgrab") |
| 17 | SEEN = os.path.join(CACHE, "seen") |
| 18 | |
| 19 | |
| 20 | def read_opml(path): |
| 21 | dom = minidom.parse(path) |
| 22 | feeds = [] |
| 23 | for node in dom.getElementsByTagName("outline"): |
| 24 | url = node.getAttribute("xmlUrl") |
| 25 | if url: |
| 26 | feeds.append((node.getAttribute("text"), url)) |
| 27 | return feeds |
| 28 | |
| 29 | |
| 30 | def enclosures(feed_url): |
| 31 | dom = minidom.parse(urllib.urlopen(feed_url)) |
| 32 | for item in dom.getElementsByTagName("item"): |
| 33 | for enc in item.getElementsByTagName("enclosure"): |
| 34 | yield enc.getAttribute("url") |
| 35 | |
| 36 | |
| 37 | def load_seen(): |
| 38 | seen = {} |
| 39 | if not os.path.exists(SEEN): |
| 40 | return seen |
| 41 | for line in open(SEEN): |
| 42 | seen[line.strip()] = 1 |
| 43 | return seen |
| 44 | |
| 45 | |
| 46 | def main(argv): |
| 47 | opml = len(argv) > 1 and argv[1] or "feeds.opml" |
| 48 | if not os.path.isdir(CACHE): |
| 49 | os.makedirs(CACHE) |
| 50 | seen = load_seen() |
| 51 | out = open(SEEN, "a") |
| 52 | for title, url in read_opml(opml): |
| 53 | print "==>", title |
| 54 | try: |
| 55 | encs = list(enclosures(url)) |
| 56 | except Exception, e: |
| 57 | print " feed broken:", e |
| 58 | continue |
| 59 | for enc in encs: |
| 60 | if enc in seen: |
| 61 | continue |
| 62 | fname = os.path.join(CACHE, os.path.basename(enc)) |
| 63 | print " ", enc |
| 64 | urllib.urlretrieve(enc, fname) |
| 65 | out.write(enc + "\n") |
| 66 | if os.path.isdir(IPOD): |
| 67 | # NB: this does not update the iTunesDB. use gtkpod, or |
| 68 | # just play it from the notes folder like a caveman. |
| 69 | shutil.copy(fname, os.path.join(IPOD, "Podcasts")) |
| 70 | out.close() |
| 71 | |
| 72 | |
| 73 | if __name__ == "__main__": |
| 74 | main(sys.argv) |