-
Notifications
You must be signed in to change notification settings - Fork 6
/
postNotes.js
78 lines (67 loc) · 2.44 KB
/
postNotes.js
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
// this web worker imports hypothesis annotations into zotero as child notes
// it adds a zotero tag to each imported note like 'hypothesis-BvFJGPmpRd-7d6g7_sOpFg'
// use hlib, not hlib2, because no web components in this environment
self.importScripts('https://jonudell.info/hlib/hlib.bundle.js')
self.importScripts('https://jonudell.info/hlib/showdown.js')
// import a hypothesis annnotation as a zotero child note
function importAnnotation(zoteroKey, zoteroUserId, zoteroApiKey, anno) {
const converter = new Showdown.converter()
const quote = anno.quote != '' ? `<blockquote>${anno.quote}</blockquote>` : ''
const body = converter.makeHtml(anno.text)
const html = `
<p>Hypothesis <a href="https://hyp.is/${anno.id}">annotation</a> by ${anno.user}</p>
${quote}
${body}`
// params for the zotero api call to create a hypothesis-derived child note
const tags = [ { tag: `hypothesis-${anno.id}` } ]
for (let tag of anno.tags) {
tags.push({ tag: tag })
}
const params = [
{
parentItem: zoteroKey,
itemType: 'note',
note: html,
tags: tags,
collections: [],
relations: {}
}
]
const zoteroApiCall = `https://www.zotero.org/api/users/${zoteroUserId}/items/`
const opts = {
method: 'post',
url: zoteroApiCall,
params: JSON.stringify(params),
headers: {
'Zotero-API-Key': `${zoteroApiKey}`
}
}
// call zotero api to import a hypothesis-derived child note
return hlib.httpRequest(opts)
}
function delaySeconds(seconds) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000))
}
// listen for a request to import one or more hypothesis annotations for a zotero item
self.addEventListener('message', e => {
const zoteroUserId = e.data.zoteroUserId
const zoteroApiKey = e.data.zoteroApiKey
const zoteroKey = e.data.annotationsToImport.key
const rows = e.data.annotationsToImport.hypothesisAnnos
processRows(rows)
async function processRows(rows) {
for (let i = 0; i < rows.length; i++) {
await delaySeconds(.1)
const anno = hlib.parseAnnotation(rows[i])
const result = await(importAnnotation(zoteroKey, zoteroUserId, zoteroApiKey, anno))
const user = `${anno.user}`.replace('acct:', '').replace('@hypothes.is', '')
self.postMessage(
`imported <a class="url" target="_anno" href="https://hypothes.is/a/${anno.id}">${anno.id}</a>
by ${user} on ${anno.url}`
)
self.postMessage({
zoteroKey: zoteroKey // echo back the zotero key so caller can track progress
})
}
}
})