]> git.phdru.name Git - bookmarks_db.git/blob - bkmk_parser.py
If sys.getdefaultencoding() returns "ascii" - use
[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       self.accumulator += "<TITLE>"
84
85    def end_title(self):
86       self.accumulator += "</TITLE>"
87
88
89    # Start root folder
90    def start_h1(self, attrs):
91       root_folder = Folder()
92       self.current_object = root_folder
93       self.root_folder = root_folder
94       self.current_folder = root_folder
95       self.folder_stack = [root_folder]
96
97       self.root_folder.header = self.accumulator.strip()
98       self.accumulator = ''
99
100    def end_h1(self):
101       accumulator = self.accumulator
102       self.accumulator = ''
103
104       debug("Root folder name: `%s'" % accumulator)
105       self.root_folder.name = accumulator
106
107
108    # Start a folder
109    def start_h3(self, attrs):
110       for attrname, value in attrs:
111          value = value.strip()
112          if attrname == 'add_date':
113             add_date = value
114
115       debug("New folder...")
116       folder = Folder(add_date)
117       self.current_object = folder
118       self.current_folder.append(folder)
119       self.folder_stack.append(folder) # push new folder
120       self.current_folder = folder
121       self.objects += 1
122
123    def end_h3(self):
124       accumulator = self.accumulator
125       self.accumulator = ''
126
127       debug("Folder name: `%s'" % accumulator)
128       self.current_folder.name = accumulator
129
130
131    # Start a bookmark
132    def start_a(self, attrs):
133       last_visit = None
134       last_modified = None
135       keyword = None
136
137       for attrname, value in attrs:
138          value = value.strip()
139          if attrname == "href":
140             href = value
141          elif attrname == "add_date":
142             add_date = value
143          elif attrname == "last_visit":
144             last_visit = value
145          elif attrname == "last_modified":
146             last_modified = value
147          elif attrname == "shortcuturl":
148             keyword = value
149
150       debug("Bookmark points to: `%s'" % href)
151       bookmark = Bookmark(href, add_date, last_visit, last_modified, keyword or '')
152       self.current_object = bookmark
153       self.current_folder.append(bookmark)
154       self.urls += 1
155       self.objects += 1
156
157    def end_a(self):
158       accumulator = self.accumulator
159       self.accumulator = ''
160
161       debug("Bookmark name: `%s'" % accumulator)
162       bookmark = self.current_folder[-1]
163       bookmark.name = accumulator
164
165
166    def flush(self):
167       accumulator = self.accumulator
168
169       if accumulator:
170          self.accumulator = ''
171
172          current_object = self.current_object
173          if current_object:
174             current_object.comment += accumulator.strip()
175             debug("Comment: `%s'" % current_object.comment)
176
177
178    def start_dl(self, attrs):
179       self.flush()
180
181    do_dt = start_dl
182
183
184    # End of folder
185    def end_dl(self):
186       self.flush()
187       debug("End folder")
188       debug("Folder stack: %s" % dump_names(self.folder_stack))
189       if self.folder_stack:
190          del self.folder_stack[-1] # pop last folder
191          if self.folder_stack:
192             self.current_folder = self.folder_stack[-1]
193          else:
194             debug("FOLDER STACK is EMPTY!!! (1)")
195       else:
196          debug("FOLDER STACK is EMPTY!!! (2)")
197       self.current_object = None
198
199
200    def close(self):
201       HTMLParser.close(self)
202       if self.folder_stack:
203          raise ValueError, "wrong folder stack: %s" % self.folder_stack
204
205
206    def do_dd(self, attrs):
207       pass
208
209    do_p = do_dd
210
211
212    # Start ruler
213    def do_hr(self, attrs):
214       self.flush()
215       debug("Ruler")
216       self.current_folder.append(Ruler())
217       self.current_object = None
218       self.objects += 1
219
220
221    # BR in comment
222    def do_br(self, attrs):
223       self.accumulator += "<BR>"
224
225
226    # Allow < in the text
227    def unknown_starttag(self, tag, attrs):
228       self.accumulator += "<%s>" % tag
229
230
231    # Do not allow unknow end tags
232    def unknown_endtag(self, tag):
233       raise NotImplementedError("Unknow end tag `%s'" % tag)