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