lib/xbelimp.py
author fabien
Tue, 07 Oct 2003 00:07:32 -0400
branchxbelweb
changeset 33 db91081e5a78
parent 26 17b0cd274530
permissions -rw-r--r--
[svn r1577] Various change to the new interface.

#!/usr/bin/python

from xbel_handler import XBELHandler, bookmark
from xml.sax import saxexts
import bkmark

def parse_xbel(xbelfile):
    xbel_handler = XBELHandler()
    p=saxexts.XMLParserFactory.make_parser("xml.sax.drivers.drv_xmlproc")
    p.setDocumentHandler( xbel_handler )
    p.parseFile( xbelfile )
    return  xbel_handler.bms

_keywords = {}
    
def import_bookmarks(db, bms):
	global _keywords
	_keywords = {}
	for elem in db.get_all_keywords():
		_keywords[elem[1]] = elem[0]
	#print "<body>"
	#print "<ol>"
	for child in bms.folders:
		if isinstance(child, bookmark.Bookmark):
			import_bookmark(db, child)
		else:
			import_folder(db, child)
	#print "</ol>"

def import_folder(db, folder, keywords = []):
	global _keywords
	kw = folder.title.strip().encode('utf-8')
	#print "<li>" + kw
	if _keywords.has_key(kw):
		id = _keywords[kw]
		#print " [%d]" % (id,)
	else:
		id = db.add_keyword(kw)
		id = len(_keywords)
		#print " [%d] (added)" % (id,)
		_keywords[kw] = id
	#print "<ol>"
	for child in folder.children:
		if isinstance(child, bookmark.Bookmark):
			import_bookmark(db, child, keywords+[id])
		else:
			import_folder(db, child, keywords+[id])
	#print "</ol></li>"

def import_bookmark(db, bookmark, keywords = []):
	bk = bkmark.Bookmark()
	bk.name = bookmark.title.encode('utf-8')
	bk.url = bookmark.href.encode('utf-8')
	if hasattr(bookmark, 'desc'):
		bk.desc = bookmark.desc.encode('utf-8')
	id = db.add_bookmark(bk)
	#print "<li>add bookmark '" + bk.name + "' [%d]" % (id,)
	#print " with keywords '" + ','.join(map(str,keywords)) + "'</li>"
	db.update_keywords(id, keywords)