-
Notifications
You must be signed in to change notification settings - Fork 117
/
zotero.js
353 lines (311 loc) · 10 KB
/
zotero.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
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
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2011 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
var Zotero = new function() {
this.version = "5.0";
this.isConnector = true;
this.isFx = false;
this.initDeferred = {};
this.initDeferred.promise = new Promise(function(resolve, reject) {
this.initDeferred.resolve = resolve;
this.initDeferred.reject = reject;
}.bind(this));
// Browser check adopted from:
// http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Firefox 1.0+
this.isFirefox = typeof InstallTrigger !== 'undefined';
// At least Safari 10+
this.isSafari = typeof safari !== 'undefined';
// Internet Explorer 6-11
this.isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
this.isEdge = !this.isIE && !!window.StyleMedia;
// Chrome and Chromium
this.isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1 || window.navigator.userAgent.indexOf("Chromium") !== -1;
this.isBrowserExt = this.isFirefox || this.isEdge || this.isChrome;
if (this.isFirefox) {
this.browser = "g";
this.clientName = 'Firefox Connector';
} else if (this.isSafari) {
this.browser = "s";
this.clientName = 'Safari Connector';
} else if (this.isIE) {
this.browser = "i";
this.clientName = 'Internet Explorer';
} else if (this.isEdge) {
this.browser = "c";
this.clientName = 'Edge Connector';
} else if (this.isChrome) {
this.browser = "c";
this.clientName = 'Chrome Connector';
} else {
// Assume this is something with no more capabilities than IE
this.browser = "i";
this.clientName = window.navigator.appName;
}
if (this.isBrowserExt) {
this.version = browser.runtime.getManifest().version;
} else if (this.isSafari) {
this.version = safari.extension.bundleVersion;
}
// window.Promise and Promise differ (somehow) in Firefox and when certain
// async promise resolution conditions arise upon calling Zotero.Promise.all().then(result => )
// somehow the result array doesn't properly have result[1] bound, even though
// Array.from(result)[1] is there. Magic of code.
// this.Promise = window.Promise;
this.Promise = Promise;
this.migrate = async function() {
let lastVersion = Zotero.Prefs.get('lastVersion');
var [major, minor, patch] = lastVersion.split('.');
Zotero.Prefs.set('lastVersion', Zotero.version);
// If coming from a version before 5.0.24, reset the
// auto-associate setting for all existing proxies, since it wasn't being set properly for
// proxies imported from the client
if ((lastVersion == '' || (major == 5 && minor == 0 && patch < 24)) && Zotero.Prefs.get('proxies.clientChecked')) {
for (let proxy of Zotero.Proxies.proxies) {
proxy.autoAssociate = true;
}
Zotero.Proxies.storeProxies();
}
};
/**
* Initializes Zotero services for the global page in Chrome or Safari
*/
this.initGlobal = async function() {
Zotero.isBackground = true;
if (Zotero.isBrowserExt) {
browser.runtime.getPlatformInfo().then(function (info) {
switch (info.os) {
case 'mac':
case 'win':
this.platform = info.os;
break;
default:
this.platform = 'unix';
}
}.bind(this));
} else if (Zotero.isSafari) {
this.platform = 'mac';
} else {
// IE and the likes? Who knows
this.platform = 'win';
}
await Zotero.Prefs.init();
Zotero.Debug.init();
Zotero.Messaging.init();
Zotero.Connector_Types.init();
Zotero.Repo.init();
if (Zotero.isBrowserExt) {
Zotero.WebRequestIntercept.init();
}
Zotero.Proxies.init();
Zotero.initDeferred.resolve();
await Zotero.migrate();
};
/**
* Initializes Zotero services for injected pages and the inject side of the bookmarklet
*/
this.initInject = function() {
Zotero.isInject = true;
Zotero.Messaging.init();
Zotero.Connector_Types.init();
Zotero.Prefs.loadNamespace(['translators.', 'downloadAssociatedFiles', 'automaticSnapshots',
'reportTranslationFailure', 'capitalizeTitles']);
return Zotero.Prefs.loadNamespace('debug').then(function() {
Zotero.Debug.init();
Zotero.initDeferred.resolve();
});
};
/**
* Get versions, platform, etc.
*/
this.getSystemInfo = function() {
var info = {
connector: "true",
version: this.version,
platform: navigator.platform,
locale: navigator.language,
userAgent: navigator.userAgent
};
info.appName = Zotero.clientName;
info.zoteroAvailable = Zotero.Connector.isOnline;
var str = '';
for (var key in info) {
str += key + ' => ' + info[key] + ', ';
}
str = str.substr(0, str.length - 2);
return Promise.resolve(str);
};
/**
* Writes a line to the debug console
*/
this.debug = function(message, level) {
Zotero.Debug.log(message, level);
};
this.logError = function(err) {
if(!window.console) return;
// Firefox uses this
var fileName = (err.fileName ? err.fileName : null);
var lineNumber = (err.lineNumber ? err.lineNumber : null);
// Safari uses this
if(!fileName && err.sourceURL) fileName = err.sourceURL;
if(!lineNumber && err.line) lineNumber = err.line;
// Chrome only gives a stack
if(!fileName && !lineNumber && err.stack) {
const stackRe = /^\s+at (?:[^(\n]* \()?([^\n]*):([0-9]+):([0-9]+)\)?$/m;
var m = stackRe.exec(err.stack);
if(m) {
fileName = m[1];
lineNumber = m[2];
}
}
if(!fileName && !lineNumber && Zotero.isIE && typeof err === "object") {
// IE can give us a line number if we re-throw the exception, but we wrap this in a
// setTimeout call so that we won't throw in the middle of a function
window.setTimeout(function() {
window.onerror = function(errmsg, fileName, lineNumber) {
try {
Zotero.Errors.log("message" in err ? err.message : err.toString(), fileName, lineNumber);
} catch(e) {};
return true;
};
throw err;
window.onerror = undefined;
}, 0);
return;
}
if(fileName && lineNumber) {
console.error(err+" at "+fileName+":"+lineNumber);
} else {
console.error(err);
}
if (err.stack) {
let error = err.stack;
if (Zotero.isSafari) {
error = err.message + '\n' + error;
}
Zotero.Errors.log(error);
} else {
Zotero.Errors.log(err.message ? err.message : err.toString(), fileName, lineNumber);
}
};
}
Zotero.Prefs = new function() {
const DEFAULTS = {
"debug.log": false,
"debug.stackTrace": false,
"debug.store": false,
"debug.store.limit": 750000,
"debug.level": 5,
"debug.time": false,
"lastVersion": "",
"downloadAssociatedFiles": true,
"automaticSnapshots": true,
"connector.repo.lastCheck.localTime": 0,
"connector.repo.lastCheck.repoTime": 0,
"connector.url": ZOTERO_CONFIG.CONNECTOR_SERVER_URL,
"capitalizeTitles": false,
"interceptKnownFileTypes": true,
"allowedInterceptHosts": [],
"firstUse": true,
"firstSaveToServer": true,
"reportTranslationFailure": true,
"translatorMetadata": [],
"proxies.transparent": true,
"proxies.autoRecognize": true,
"proxies.showRedirectNotification": true,
"proxies.disableByDomain": false,
"proxies.disableByDomainString": '.edu',
"proxies.proxies": [],
"proxies.clientChecked": false,
};
this.syncStorage = {};
/**
* Should override per browser and load data into this.syncStorage
*/
this.init = function() {throw new Error("Prefs initialization not overriden");};
this.get = function(pref) {
try {
if (!(pref in this.syncStorage)) throw new Error(`Prefs.get: ${pref} not preloaded`);
return this.syncStorage[pref];
} catch (e) {
if (DEFAULTS.hasOwnProperty(pref)) return DEFAULTS[pref];
if (Zotero.isBackground) {
throw new Error("Zotero.Prefs: Invalid preference "+pref);
} else {
throw e;
}
}
};
this.getAll = function() {
let prefs = Object.assign({}, DEFAULTS, this.syncStorage);
delete prefs['translatorMetadata'];
return Zotero.Promise.resolve(prefs);
};
this.getAsync = function(pref) {
return new Zotero.Promise(function(resolve, reject) {
try {
if (typeof pref === "object") {
var prefData = {};
for(var i=0; i<pref.length; i++) {
prefData[pref[i]] = Zotero.Prefs.get(pref[i]);
}
resolve(prefData);
} else {
resolve(Zotero.Prefs.get(pref));
}
} catch (e) {
reject(e);
}
});
};
/**
* Pre-load a namespace of prefs that can then be accessed synchronously.
* Only needed in injected code
*
* @param namespace {String|String[]}
*/
this.loadNamespace = function(namespaces) {
if (Zotero.isBackground) throw new Error('trying to load namespace in background. all prefs are available via the sync API');
if (! Array.isArray(namespaces)) namespaces = [namespaces];
return this.getAll().then(function(prefs) {
let keys = Object.keys(prefs);
for (let namespace of namespaces) {
keys.filter((key) => key.indexOf(namespace) === 0)
.forEach((key) => this.syncStorage[key] = prefs[key]);
}
}.bind(this));
};
/**
* Should override per browser
* @param pref
* @param value
*/
this.set = function(pref, value) {
Zotero.debug("Setting "+pref+" to "+JSON.stringify(value));
this.syncStorage[pref] = value;
};
/**
* Should override per browser
* @param pref
*/
this.clear = function(pref) {
if (Array.isArray(pref)) return pref.forEach((p) => this.clear(p));
delete this.syncStorage[pref];
}
}