]> git.phdru.name Git - bookmarks_db.git/blob - bkmk_parser.py
Store charset in the DB and the generated HTML.
[bookmarks_db.git] / bkmk_parser.py
1 """
2    Parser for Netscape Navigator's and Mozilla's bookmarks.html
3
4    Written by BroytMann. Copyright (C) 1997-2005 PhiloSoft Design
5 """
6
7
8 import sys, os
9 from m_lib.net.www.html import HTMLParser
10 from bkmk_objects import Folder, Bookmark, Ruler
11
12
13 DEBUG = os.environ.has_key("BKMK_DEBUG")
14
15 if DEBUG:
16    def debug(note):
17       print note
18
19    def dump_names(folder_stack):
20       l = []
21       for object in folder_stack:
22          if object.isFolder:
23             l.append(object.name)
24       return "'%s'" % "' '".join(l)
25
26 else:
27    def debug(note):
28       pass
29    dump_names = debug
30
31
32 DEFAULT_CHARSET = None
33
34 class BkmkParser(HTMLParser):
35    def __init__(self):
36       HTMLParser.__init__(self)
37
38       self.urls = 0
39       self.objects = 0
40
41       self.charset = ""
42       self.recode = None
43
44
45    def handle_data(self, data):
46       if data:
47          if DEFAULT_CHARSET:
48             data = unicode(data, self.charset, "replace").encode(DEFAULT_CHARSET, "replace")
49          self.accumulator += data
50
51
52    # Mozilla - get charset
53    def do_meta(self, attrs):
54       http_equiv = ""
55       content = ""
56
57       for attrname, value in attrs:
58          value = value.strip()
59          if attrname == 'http-equiv':
60             http_equiv = value.lower()
61          elif attrname == 'content':
62             content = value
63
64       if http_equiv == "content-type":
65          try:
66             # extract charset from "text/html; charset=UTF-8"
67             self.charset = content.split('=')[1]
68          except IndexError:
69             pass
70          else:
71             global DEFAULT_CHARSET
72             DEFAULT_CHARSET = sys.getdefaultencoding()
73             if DEFAULT_CHARSET == "ascii":
74                try:
75                   import locale
76                except ImportError:
77                   pass
78                else:
79                   DEFAULT_CHARSET = locale.getpreferredencoding()
80
81
82    def start_title(self, attrs):
83       if DEFAULT_CHARSET:
84          self.accumulator += '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%s">\n' % DEFAULT_CHARSET
85       self.accumulator += "<TITLE>"
86
87    def end_title(self):
88       self.accumulator += "</TITLE>"
89
90
91    # Start root folder
92    def start_h1(self, attrs):
93       root_folder = Folder()
94       self.current_object = root_folder
95       self.root_folder = root_folder
96       self.current_folder = root_folder
97       self.folder_stack = [root_folder]
98
99       self.root_folder.header = self.accumulator.strip()
100       self.accumulator = ''
101
102    def end_h1(self):
103       accumulator = self.accumulator
104       self.accumulator = ''
105
106       debug("Root folder name: `%s'" % accumulator)
107       self.root_folder.name = accumulator
108
109
110    # Start a folder
111    def start_h3(self, attrs):
112       for attrname, value in attrs:
113          value = value.strip()
114          if attrname == 'add_date':
115             add_date = value
116
117       debug("New folder...")
118       folder = Folder(add_date)
119       self.current_object = folder
120       self.current_folder.append(folder)
121       self.folder_stack.append(folder) # push new folder
122       self.current_folder = folder
123       self.objects += 1
124
125    def end_h3(self):
126       accumulator = self.accumulator
127       self.accumulator = ''
128
129       debug("Folder name: `%s'" % accumulator)
130       self.current_folder.name = accumulator
131
132
133    # Start a bookmark
134    def start_a(self, attrs):
135       last_visit = None
136       last_modified = None
137       keyword = None
138
139       for attrname, value in attrs:
140          value = value.strip()
141          if attrname == "href":
142             href = value
143          elif attrname == "add_date":
144             add_date = value
145          elif attrname == "last_visit":
146             last_visit = value
147          elif attrname == "last_modified":
148             last_modified = value
149          elif attrname == "shortcuturl":
150             keyword = value
151
152       debug("Bookmark points to: `%s'" % href)
153       bookmark = Bookmark(href, add_date, last_visit, last_modified, keyword or '')
154       self.current_object = bookmark
155       self.current_folder.append(bookmark)
156       self.urls += 1
157       self.objects += 1
158
159    def end_a(self):
160       accumulator = self.accumulator
161       self.accumulator = ''
162
163       debug("Bookmark name: `%s'" % accumulator)
164       bookmark = self.current_folder[-1]
165       bookmark.name = accumulator
166
167
168    def flush(self):
169       accumulator = self.accumulator
170
171       if accumulator:
172          self.accumulator = ''
173
174          current_object = self.current_object
175          if current_object:
176             current_object.comment += accumulator.strip()
177             debug("Comment: `%s'" % current_object.comment)
178
179
180    def start_dl(self, attrs):
181       self.flush()
182
183    do_dt = start_dl
184
185
186    # End of folder
187    def end_dl(self):
188       self.flush()
189       debug("End folder")
190       debug("Folder stack: %s" % dump_names(self.folder_stack))
191       if self.folder_stack:
192          del self.folder_stack[-1] # pop last folder
193          if self.folder_stack:
194             self.current_folder = self.folder_stack[-1]
195          else:
196             debug("FOLDER STACK is EMPTY!!! (1)")
197       else:
198          debug("FOLDER STACK is EMPTY!!! (2)")
199       self.current_object = None
200
201
202    def close(self):
203       HTMLParser.close(self)
204       if self.folder_stack:
205          raise ValueError, "wrong folder stack: %s" % self.folder_stack
206
207
208    def do_dd(self, attrs):
209       pass
210
211    do_p = do_dd
212
213
214    # Start ruler
215    def do_hr(self, attrs):
216       self.flush()
217       debug("Ruler")
218       self.current_folder.append(Ruler())
219       self.current_object = None
220       self.objects += 1
221
222
223    # BR in comment
224    def do_br(self, attrs):
225       self.accumulator += "<BR>"
226
227
228    # Allow < in the text
229    def unknown_starttag(self, tag, attrs):
230       self.accumulator += "<%s>" % tag
231
232
233    # Do not allow unknow end tags
234    def unknown_endtag(self, tag):
235       raise NotImplementedError("Unknow end tag `%s'" % tag)