-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
372 lines (300 loc) · 10.9 KB
/
background.js
File metadata and controls
372 lines (300 loc) · 10.9 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// if (!window.hasOwnProperty('browser')) {
// window.browser = window.chrome
// }
const cache = {}
function pick(object, ...props) {
return props.reduce((result, prop) => {
result[prop] = object[prop]
return result
}, {})
}
class PinboardClient {
constructor(pinboard_access_token) {
this.pinboard_access_token = pinboard_access_token
}
async posts() {
return this.getJson(this.apiUrl('posts/all'))
}
async getPost(url) {
if (!url) {
console.log('getPost', 'skipping empty url')
return
}
return (await this.getJson(`${this.apiUrl('posts/get')}&url=${encodeURIComponent(url)}`)).posts[0]
}
async addPost(params) {
let url = this.apiUrl('posts/add')
for (const param in params) {
if (params[param]) {
url += `&${param}=${encodeURIComponent(params[param])}`
}
}
return this.getJson(url)
}
async deletePost(url) {
if (!url) {
console.log('deletePost', 'skipping empty url')
return
}
return this.getJson(`${this.apiUrl('posts/delete')}&url=${encodeURIComponent(url)}`)
}
async renameTag({from, to}) {
if (!from) {
console.log('renameTag', 'skipping empty from:')
return
}
const url = this.apiUrl('tags/rename')
return this.getJson(`${url}&old=${encodeURIComponent(from)}&new=${encodeURIComponent(to)}`)
}
apiUrl(action) {
return `https://api.pinboard.in/v1/${action}?auth_token=${this.pinboard_access_token}&format=json`
}
async getJson(url) {
return this.enqueue(() => getJson(url))
}
// Pinboard API is really slow - queue requests to avoid race conditions
async enqueue(fn) {
if (this.queue) {
this.queue = this.queue.finally(() => this.enqueue(fn))
} else {
this.queue = fn().finally(() => delete this.queue)
}
return this.queue
}
}
async function ensureFirefoxUpdatedNewFolderTitle(folder) {
return new Promise((resolve, reject) => {
const i = setInterval(() => {
browser.bookmarks.get(folder.id).then(([freshFolder]) => {
console.log('freshFolder.title', freshFolder.title)
if (freshFolder.title !== 'New Folder') {
clearInterval(i)
clearTimeout(t)
resolve(freshFolder)
}
})
}, 100)
const t = setTimeout(() => {
console.log('ensureFirefoxUpdatedNewFolderTitle', 'timed out')
clearInterval(i)
resolve(folder)
}, 20000)
})
}
async function isInPinboardFolder(id) {
const [item] = await browser.bookmarks.get(id)
if (!item.parentId) {
return false
}
const [parent] = await browser.bookmarks.get(item.parentId)
if (parent.title === 'Pinboard') {
return true
}
return isInPinboardFolder(parent.id)
}
async function createBrowserBookmarkOrFolder({url, title, parentId}) {
const bookmarkOrFolder = await browser.bookmarks.create({parentId, title, url})
cache[bookmarkOrFolder.id] = bookmarkOrFolder
return bookmarkOrFolder
}
async function getAccessToken() {
return await browser.storage.sync.get("pinboard_access_token")
}
async function getJson(url) {
const response = await fetch(url)
return await response.json()
}
async function ensureEmptyPinboardFolder() {
const bookmarks = await browser.bookmarks.getTree()
const otherBookmarksFolder = bookmarks[0].children.find(b => b.id === 'unfiled_____')
const pinboardFolder = otherBookmarksFolder.children.find(b => b.title === 'Pinboard')
if (pinboardFolder) {
await Promise.all(
pinboardFolder.children.map(
node => browser.bookmarks.removeTree(node.id)
)
)
return pinboardFolder
}
return createBrowserBookmarkOrFolder({
title: 'Pinboard'
})
}
const ensureFolder = async (name, parentId) => {
const [parent] = await browser.bookmarks.getSubTree(parentId)
const existingFolder = parent.children.find(b => b.title === name && b.type === 'folder')
if (existingFolder) {
return existingFolder
}
return createBrowserBookmarkOrFolder({
parentId,
title: name,
})
}
(async () => {
async function updatePinboardBookmarkOrTag(id) {
if (!(await isInPinboardFolder(id))) return
const oldVersion = cache[id]
if (!oldVersion) return
const [bookmarkOrTag] = await browser.bookmarks.get(id)
console.log('updatePinboardBookmarkOrTag', {bookmarkOrTag, oldVersion})
if (bookmarkOrTag.type === 'folder') {
await pinboardClient.renameTag({from: oldVersion.title, to: bookmarkOrTag.title})
} else if (bookmarkOrTag.title !== oldVersion.title || bookmarkOrTag.url !== oldVersion.url) {
const pinboardBookmark = await pinboardClient.getPost(oldVersion.url)
if (!pinboardBookmark) {
console.log(`Pinboard bookmark not found: ${oldVersion.url}`)
delete cache[id]
return
}
const postParams = Object.assign(
{
url: bookmarkOrTag.url,
description: bookmarkOrTag.title,
dt: pinboardBookmark.time,
},
pick(pinboardBookmark, 'tags', 'extended', 'shared', 'toread')
)
await pinboardClient.addPost(postParams)
if (oldVersion.url && bookmarkOrTag.url !== oldVersion.url) {
oldVersion.pinboardBookmark = pinboardBookmark
await removePinboardBookmarkOrTag(id, {node: oldVersion})
}
}
cache[id] = bookmarkOrTag
}
async function updatePinboardBookmarkTags(id, {parentId, oldParentId}) {
if (!(await isInPinboardFolder(id))) return
const [bookmark] = await browser.bookmarks.get(id)
console.log('updateTag', {bookmark, parentId, oldParentId})
if (!bookmark.url) {
console.log('Skipping folder')
return
}
let pinboardBookmark = await pinboardClient.getPost(bookmark.url)
console.log('pinboardBookmark', pinboardBookmark)
if (!pinboardBookmark) {
pinboardBookmark = {
url: bookmark.url,
description: bookmark.title,
tags: ''
}
} else {
let [newParentFolder] = await browser.bookmarks.get(parentId)
const [oldParentFolder] = await browser.bookmarks.get(oldParentId)
console.log({newParentFolder, oldParentFolder})
const [newRootFolder] = await browser.bookmarks.get(newParentFolder.parentId)
const [oldRootFolder] = await browser.bookmarks.get(oldParentFolder.parentId)
console.log({newRootFolder, oldRootFolder})
const isNewRootChild = newRootFolder?.title === 'Pinboard'
const isOldRootChild = oldRootFolder?.title === 'Pinboard'
// If user creates new folder, then here we see 'New Folder' as opposed to the name
// user has given it.
if (newParentFolder.title === 'New Folder') {
newParentFolder = await ensureFirefoxUpdatedNewFolderTitle(newParentFolder)
}
const tagToAdd = isNewRootChild && newParentFolder.title != 'New Folder' ? newParentFolder.title : null
const tagToRemove = isOldRootChild ? oldParentFolder.title : null
const updatedTags = pinboardBookmark.tags
.split(' ')
.filter(t => t && t !== tagToRemove)
.concat(tagToAdd)
.filter(Boolean)
.join(' ')
if (updatedTags === pinboardBookmark.tags) return
pinboardBookmark.tags = updatedTags
pinboardBookmark.url = pinboardBookmark.href
}
await pinboardClient.addPost(pinboardBookmark)
}
/*
"{
\"id\": \"gzO74eOYa1rJ\",
\"parentId\": \"toolbar_____\",
\"index\": 4,
\"title\": \"BEST METAL & PROG ROCK ALBUMS OF 2021 | METALISED!\",
\"dateAdded\": 1643660290019,
\"type\": \"bookmark\",
\"url\": \"https://metalised.wordpress.com/2022/01/17/best-metal-prog-rock-albums-of-2021/\"
}"
*/
async function createPinboardBookmark(id, {title, url, parentId}) {
// Don't create folders
if (!url) return
if (!(await isInPinboardFolder(id))) return
console.log('createPinboardBookmark', {title, url, parentId})
const existingPinboardBookmark = await pinboardClient.getPost(url)
const tags = []
if (existingPinboardBookmark) {
tags.concat(existingPinboardBookmark.tags.split(' ').filter(Boolean))
}
const [parentFolder] = await browser.bookmarks.get(parentId)
const [rootFolder] = await browser.bookmarks.get(parentFolder.parentId)
const isParentInPinboardFilder = rootFolder?.title === 'Pinboard'
if (isParentInPinboardFilder) {
tags.concat(parentFolder.title)
}
await pinboardClient.addPost({
url,
description: title,
tags: tags.filter(Boolean).join(' ')
})
cache[id] = (await browser.bookmarks.get(id))[0]
}
async function removePinboardBookmarkOrTag(id, {node: {url, parentId, pinboardBookmark}}) {
const [parent] = await browser.bookmarks.get(parentId)
if (parent.title !== 'Pinboard' && !(await isInPinboardFolder(parentId))) {
return
}
console.log('removePinboardBookmark', {id, url, pinboardBookmark})
if (!pinboardBookmark) {
pinboardBookmark = await pinboardClient.getPost(url)
console.log('pinboardBookmark', pinboardBookmark)
}
if (!pinboardBookmark) {
delete cache[id]
return
}
const browserTag = parent.title
const pinboardTags = pinboardBookmark.tags.split(' ').filter(Boolean)
if (pinboardTags.size > 1 && pinboardTags.includes(browserTag)) {
pinboardBookmark.tags = pinboardTags.filter(t => t !== browserTag).join(' ')
await pinboardClient.addPost(pinboardBookmark)
} else {
await pinboardClient.deletePost(url)
delete cache[id]
}
}
const {pinboard_access_token} = await getAccessToken()
const pinboardClient = new PinboardClient(pinboard_access_token)
const pinboardBookmarks = await pinboardClient.posts()
console.log('pinboardBookmarks', pinboardBookmarks)
const pinboardFolder = await ensureEmptyPinboardFolder()
for (const b of pinboardBookmarks) {
if (b.tags) {
await Promise.all(
b.tags.split(' ').filter(Boolean).map(async tag => {
const tagFolder = await ensureFolder(tag, pinboardFolder.id)
return createBrowserBookmarkOrFolder({
parentId: tagFolder.id,
url: b.href,
title: b.description,
})
})
)
} else {
await createBrowserBookmarkOrFolder({
parentId: pinboardFolder.id,
url: b.href,
title: b.description,
})
}
}
// In FF a bookmark is added right after the star button is pressed (before user presses Save button in the popup!)
// When a user finally presses Save, then, if they chose a folder, an `onMoved` event is fired.
// At that point, we know both the bookmark and the tag, so we can add it to pinboard.
browser.bookmarks.onCreated.addListener((...args) => createPinboardBookmark(...args).catch(console.error))
browser.bookmarks.onMoved.addListener((...args) => updatePinboardBookmarkTags(...args).catch(console.error))
browser.bookmarks.onChanged.addListener((...args) => updatePinboardBookmarkOrTag(...args).catch(console.error))
browser.bookmarks.onRemoved.addListener((...args) => removePinboardBookmarkOrTag(...args).catch(console.error))
})()