]> git.phdru.name Git - bookmarks_db.git/blob - Storage/bkmk_stjson.py
cd6139faa36c66afdaf65c57deb479e13e46b99f
[bookmarks_db.git] / Storage / bkmk_stjson.py
1 """
2     Bookmarks storage manager - json.
3
4     Written by Broytman, Jul 2010. Copyright (C) 2010 PhiloSoft Design
5 """
6
7
8 try:
9    import json
10 except ImportError:
11    import simplejson as json
12
13 from bkmk_objects import Folder, Bookmark, Ruler, Walker
14
15
16 class storage_json(Walker):
17     filename = "bookmarks_db.json"
18
19     def root_folder(self, f):
20         self.dict = dict = {}
21         dict["children"] = children = []
22         self.folder_stack = [children]
23         dict["dateAdded"] = f.add_date
24         dict["id"] = f.id
25         dict["lastModified"] = f.last_modified
26         dict["root"] = "placesRoot"
27         dict["title"] = ""
28         dict["type"] = "text/x-moz-place-container"
29
30     def start_folder(self, f, level):
31         dict = {}
32         comment = getattr(f, 'comment')
33         if comment: dict["annos"] = make_annos(comment)
34         dict["children"] = children = []
35         dict["dateAdded"] = f.add_date
36         dict["id"] = f.id
37         index = getattr(f, 'index')
38         if index: dict["index"] = index
39         dict["lastModified"] = f.last_modified
40         parent_idx = getattr(f, 'parent_idx')
41         if parent_idx: dict["parent"] = parent_idx
42         dict["title"] = f.name.decode('utf-8')
43         dict["type"] = "text/x-moz-place-container"
44         self.folder_stack[-1].append(dict)
45         self.folder_stack.append(children)
46
47     def end_folder(self, f, level):
48         del self.folder_stack[-1]
49
50     def bookmark(self, b, level):
51         dict = {}
52         comment = getattr(b, 'comment')
53         if comment: dict["annos"] = make_annos(comment)
54         charset = getattr(b, 'charset')
55         if charset: dict["charset"] = charset
56         dict["dateAdded"] = b.add_date
57         dict["id"] = b.id
58         index = getattr(b, 'index')
59         if index: dict["index"] = index
60         keyword = getattr(b, 'keyword')
61         if keyword: dict["keyword"] = keyword
62         dict["lastModified"] = b.last_modified
63         dict["parent"] = b.parent_idx
64         dict["title"] = b.name.decode('utf-8')
65         dict["type"] = "text/x-moz-place"
66         dict["uri"] = b.href
67         self.folder_stack[-1].append(dict)
68
69     def ruler(self, r, level):
70         dict = {}
71         comment = getattr(r, 'comment')
72         if comment: dict["annos"] = make_annos(comment)
73         dict["dateAdded"] = r.add_date
74         dict["id"] = r.id
75         dict["index"] = r.index
76         dict["lastModified"] = r.last_modified
77         dict["parent"] = r.parent_idx
78         dict["title"] = r.name.decode('utf-8')
79         dict["type"] = "text/x-moz-place-separator"
80         self.folder_stack[-1].append(dict)
81
82     def store(self, root_folder):
83         root_folder.walk_depth(self)
84
85         outfile = open(self.filename, 'wb')
86         json.dump(self.dict, outfile)
87         outfile.close()
88         del self.dict
89
90
91     def load(self):
92         infile = open(self.filename, 'rb')
93         bkmk_s = infile.read()
94         infile.close()
95
96         # Work around a bug in Mozilla - remove the trailing comma
97         bkmk_s = bkmk_s.strip().replace(',]', ']')
98         bookmarks_dict = json.loads(bkmk_s)
99
100         root_folder = Folder()
101         root_folder.header = ''
102         root_folder.add_date = bookmarks_dict["dateAdded"]
103         root_folder.comment = ''
104         root_folder.last_modified = bookmarks_dict["lastModified"]
105         self.folder_stack = [root_folder]
106         self.current_folder = root_folder
107
108         self.load_folder(root_folder, bookmarks_dict)
109         if self.folder_stack:
110             raise RuntimeError('Excessive folder stack: %s' % self.folder_stack)
111
112         return root_folder
113
114     def load_folder(self, folder, fdict):
115         if fdict["type"] != "text/x-moz-place-container":
116             raise ValueError("Root object is not a Mozilla container")
117
118         folder.id = fdict["id"]
119         folder.index = fdict.get("index")
120         folder.parent_idx = fdict.get("parent")
121         folder.name = encode(fdict["title"])
122
123         for record in fdict["children"]:
124             if record["type"] == "text/x-moz-place-container":
125                 folder = Folder(
126                     add_date=record["dateAdded"],
127                     comment=get_comment(record.get("annos")),
128                     last_modified=record["lastModified"])
129                 self.current_folder.append(folder)
130                 self.folder_stack.append(folder)
131                 self.current_folder = folder
132                 self.load_folder(folder, record)
133
134             elif record["type"] == "text/x-moz-place":
135                 bookmark = Bookmark(
136                     href=record["uri"],
137                     add_date=record.get("dateAdded"),
138                     last_modified=record.get("lastModified"),
139                     keyword=record.get("keyword"),
140                     comment=get_comment(record.get("annos")),
141                     charset=record.get("charset"))
142                 bookmark.id = record["id"]
143                 bookmark.index = record.get("index")
144                 bookmark.parent_idx = record["parent"]
145                 bookmark.name = encode(record["title"])
146                 self.current_folder.append(bookmark)
147
148             elif record["type"] == "text/x-moz-place-separator":
149                 ruler = Ruler()
150                 ruler.add_date = record["dateAdded"]
151                 ruler.id = record["id"]
152                 ruler.index = record["index"]
153                 ruler.last_modified = record["lastModified"]
154                 ruler.parent_idx = record["parent"]
155                 ruler.name = encode(record["title"])
156                 ruler.comment = get_comment(record.get("annos"))
157                 self.current_folder.append(ruler)
158
159             else:
160                 raise ValueError('Unknown record type "%s"' % record["type"])
161
162         del self.folder_stack[-1]
163         if self.folder_stack:
164             self.current_folder = self.folder_stack[-1]
165         else:
166             self.current_folder = None
167
168 def encode(title):
169     return title.encode("UTF-8", "xmlcharrefreplace")
170
171 def get_comment(annos):
172     if not annos:
173         return None
174
175     for a in annos:
176         if a["name"] == "bookmarkProperties/description" and \
177                 a["type"] == 3:
178             return a["value"].encode('utf-8')
179
180     return None
181
182 def make_annos(comment):
183     return [{
184         "expires": 4,
185         "flags": 0,
186         "mimeType": None,
187         "name": "bookmarkProperties/description",
188         "type": 3,
189         "value": comment.decode('utf-8')}]