-
Notifications
You must be signed in to change notification settings - Fork 0
/
SafariBookmarkEditor
executable file
·243 lines (208 loc) · 6.97 KB
/
SafariBookmarkEditor
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
#!/usr/bin/python
import argparse
import os
import plistlib
import subprocess
import uuid
class SafariBookmarks(object):
"""
Creates a Safari bookmark instance in the context of the current user.
Attributes:
plist_path (str): Path to Bookmarks plist of current user.
plist (dict(dict, ..., dict)): XML of bookmarks dictionary parsed into plist.
titles (list(str, ..., str)): List of titles of current bookmarks.
bookmarks (list(dict, ..., dict)): Reference to bookmarks entry of parsed plist dictionary.
"""
def __init__(self):
self.plist_path = self.get()
self.plist = dict()
self.titles = list()
self.bookmarks = list()
self.read()
def get(self):
"""
Checks to see Bookmarks plist exists and has correct form.
If either of these conditions aren't met replaces existing plist with new empty one.
Returns:
Expanded path to ~/Library/Safari/Bookmarks.plist
"""
plist_path = os.path.expanduser('~/Library/Safari/Bookmarks.plist')
if not os.path.isfile(plist_path):
print "Bookmarks.plist doesn't appear to exist."
print "Generating new Bookmarks.plist."
self.generate(plist_path)
return plist_path
def generate(self, plist_path):
"""
Generates a boilerplate Safari Bookmarks plist at plist path.
Raises:
CalledProcessError if creation of plist fails.
"""
subprocess.check_call(["touch", plist_path])
contents = dict(
Children=list((
dict(
Title="History",
WebBookmarkIdentifier="History",
WebBookmarkType="WebBookmarkTypeProxy",
WebBookmarkUUID=str(uuid.uuid5(uuid.NAMESPACE_DNS, "History")),
),
dict(
Children=list(),
Title="BookmarksBar",
WebBookmarkType="WebBookmarkTypeList",
WebBookmarkUUID=str(uuid.uuid5(uuid.NAMESPACE_DNS, "BookmarksBar")),
),
dict(
Title="BookmarksMenu",
WebBookmarkType="WebBookmarkTypeList",
WebBookmarkUUID=str(uuid.uuid5(uuid.NAMESPACE_DNS, "BookmarksMenu")),
),
)),
Title="",
WebBookmarkFileVersion=1,
WebBookmarkType="WebBookmarkTypeList",
WebBookmarkUUID=str(uuid.uuid5(uuid.NAMESPACE_DNS, "")),
)
plistlib.writePlist(contents, plist_path)
def read(self):
"""
Parses plist into dictionary. Creates a new empty bookmarks plist if plist can't be read.
Returns:
Dictionary containing info parsed from bookmarks plist.
"""
subprocess.call(['plutil', '-convert', 'xml1', self.plist_path])
try:
pl = plistlib.readPlist(self.plist_path)
except:
print "Bookmarks.plist appears to be corrupted."
print "Generating new Bookmarks.plist."
self.generate() # if plist can't be read generate new empty one.
pl = plistlib.readPlist(self.plist_path)
self.plist = pl
self.bookmarks = self.plist['Children'][1]['Children']
self.titles = [bm["URIDictionary"]["title"] for bm in self.bookmarks if bm.get("URIDictionary") is not None]
def add(self, title, url, index=-1):
"""
Adds a bookmark to plist dictionary.
Args:
title (str): Title to label bookmark with.
url (str): Url to bookmark.
"""
if title in self.titles:
print "Warning: Found preexisting bookmark with title %s, skipping." % (title)
return
if title in self.titles:
return
if index == -1 or index > len(self.bookmarks):
index = len(self.bookmarks)
elif index < -1:
index = 0
bookmark = dict(
WebBookmarkType='WebBookmarkTypeLeaf',
WebBookmarkUUID=str(uuid.uuid5(uuid.NAMESPACE_DNS, title)),
URLString=url,
URIDictionary=dict(
title=title
),
)
self.bookmarks.insert(index, bookmark)
self.titles.append(title)
def remove(self, title):
"""
Removes bookmark identified by title from plist dictionary if found.
Args:
title (str): Title bookmark is identified by.
"""
if title not in self.titles:
return
for bookmark in self.bookmarks:
if bookmark.get("URIDictionary") and bookmark["URIDictionary"]["title"] == title:
self.titles.remove(title)
self.bookmarks.remove(bookmark)
return
def removeAll(self):
"""
Removes all bookmarks from the plist dictionary.
"""
# Remove bookmarks in reveresed order to avoid shifting issues
for bookmark in reversed(self.bookmarks):
self.bookmarks.remove(bookmark)
self.titles = list()
def move(self, title, index):
"""
Moves bookmark identified by title to specified index in order of bookmarks if found.
Args:
title (str): Title bookmark is identified by.
index (int): Index to move bookmark to.
"""
if title not in self.titles:
return
if index > len(self.bookmarks) or index == -1:
index = len(self.bookmarks)
elif index < -1:
index = 0
for bookmark in self.bookmarks:
if bookmark.get('URIDictionary') and bookmark['URIDictionary']['title'] == title:
to_mv = bookmark
break
self.bookmarks.remove(to_mv)
self.bookmarks.insert(index, to_mv)
def swap(self, title1, title2):
"""
Swaps position of bookmark identified by title1 with bookmark identified by title2 if both are found.
Args:
title1 (str): Title 1st bookmark is identified by.
title2 (str): Title 2nd bookmark is identified by.
"""
if (title1 not in self.titles) or (title2 not in self.titles) or (title1 == title2):
return
for index, bookmark in enumerate(self.bookmarks):
if bookmark.get('URIDictionary') and bookmark['URIDictionary']['title'] == title1:
index1 = index
bookmark1 = bookmark
if bookmark.get('URIDictionary') and bookmark['URIDictionary']['title'] == title2:
index2 = index
bookmark2 = bookmark
self.bookmarks[index1] = bookmark2
self.bookmarks[index2] = bookmark1
def write(self):
"""
Writes modified plist dictionary to bookmarks plist and converts to binary format.
"""
plistlib.writePlist(self.plist, self.plist_path)
subprocess.call(['plutil', '-convert', 'binary1', self.plist_path])
def getIndex(self, title):
if title not in self.titles:
return None
for index, bm in enumerate(self.bookmarks):
if bm.get("URIDictionary") is None:
continue
bm_title = bm["URIDictionary"]["title"]
if bm_title == title:
return index
def main():
parser = argparse.ArgumentParser(
description='Command line tool for adding and removing Safari bookmarks in the context of the currently logged in user.',
)
parser.add_argument('--add', metavar='title::url', type=str, nargs='+',
help='double-colon seperated title and url of bookmark(s) to add in IE: --add MyWebsite::http://www.mywebsite.com MyOtherWebsite::http://www.myotherwebsite.com',
)
parser.add_argument('--remove', metavar='title', type=str, nargs='+',
help='title(s) of bookmark(s) to remove IE: --remove MyWebsite MyOtherWebsite',
)
parser.add_argument('--removeall', action='store_true', help='remove all current bookmarks')
args = parser.parse_args()
bookmarks = SafariBookmarks()
if args.removeall:
bookmarks.removeAll()
if args.remove:
for title in args.remove:
bookmarks.remove(title)
if args.add:
for bookmark in args.add:
title, url = bookmark.split('::')
bookmarks.add(title, url)
bookmarks.write()
if __name__ == "__main__":
main()