-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.ts
73 lines (58 loc) · 2.16 KB
/
lib.ts
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
declare const Zotero: any
declare const Components: any
const {
// classes: Cc,
// interfaces: Ci,
utils: Cu,
} = Components
if (Zotero.platformMajorVersion < 102) {
Cu.importGlobalProperties(['fetch', 'URL'])
}
Zotero.DateFromLastModified = new class {
private notifierID: number
log(msg) {
Zotero.debug(`DFLM: ${msg}`)
}
install() {
this.notifierID = Zotero.Notifier.registerObserver(this, ['item'])
}
async update(id: number) {
const item = await Zotero.Items.getAsync(id)
if (item.isFeedItem || !item.isRegularItem()) return
const types = (Zotero.Prefs.get('date-from-last-modified.itemtypes') || '').trim().toLowerCase().split(/\s*,\s*/)
if (types.length && !types.includes(Zotero.ItemTypes.getName(item.itemTypID))) return
const url: string = item.getField('url', false, true)
const date: string = item.getField('date', false, true)
this.log(JSON.stringify({ url, date }))
if (!url || date) return
this.log(`getting lastModified from ${url}`)
const result = await fetch(url)
const lastModified = this.formatDate(new Date(result.headers.get('Last-Modified')))
this.log(`lastModified=${lastModified}`)
const today = this.formatDate(new Date())
if (lastModified && lastModified !== today && lastModified !== '1970-1-1') {
item.setField('date', lastModified)
this.log(`setting ${item.itemID} ${lastModified}`)
await item.saveTx()
}
}
uninstall() {
Zotero.Notifier.unregisterObserver(this.notifierID)
}
public notify(event: string, type: string, ids: number[], _extraData) {
this.log(JSON.stringify({ event, type, ids }))
if (event !== 'add' && event !== 'modify') return
for (const id of ids) {
void this.update(id)
}
}
private formatDate(date: Date) {
// if (!(date instanceof Date) || isNaN(date)) return ''
if (!(date instanceof Date)) return ''
const year = date.getFullYear()
if (typeof year === 'undefined') return ''
const formatted = date.toISOString().replace(/T.*/, '')
if (formatted === '1970-01-01' || formatted === (new Date).toISOString().replace(/T.*/, '')) return ''
return formatted.replace(/-0/g, '-')
}
}