-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleBookmarks.py
More file actions
executable file
·238 lines (219 loc) · 7.42 KB
/
GoogleBookmarks.py
File metadata and controls
executable file
·238 lines (219 loc) · 7.42 KB
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
#!/usr/bin/python
def buildTree(bookmarks):
tree = []
groups = {}
for bookmark in bookmarks:
if bookmark["fold"] == "" or len(bookmark["fold"]) == 0:
tree.append(bookmark)
else:
group = bookmark["fold"][0].encode("utf8")
if (bookmark["fold"]) > 1:
bookmark["fold"] = bookmark["fold"][1:]
else:
bookmark["fold"] = ""
if groups.has_key(group):
groups[group].append(bookmark)
else:
groups[group] = [bookmark]
for name, group in groups.iteritems():
tree.append({"name": name, "tree": buildTree(group)})
return tree
def htmlizeTree(tree, base):
from BeautifulSoup import Tag, NavigableString
import cgi
elements = []
for branch in tree:
if branch.has_key("href"):
el = Tag(base, "A")
for attrib in ("href", "add_date", "icon"):
el[attrib] = branch[attrib]
else:
el = Tag(base, "H3")
try:
el.insert(0, NavigableString(branch["name"]))
except:
el.insert(0, NavigableString("[can not convert]"))
print "can not convert ", branch["name"]
dt = Tag(base, "DT")
dt.insert(0, el)
elements.append(dt)
if branch.has_key("tree"):
elements.append(htmlizeTree(branch["tree"], base))
dl = Tag(base, "DL")
for i, element in enumerate(elements):
dl.insert(i, element)
dd = Tag(base, "DD")
dd.insert(0, dl)
return dd
def writeBookmarks(filename, bookmarks):
from BeautifulSoup import BeautifulSoup
for bookmark in bookmarks:
bookmark["fold"] = bookmark["fold"].split("/")
if bookmark["fold"][0] == "Andere Lesezeichen":
bookmark["fold"] = bookmark["fold"][1:]
tree = buildTree(bookmarks)
page = BeautifulSoup()
bookmarkFile = open(filename, "w")
bookmarkFile.write('''<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>''')
dd = htmlizeTree(tree, page)
bookmarkFile.write(dd.prettify())
bookmarkFile.close()
def getParentName(p):
p = p.parent
if p is None or p.name == u'document':
return ()
while p.name != "dt":
p = p.parent
if p is None or p.name == u'document':
return ()
names = getParentName(p)
name = p.find("h3")
if name is not None:
names += (name.contents[0], )
return names
def getAttribute(self, attribute):
if self.has_key(attribute):
return self[attribute]
else:
return None
def getContent(self, num):
c = self.contents
if c is None:
return ""
if len(c) <= num:
return ""
return c[num]
def extractBookmarks(filename):
bms = []
bookmarkfile = open(filename, "r")
from BeautifulSoup import BeautifulSoup
for bookmark in BeautifulSoup(bookmarkfile).findAll("a"):
folder = getParentName(bookmark.parent)
if len(folder) == 0 or folder[0] != "Lesezeichenleiste":
folder = ("Andere Lesezeichen",) + folder
bms.append({
"name": getContent(bookmark, 0),
"href": getAttribute(bookmark, "href"),
"fold": "/".join(folder),
"add_date": getAttribute(bookmark, "add_date"),
"icon": getAttribute(bookmark, "icon"),
"srce": filename
})
bookmarkfile.close()
return bms
def values(self, keys):
v = []
for key in keys:
v.append(self[key])
return v
def csvWrite(filename, bookmarks, header):
import csv
csvfile = open(filename, "wb")
csv = csv.writer(csvfile, delimiter=";")
csv.writerow(header)
for bookmark in bookmarks:
csv.writerow(values(bookmark, header))
csvfile.close()
def cleanDoubles(bookmarks):
old = bookmarks[0]
new = [bookmarks[0]]
conflicts = []
for bookmark in bookmarks[1:]:
if bookmark["href"] != old["href"] or bookmark["name"] != old["name"] or bookmark["fold"] != old["fold"]:
new.append(bookmark)
old = bookmark
else:
if old["icon"] is None and bookmark["icon"] is not None:
new = new[:-1]
old["icon"] = bookmark["icon"]
new.append(old)
return new
def extractDifferentAttributes(attribName, bookmarks):
attributes = [bookmarks[0][attribName]]
for bookmark in bookmarks[1:]:
new = True
for attribute in attributes:
if bookmark[attribName] == attribute:
new = False
if new:
attributes.append(bookmark[attribName])
return attributes
def gruppiere(bookmarks):
groups = [[bookmarks[0]]]
for bookmark in bookmarks[1:]:
if bookmark["href"] == groups[-1][0]["href"]:
groups[-1].append(bookmark)
else:
groups.append([bookmark])
return groups
def nachfrage(auswahl, name):
for i, wahl in enumerate(auswahl):
print "%d) %s" % (i+1, wahl)
print "%d) [new entry]" % (i+2)
d = try_int(raw_input("Select a %s for that bookmark: " % name))
while d is None or d < 1 or d > i+2:
d = try_int(raw_input("Select a %s for that bookmark: " % name))
if d == i+2:
return raw_input("Enter new %s for that bookmark: " % name)
else:
return auswahl[i-1]
def merge(bookmarks):
bookmarks.sort(key=lambda x: x["href"])
groups = gruppiere(cleanDoubles(bookmarks))
bookmarks = []
for group in groups:
if len(group) > 1:
print "\nBookmark linking to %s (one name: %s)" % (group[0]["href"], group[0]["name"])
for attribName in ["name", "fold"]:
attribute = extractDifferentAttributes(attribName, group)
if len(attribute) > 1:
attribute = [nachfrage(attribute, attribName)]
group[0][attribName] = attribute[0]
bookmarks.append(group[0])
return bookmarks
def cleanNonsense(bookmark):
if bookmark["href"] is None:
return False
if bookmark["href"][0:len("http://")] == "http://" or \
bookmark["href"][0:len("https://")] == "https://" or \
bookmark["href"][0:len("javascript:")] == "javascript:":
return True
def try_int(string):
try:
return int(string)
except ValueError:
return None
def clearBookmarks(filename):
from BeautifulSoup import BeautifulSoup
page = open(filename, "r")
struct = BeautifulSoup(page)
page.close()
As = struct.findAll("a")
for A in As:
A["href"] = ""
A["icon"] = ""
page = open(filename + ".new", "w")
page.write(struct.prettify())
page.close()
def main():
divs = ("Arbeit", "Katja", "Paula", "Katja neu")
header = ["name", "href", "fold", "add_date", "icon", "srce"]
fn_base = "/home/ber/Dropbox/Lesezeichen %s"
fn_in = lambda i: fn_base % ("auf %s.html" % i)
fn_out = lambda i: fn_base % ("auf %s.csv" % i)
bms = []
for div in divs:
bm = extractBookmarks(fn_in(div))
csvWrite(fn_out(div), bm, header)
bms += bm
bms = filter(cleanNonsense, bms)
bms = merge(bms)
writeBookmarks(fn_base % "global.html", bms)
csvWrite(fn_base % "global.csv", bms, header)
main()