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