-
Notifications
You must be signed in to change notification settings - Fork 5
/
debug-log.ts
237 lines (198 loc) · 8.63 KB
/
debug-log.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
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
/* eslint-disable no-magic-numbers */
type ZoteroPane = {
getSelectedItems: () => any[]
}
declare const Zotero: {
platformMajorVersion: number
debug: (msg: string) => void
DebugLogSender: {
plugins: Record<string, string[]>
}
Translate: any
Prefs: {
get: (name: string, global?: boolean) => string | number | boolean
}
getInstalledExtensions: () => Promise<string[]>
platform: string
oscpu: string
locale: string
Utilities: {
generateObjectKey: () => string
}
Debug: {
enabled: boolean
getConsoleViewerOutput: () => string[]
}
getErrors: (something: boolean) => string[]
Schema: {
schemaUpdatePromise: Promise<void>
}
getActiveZoteroPane: () => ZoteroPane
getMainWindow(): Window
}
type ExportTranslator = {
setHandler: (phase: string, handler: (obj: { string: string }, success: boolean) => void) => void // eslint-disable-line id-blacklist
setTranslator: (id: string) => void
setItems: (items: any[]) => void
translate: () => void
}
declare const Components: any
declare const Services: any
import * as UZip from 'uzip'
type FileIO = {
success: boolean
key: string
link: string
}
class DebugLogSender {
public id = {
menu: 'debug-log-sender-menu',
menupopup: 'debug-log-sender-menupopup',
menuitem: 'debug-log-sender',
}
public debugEnabledAtStart: boolean = Zotero ? (Zotero.Prefs.get('debug.store') || Zotero.Debug.enabled) as unknown as boolean : null
public convertLegacy() {
if (!Zotero.DebugLogSender) return
const plugins = Zotero.DebugLogSender.plugins || {}
delete Zotero.DebugLogSender
const doc = Zotero.getMainWindow().document
doc.querySelector('menuitem#debug-log-menu')?.remove()
for (const [plugin, preferences] of Object.entries(plugins)) {
this.register(plugin, preferences)
}
}
private element(name: string, attrs: Record<string, string> = {}): HTMLElement {
const doc = Zotero.getMainWindow().document
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
const elt: HTMLElement = doc[Zotero.platformMajorVersion >= 102 ? 'createXULElement' : 'createElement'](name)
for (const [k, v] of Object.entries(attrs)) {
elt.setAttribute(k, v)
}
return elt
}
public register(plugin: string, preferences: string[] = []): void {
this.convertLegacy()
const doc = Zotero.getMainWindow().document
let menupopup = doc.querySelector(`#${this.id.menupopup}`)
if (!menupopup) {
menupopup = doc.querySelector('menupopup#menu_HelpPopup')
.appendChild(this.element('menu', { id: this.id.menu, label: 'Send debug log to file.io' }))
.appendChild(this.element('menupopup', { id: this.id.menupopup }))
}
doc.querySelector(`.${this.id.menuitem}[label=${JSON.stringify(plugin)}]`)?.remove()
const menuitem = menupopup.appendChild(this.element('menuitem', {
label: plugin,
class: this.id.menuitem,
'data-preferences': JSON.stringify(preferences || []),
}))
menuitem.addEventListener('command', event => this.send(event.currentTarget))
}
public unregister(plugin: string): void {
const doc = Zotero.getMainWindow().document
doc.querySelector(`.debug-log-sender[label=${JSON.stringify(plugin)}]`)?.remove()
const menupopup = doc.querySelector('#debug-log-sender-menupopup')
if (menupopup && !menupopup.children.length) doc.querySelector('#debug-log-sender-menu')?.remove()
}
private alert(title, body) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const ps = Zotero.platformMajorVersion >= 102
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
? Services.prompt
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
: Components.classes['@mozilla.org/embedcomp/prompt-service;1'].getService(Components.interfaces.nsIPromptService)
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
ps.alert(null, title, body)
}
public send(target: EventTarget): void {
const elt: HTMLElement = target as unknown as HTMLElement
const plugin: string = elt.getAttribute('label')
const preferences: string[] = JSON.parse(elt.getAttribute('data-preferences')) as string[]
this.sendAsync(plugin, preferences).catch((err: Error) => {
this.alert('Debug log submission error', `${err}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions
})
}
private async sendAsync(plugin: string, preferences: string[]) {
await Zotero.Schema.schemaUpdatePromise
const files: Record<string, Uint8Array> = {}
const enc = new TextEncoder()
const key: string = Zotero.Utilities.generateObjectKey()
const log = [
await this.info(preferences),
Zotero.getErrors(true).join('\n\n'),
Zotero.Debug.getConsoleViewerOutput().slice(-250000).join('\n'), // eslint-disable-line no-magic-numbers
].filter((txt: string) => txt).join('\n\n').trim()
files[`${key}/debug.txt`] = enc.encode(log)
const rdf = await this.rdf()
if (rdf) files[`${key}/items.rdf`] = enc.encode(rdf)
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
const zip = new Uint8Array(UZip.encode(files) as ArrayBuffer)
const blob = new Blob([zip], { type: 'application/zip'})
const formData = new FormData()
formData.append('file', blob, `${key}.zip`)
const response = await this.post('https://file.io', formData)
this.alert(`Debug log ID for ${plugin}`, `${key}-fio-${response.key}`)
}
private preferences(preferences: string[]): Record<string, string | number | boolean> {
const prefs: Record<string, string | number | boolean> = {}
const names: string[] = []
for (const pref of preferences) {
if (pref.endsWith('.')) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
const childkeys: string[] = Services.prefs.getBranch(pref).getChildList('', {})
for (const key of childkeys) {
names.push(pref + key)
}
}
else {
names.push(pref)
}
}
for (const pref of names.sort()) {
prefs[pref] = Zotero.Prefs.get(pref, true)
}
return prefs
}
private async post(url: string, data: FormData): Promise<FileIO> {
const response = await fetch(url, { method: 'POST', body: data })
return (await response.json()) as FileIO
}
// general state of Zotero
private async info(preferences: string[]): Promise<string> {
let info = ''
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
const appInfo: { name: string; version: string } = Components.classes['@mozilla.org/xre/app-info;1'].getService(Components.interfaces.nsIXULAppInfo)
info += `Application: ${appInfo.name} ${appInfo.version} ${Zotero.locale}\n`
info += `Platform: ${Zotero.platform} ${Zotero.oscpu}\n`
const addons: string[] = await Zotero.getInstalledExtensions()
if (addons.length) {
info += 'Addons:\n' + addons.map((addon: string) => ` ${addon}\n`).join('') // eslint-disable-line prefer-template
}
info += `Debug logging on at Zotero start: ${this.debugEnabledAtStart}\n`
info += `Debug logging on at log submit: ${Zotero.Prefs.get('debug.store') || Zotero.Debug.enabled}\n`
for (const [pref, value] of Object.entries(this.preferences(preferences))) {
info += `${pref} = ${JSON.stringify(value)}\n`
}
return info
}
private rdf(): Promise<string> {
return new Promise((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
const items: any[] = Zotero.getActiveZoteroPane().getSelectedItems()
if (items.length === 0) return resolve('')
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
const translation: ExportTranslator = new Zotero.Translate.Export() as ExportTranslator
translation.setItems(items)
translation.setTranslator('14763d24-8ba0-45df-8f52-b8d1108e7ac9') // rdf
translation.setHandler('done', (obj, success) => {
if (success) {
resolve(obj ? obj.string : undefined)
}
else {
reject('translation failed')
}
})
translation.translate() // eslint-disable-line @typescript-eslint/no-unsafe-call
})
}
}
export const DebugLog = new DebugLogSender