-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookmark_utils.py
293 lines (237 loc) · 8.55 KB
/
bookmark_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""reads a bookmark html export in the `<!DOCTYPE NETSCAPE-Bookmark-file-1>` browser format
I've checked, and firefox, edge, and vivaldi all use this format
"""
import json
import sys
import warnings
from dataclasses import asdict, dataclass, field
from typing import Iterator, List
from bs4 import BeautifulSoup, PageElement # type: ignore[import]
from muutils.json_serialize import json_serialize # type: ignore[import]
# pylint: disable=missing-class-docstring,pointless-string-statement
@dataclass(kw_only=True)
class Bookmark:
title: str
href: str
add_date: int
_parent: "BookmarkFolder|None" = field(default=None, repr=False, compare=False)
tags: List[str] | None = None
def serialize(self) -> dict:
return dict(
title=self.title,
href=self.href,
add_date=self.add_date,
tags=self.tags,
)
@classmethod
def load(cls, data: dict) -> "Bookmark":
return cls(**data)
@dataclass
class BookmarkFolder:
title: str
add_date: int | None
last_modified: int | None
contents: list["Bookmark|BookmarkFolder"]
_parent: "BookmarkFolder|None" = field(default=None, repr=False, compare=False)
_being_serialized: bool = False
def serialize(self) -> dict:
if self._being_serialized:
raise RuntimeError("recursive serialization")
self._being_serialized = True
return dict(
title=self.title,
add_date=self.add_date,
last_modified=self.last_modified,
contents=[x.serialize() for x in self.contents],
)
@classmethod
def load(cls, data: dict | list) -> "BookmarkFolder":
output: "BookmarkFolder"
if isinstance(data, list):
output = cls(
title="_root",
add_date=None,
last_modified=None,
contents=[
Bookmark.load(x) if "href" in x else BookmarkFolder.load(x)
for x in data
],
)
elif isinstance(data, dict):
output = cls(
title=data["title"],
add_date=data["add_date"],
last_modified=data["last_modified"],
contents=[
Bookmark.load(x) if "href" in x else BookmarkFolder.load(x)
for x in data["contents"]
],
)
else:
raise TypeError(f"invalid type {type(data)}")
output.set_parents()
return output
def get_child(self, title: str) -> "Bookmark|BookmarkFolder":
"""get a child from `contents` by title"""
for x in self.contents:
if x.title == title:
return x
raise KeyError(f"no child with title {title}")
def __getitem__(self, title: str) -> "Bookmark|BookmarkFolder":
return self.get_child(title)
def iter_bookmarks(self) -> Iterator[Bookmark]:
for x in self.contents:
if isinstance(x, Bookmark):
yield x
else:
yield from x.iter_bookmarks()
def count_bookmarks(self) -> int:
"""counts downstream bookmarks"""
return sum(
1 if isinstance(x, Bookmark) else x.count_bookmarks() for x in self.contents
)
def get_tree(self) -> dict:
"""gets only the downstream folder structure, not the bookmarks"""
output: dict = dict()
for x in self.contents:
if isinstance(x, Bookmark):
continue
output[x.title] = x.get_tree()
return output
def set_parents(self) -> None:
"""sets the parent attribute of all children"""
for x in self.contents:
x._parent = self
if isinstance(x, BookmarkFolder):
x.set_parents()
def process_child(element: PageElement) -> Bookmark | BookmarkFolder | None:
if element.name == "h3":
bkfolder: BookmarkFolder = BookmarkFolder(
title=element.string,
add_date=element["add_date"] if "add_date" in element else None,
last_modified=element["last_modified"]
if "last_modified" in element
else None,
contents=list(),
)
child_elements = element.find_next_sibling("dl")
# preserve order, and loop over both folders and bookmarks at once
for child in child_elements.children:
p: Bookmark | BookmarkFolder | None = process_child(child)
if p is not None:
p._parent = bkfolder
bkfolder.contents.append(p)
return bkfolder
elif element.name == "dl":
# we skip it, because the sibling dl element should be processed in `get_bookmark_folder`
return None
elif element.name == "a":
return Bookmark(
title=element.string,
href=element["href"],
add_date=element["add_date"],
)
else:
warnings.warn(f"unexpected tag {element.name}")
# raise ValueError(f"unexpected tag {element.name}")
return None
def process_bookmark_file(data: str) -> BookmarkFolder:
# this part is a hack: remove all <DT> and <p> tags, they are useless and complicate things
data = (
data.replace("<DT>", "")
.replace("<dt>", "")
.replace("<p>", "")
.replace("<P>", "")
)
# parse the html
soup: BeautifulSoup = BeautifulSoup(data, "html.parser")
# the structure is now as follows:
"""<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL>
<H3 add_date="1624139022" last_modified="1674165683" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks</H3>
<DL>
<DT><A HREF="https://calendar.google.com/calendar/r" add_date="1594058447">calendar</A>
<DT><A HREF="https://github.com/" add_date="1657553942">github</A>
..............
"""
# find title
title = soup.find("h1").string
# the first dl element is the root folder, get the <p> inside it
root_folder = soup.find("dl")
output = BookmarkFolder(
title=title,
add_date=None,
last_modified=None,
contents=list(),
)
# we want to iterate over all the children of the root folder
for child in root_folder.children:
p: Bookmark | BookmarkFolder | None = process_child(child)
if p is not None:
p._parent = output
output.contents.append(p)
return output
def flatten_bookmarks(folder: BookmarkFolder) -> list[Bookmark]:
"""tag bookmark with position in the folder hierarchy"""
output: list[Bookmark] = list()
# use the iterator of the folder to get all contained bookmarks, not just direct children
bk: Bookmark
for bk in folder.iter_bookmarks():
tags_temp: list[str] = list()
bk_temp: Bookmark | BookmarkFolder = bk
# loop until root
while bk_temp._parent is not None:
tags_temp.append(bk_temp._parent.title)
bk_temp = bk_temp._parent
bk.tags = tags_temp[::-1]
output.append(bk)
return output
def main(
fname: str,
flatten: bool = False,
tree: bool = False,
select: str | None = None,
):
# read file
with open(fname, "r", encoding="utf-8") as f:
data = f.read()
# load as html or json
bookmarks: BookmarkFolder
if any(
[
fname.endswith(".html"),
fname.endswith(".htm"),
data.startswith("<!DOCTYPE NETSCAPE-Bookmark-file-1>"),
]
):
bookmarks = process_bookmark_file(data)
elif any(
[
fname.endswith(".json"),
data.startswith("{"),
]
):
js_temp = json.loads(data)
bookmarks = BookmarkFolder.load(json.loads(data))
else:
raise ValueError(f"unknown file format for {fname}")
print(f"{bookmarks.count_bookmarks()} bookmarks found", file=sys.stderr)
if flatten:
if tree:
raise ValueError("cannot flatten and print tree at the same time")
bookmarks = flatten_bookmarks(bookmarks) # type: ignore
if select is not None:
# select by path
path: list[str] = select.split("/")
for p in path:
bookmarks = bookmarks.get_child(p) # type: ignore
if tree:
print(json.dumps(bookmarks.get_tree(), indent="\t"))
else:
print(json.dumps(json_serialize(bookmarks), indent="\t"))
if __name__ == "__main__":
import fire # type: ignore[import]
fire.Fire(main)