#!/usr/local/bin/python

# handrss.py -- Use an OPML file (XML "subscription list" for an RSS reader)
#     to update the "RSS Source URLs" Palm PDB file for the Hand/RSS reader.
#
# Hand/RSS itself is at http://standalone.com/palmos/hand_rss/
# The original peepdb is at http://linux.piter-press.ru/peepdb/
#   but you probably need the patches in the version distributed near this file
#
# Copyright 2003 Mark Eichin <eichin@thok.org>
# free for all use, please send me patches or info about interesting uses.

import peepdb
import os
import sys
import struct

import xml.dom
import xml.dom.minidom

progname, palmuser = sys.argv
home = os.getenv("HOME")
oplfile = xml.dom.minidom.parse(os.path.join(home, "MySubscriptions.opml"))

def fakexpath(nodes, xmldoc):
    if not nodes:
        return [xmldoc]
    hotnodes = [n for n 
                in xmldoc.childNodes 
                if n.nodeType == xml.dom.Node.ELEMENT_NODE
                and n.nodeName == nodes[0]]
    res = []
    # can't use a comprehension because they're all lists...
    for node in hotnodes:
        res.extend(fakexpath(nodes[1:], node))
    return res

oplentries = {}
oplorder = []
for opl in fakexpath(["opml", "body", "outline"], oplfile):
    xmlurl = opl.attributes["xmlUrl"].nodeValue.encode("iso-8859-1")
    title = opl.attributes["title"].nodeValue.encode("iso-8859-1")
    oplentries[xmlurl] = title
    oplorder.append(xmlurl)

rssfile = "RSS Source URLs.pdb"

filename = os.path.join(home, "Documents/Palm/Users", palmuser, "Backups", rssfile)

outfilename = os.path.join(home, "Documents/Palm/Users", palmuser, "Files to Install", rssfile)

p = peepdb.palmdb('load', filename)

def cvt_id(id):
    return struct.unpack(">BH", id)
def make_id(id):
    return struct.pack(">BH", 100, id)

idlow = [struct.unpack(">BH",r[0].get_id())[1] for r in p.records]
idlow.sort()
pdbentries = {}
pdborder = []
for r in p.records:
    pdbtitle,pdburl,tail = r[1][48:].split("\0")
    pdbentries[pdburl] = pdbtitle
    pdborder.append(pdburl)

def next_id():
    nid = idlow[-1] + 1
    idlow.append(nid)
    return nid




def add_rss_record(p, title, url):
    lastrec = p.records[-1]
    id = next_id()
    shorturl = url.replace("http://", "")
    data = lastrec[1][:48] + title + "\0" + shorturl + "\0"
    p.create_new_record(make_id(id), data)
    p.records[-1][0].set_dirty_bit(1)

# title = "Burn Before Reading"
# shorturl = "www-images.thok.org/~burnbeforereading/index.rss"
# add_rss_record(p, title, shorturl)

for shorturl in pdborder:
    url = "http://" + shorturl
    if url not in oplorder:
        print "only on palm:", url, pdbentries[shorturl]

for url in oplorder:
    if not url.startswith("http://"):
        print "not http:", url
        continue
    shorturl = url.replace("http://", "")
    if shorturl in pdborder:
        print "already present:", url
        continue
    add_rss_record(p, oplentries[url], url)

p.save_to_file(outfilename)