-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathlib.ts
More file actions
341 lines (300 loc) · 10.7 KB
/
lib.ts
File metadata and controls
341 lines (300 loc) · 10.7 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
import { IZotero } from './typings/global'
declare const Zotero: IZotero
declare const Components: any
import { debug } from './client/content/debug'
import { htmlencode, plaintext, getField, getDOI, isShortDoi, isZotero7 } from './client/content/util'
import { PLUGIN_ENABLED } from './client/content/config'
import { sciteColumnsZotero7 } from './client/content/columns'
import { sciteItemPaneZotero7 } from './client/content/itemPane'
interface Tallies {
doi: string
contrasting: number // NOTE: The API returns contradicting, we map this manually
mentioning: number
supporting: number
total: number
unclassified: number
citingPublications: number
}
const shortToLongDOIMap = {}
const longToShortDOIMap = {}
const MAX_DOI_BATCH_SIZE = 500 // tslint:disable-line:no-magic-numbers
async function getLongDoi(shortDoi) {
try {
if (!shortDoi) {
return ''
}
// If it starts with 10/, it is short
// otherwise, treat it as long and just return
shortDoi = shortDoi.toLowerCase().trim()
if (!isShortDoi(shortDoi)) {
// This is probably a long DOI then!
return shortDoi
}
if (shortDoi in shortToLongDOIMap) {
debug(`shortToLongDOIMap cache hit ${shortDoi}`)
return shortToLongDOIMap[shortDoi]
}
const res = await Zotero.HTTP.request('GET', `https://doi.org/api/handles/${shortDoi}`)
const doiRes = res?.response ? JSON.parse(res.response).values : []
const longDoi = (doiRes && doiRes.length && doiRes.length > 1) ? doiRes[1].data.value.toLowerCase().trim() : ''
if (!longDoi) {
debug(`Unable to resolve shortDoi ${shortDoi} to longDoi`)
// I guess just return the shortDoi for now...?
return shortDoi
}
// Use these to minimize API calls and easily go back and forth
shortToLongDOIMap[shortDoi] = longDoi
longToShortDOIMap[longDoi] = shortDoi
debug(`Converted shortDoi (${shortDoi}) to longDoi (${longDoi})`)
return longDoi
}
catch (err) {
Zotero.logError(`ERR_getLongDoi(${shortDoi}): ${err}`)
return shortDoi
}
}
const ready = Zotero.Promise.defer()
export class CScite {
public ready: any = ready.promise
public isReady: boolean = false // Track ready state with a boolean since native Promises don't have isPending()
public tallies: { [DOI: string]: Tallies } = {}
public uninstalled: boolean = false
private bundle: any
private started = false
private notifierID: number | null = null
constructor() {
this.bundle = Components.classes['@mozilla.org/intl/stringbundle;1'].getService(Components.interfaces.nsIStringBundleService).createBundle('chrome://zotero-scite/locale/zotero-scite.properties')
}
public async start(rootURI: string = '') {
if (!PLUGIN_ENABLED) {
Zotero.logError('Scite Zotero plugin is disabled. Aborting!')
return
}
if (!isZotero7) {
Zotero.logError('This version of the scite plugin only supports Zotero 7 and after, please upgrade or use an older XPI')
return
}
if (this.started) return
this.started = true
const columns = sciteColumnsZotero7.map(column => {
const iconPath = column.iconPath ? rootURI + column.iconPath : null
return {
...column,
iconPath,
htmlLabel: iconPath
? `<span><img src="${iconPath}" height="10px" width="9px" style="margin-right: 5px;"/> ${column.label}</span>`
: column.label,
}
})
for (const column of columns) {
await Zotero.ItemTreeManager.registerColumns(column)
}
Zotero.debug('[Scite Zotero] Registered columns')
const updatedSciteItemPaneZotero7 = {
...sciteItemPaneZotero7,
header: {
...sciteItemPaneZotero7.header,
icon: sciteItemPaneZotero7.header.icon ? rootURI + sciteItemPaneZotero7.header.icon : null,
},
sidenav: {
...sciteItemPaneZotero7.sidenav,
icon: sciteItemPaneZotero7.sidenav.icon ? rootURI + sciteItemPaneZotero7.sidenav.icon : null,
},
}
const registeredID = Zotero.ItemPaneManager.registerSection(updatedSciteItemPaneZotero7)
Zotero.debug(`[Scite Zotero] Registered Scite section: ${registeredID}`)
await Zotero.Schema.schemaUpdatePromise
await this.refresh()
this.isReady = true
ready.resolve(true)
this.notifierID = Zotero.Notifier.registerObserver(this, ['item'], 'Scite', 1)
// Refresh the item tree to show the loaded data
this.refreshItemTree()
}
public async unload() {
if (this.notifierID) {
Zotero.Notifier.unregisterObserver(this.notifierID)
this.notifierID = null
}
}
private refreshItemTree() {
try {
// Trigger a refresh notification to re-render columns with new data
Zotero.Notifier.trigger('refresh', 'itemtree', [])
Zotero.debug('[Scite Zotero] Triggered item tree refresh')
}
catch (err) {
Zotero.debug(`[Scite Zotero] Error refreshing item tree: ${err}`)
}
}
public getString(name, params = {}, html = false) {
if (!this.bundle || typeof this.bundle.GetStringFromName !== 'function') {
Zotero.logError(`Scite.getString(${name}): getString called before strings were loaded`)
return name
}
let template = name
try {
template = this.bundle.GetStringFromName(name)
}
catch (err) {
Zotero.logError(`Scite.getString(${name}): ${err}`)
}
const encode = html ? htmlencode : plaintext
return template.replace(/{{(.*?)}}/g, (match, param) => encode(params[param] || ''))
}
public async viewSciteReport(doi) {
try {
if (isShortDoi(doi)) {
doi = await getLongDoi(doi)
}
const zoteroPane = Zotero.getActiveZoteroPane()
zoteroPane.loadURI(`https://scite.ai/reports/${doi}`)
}
catch (err) {
Zotero.logError(`Scite.viewSciteReport(${doi}): ${err}`)
alert(err)
}
}
public async refreshTallies(doi) {
try {
if (isShortDoi(doi)) {
doi = await getLongDoi(doi)
}
const data = await Zotero.HTTP.request('GET', `https://api.scite.ai/tallies/${doi.toLowerCase().trim()}`)
const tallies = data?.response
if (!tallies) {
Zotero.logError(`Scite.refreshTallies: No tallies found for: (${doi})`)
return {}
}
const tallyData = JSON.parse(tallies)
this.tallies[doi] = {
...tallyData,
contrasting: tallyData.contradicting,
}
// Also set it for the short DOI equivalent
const shortDoi = longToShortDOIMap[doi]
if (shortDoi) {
this.tallies[shortDoi] = {
...tallyData,
contrasting: tallyData.contradicting,
}
}
return tallyData
}
catch (err) {
Zotero.logError(`Scite.refreshTallies(${doi}): ${err}`)
alert(err)
}
}
public async bulkRefreshDois(doisToFetch) {
if (!doisToFetch) {
return
}
try {
Zotero.debug(`[Scite Zotero] Fetching tallies for ${doisToFetch.length} DOIs from API...`)
const res = await Zotero.HTTP.request('POST', 'https://api.scite.ai/tallies', {
body: JSON.stringify(doisToFetch.map(doi => doi.toLowerCase().trim())),
responseType: 'json',
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})
Zotero.debug(`[Scite Zotero] API response received`)
const doiTallies = res?.response ? res.response.tallies : {}
Zotero.debug(`[Scite Zotero] Got tallies for ${Object.keys(doiTallies).length} DOIs`)
for (const doi of Object.keys(doiTallies)) {
debug(`scite bulk DOI refresh: ${doi}`)
const tallies = doiTallies[doi]
this.tallies[doi] = {
...tallies,
contrasting: tallies.contradicting,
}
// Also set it for the short DOI equivalent if present
const shortDoi = longToShortDOIMap[doi]
if (shortDoi) {
this.tallies[shortDoi] = {
...tallies,
contrasting: tallies.contradicting,
}
}
}
// Refresh the item tree to show the new data
this.refreshItemTree()
}
catch (err) {
Zotero.logError(`[Scite Zotero] bulkRefreshDois error getting ${doisToFetch.length || 0} DOIs: ${err}`)
}
}
public async get(dois, options: { refresh?: boolean } = {}) {
let doisToFetch = options.refresh ? dois : dois.filter(doi => !this.tallies[doi])
doisToFetch = await Promise.all(doisToFetch.map(async doi => {
const longDoi = await getLongDoi(doi)
return longDoi
}))
const numDois = doisToFetch.length
if (!numDois) {
return
}
if (numDois <= MAX_DOI_BATCH_SIZE) {
await this.bulkRefreshDois(doisToFetch)
}
else {
// Do them in chunks of MAX_DOI_BATCH_SIZE due to server limits
const chunks = []
let i = 0
while (i < numDois) {
chunks.push(doisToFetch.slice(i, i += MAX_DOI_BATCH_SIZE))
}
// Properly wait for each chunk to finish before returning!
await chunks.reduce(async (promise, chunk) => {
await promise
await this.bulkRefreshDois(chunk)
}, Promise.resolve())
}
return dois.map(doi => this.tallies[doi])
}
private async refresh() {
try {
Zotero.debug('[Scite Zotero] Starting refresh...')
const query = `
SELECT DISTINCT fields.fieldName, itemDataValues.value
FROM fields
JOIN itemData on fields.fieldID = itemData.fieldID
JOIN itemDataValues on itemData.valueID = itemDataValues.valueID
WHERE fieldname IN ('extra', 'DOI')
`.replace(/[\s\n]+/g, ' ').trim()
let dois = []
// eslint-disable-next-line
for (const doi of await Zotero.DB.queryAsync(query)) {
switch (doi.fieldName) {
case 'extra':
dois = dois.concat(doi.value.split('\n').map(line => line.match(/^DOI:\s*(.+)/i)).filter(line => line).map(line => line[1].trim()))
break
case 'DOI':
dois.push(doi.value)
break
}
}
Zotero.debug(`[Scite Zotero] Found ${dois.length} DOIs to refresh`)
await this.get(dois, { refresh: true })
Zotero.debug('[Scite Zotero] Refresh complete')
setTimeout(this.refresh.bind(this), 24 * 60 * 60 * 1000) // eslint-disable-line no-magic-numbers
}
catch (err) {
Zotero.logError('[Scite Zotero] Unexpected error refreshing tallies')
Zotero.logError(err)
throw err
}
}
protected async notify(action, type, ids, extraData) {
if (type !== 'item' || (action !== 'modify' && action !== 'add')) return
const dois = []
for (const item of (await Zotero.Items.getAsync(ids))) {
const doi = getDOI(getField(item, 'DOI'), getField(item, 'extra'))
if (doi && !dois.includes(doi)) dois.push(doi)
}
// this list of dois can include a mix of short and long
if (dois.length) await this.get(dois)
}
}
if (!Zotero.Scite) {
Zotero.Scite = (new CScite)
}