-
Notifications
You must be signed in to change notification settings - Fork 124
/
inject.jsx
425 lines (389 loc) · 14.4 KB
/
inject.jsx
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 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 *****
*/
/**
* Only register progress window code in top window
*/
var isTopWindow = false;
if(window.top) {
try {
isTopWindow = window.top == window;
} catch(e) {};
}
if(isTopWindow) {
/*
* Register save dialog listeners
*
* When an item is saved (by this page or by an iframe), the item will be relayed back to
* the background script and then to this handler, which will show the saving dialog
*/
Zotero.Messaging.addMessageListener("progressWindow.show", function(headline) {
Zotero.ProgressWindow.show();
if (headline) {
return Zotero.ProgressWindow.changeHeadline(headline);
}
Zotero.Connector.callMethod("getSelectedCollection", {}, function(response, status) {
if (status !== 200) {
Zotero.ProgressWindow.changeHeadline("Saving to zotero.org");
} else {
Zotero.ProgressWindow.changeHeadline("Saving to ",
response.id ? "treesource-collection.png" : "treesource-library.png",
response.name+"\u2026");
}
});
});
var itemProgress = {};
Zotero.Messaging.addMessageListener("progressWindow.itemSaving", function(data) {
itemProgress[data[2]] = new Zotero.ProgressWindow.ItemProgress(data[0], data[1],
data.length > 3 ? itemProgress[data[3]] : undefined);
});
Zotero.Messaging.addMessageListener("progressWindow.itemProgress", function(data) {
var progress = itemProgress[data[2]];
if(!progress || !data[2]) {
progress = itemProgress[data[2]] = new Zotero.ProgressWindow.ItemProgress(data[0], data[1]);
} else {
progress.setIcon(data[0]);
}
if(data[3] === false) {
progress.setError();
} else {
progress.setProgress(data[3]);
}
});
Zotero.Messaging.addMessageListener("progressWindow.close", Zotero.ProgressWindow.close);
Zotero.Messaging.addMessageListener("progressWindow.done", function(returnValue) {
if (returnValue[0]) {
Zotero.ProgressWindow.startCloseTimer(2500);
} else {
new Zotero.ProgressWindow.ErrorMessage(returnValue[1] || "translationError");
Zotero.ProgressWindow.startCloseTimer(8000);
}
});
Zotero.Messaging.addMessageListener("confirm", function (props) {
return Zotero.Inject.confirm(props);
});
Zotero.Messaging.addMessageListener("ping", function () {
// Respond to indicate that script is injected
return 'pong';
});
}
/**
* @namespace
*/
var instanceID = (new Date()).getTime();
Zotero.Inject = new function() {
var _translate;
this.translators = {};
function determineAttachmentIcon(attachment) {
if(attachment.linkMode === "linked_url") {
return Zotero.ItemTypes.getImageSrc("attachment-web-link");
}
return Zotero.ItemTypes.getImageSrc(attachment.mimeType === "application/pdf"
? "attachment-pdf" : "attachment-snapshot");
}
/**
* Check if React and components are loaded and if not - load into page.
*
* This is a performance optimization - we want to avoid loading React into every page.
*
* @param components {Object[]} an array of component names to load
* @return {Promise} resolves when components are injected
*/
this.loadReactComponents = function(components) {
var toLoad = [];
if (typeof ReactDOM === "undefined") {
toLoad = ['lib/react.js', 'lib/react-dom.js'];
}
for (let component of components) {
if (!Zotero.ui || !Zotero.ui[component]) {
toLoad.push(`ui/${component.replace(/(.)([A-Z])/g, '$1-$2').toLowerCase()}.js`)
}
}
if (toLoad.length) {
return Zotero.Connector_Browser.injectScripts(toLoad);
} else {
return Zotero.Promise.resolve();
}
}
/**
*
* @param props {Object} to be passed to ModalPrompt component
* @returns {Promise{Object}} Object with properties:
* `button` - button number clicked (or 0 if clicked outside of prompt)
* `checkboxChecked` - checkbox state on close
* `inputText` - input field string on close
*/
this.confirm = function(props) {
let deferred = Zotero.Promise.defer();
Zotero.Inject.loadReactComponents(['ModalPrompt']).then(function() {
let div = document.createElement('div');
div.style.cssText = 'z-index: 1000000; position: fixed; top: 0; left: 0; width: 100%; height: 100%';
let prompt = (
<Zotero.ui.ModalPrompt
onClose={onClose}
{...props}
/>
);
function onClose(state, event) {
deferred.resolve({
button: event ? parseInt(event.target.name || 0) : 0,
checkboxChecked: state.checkboxChecked,
inputText: state.inputText
});
ReactDOM.unmountComponentAtNode(div);
document.body.removeChild(div);
}
ReactDOM.render(prompt, div);
document.body.appendChild(div);
}.bind(this));
return deferred.promise;
};
this.firstUsePrompt = function () {
return this.confirm({
title: "You’ve installed the Zotero Connector!",
button1Text: "Got it",
button2Text: "",
message: `
The Zotero Connector enables you to save references to Zotero from your web browser in a single click.<br><br>
<em><strong>Looking for your Zotero data?</strong> If you were previously using Zotero for Firefox, you’ll need to <a href="https://www.zotero.org/download">download</a> the standalone Zotero application to access your local Zotero data going forward. For more information, see [blog post forthcoming before 5.0 Final].</em>
`,
clickOutsideToClose: true
});
};
this.firstSaveToServerPrompt = function() {
return this.confirm({
button1Text: "Try Again",
button2Text: "Cancel",
button3Text: "Enable Saving to Zotero.org",
title: "Zotero is Offline",
message: `
The Zotero Connector was unable to communicate with the Zotero desktop application. The Connector can save some pages directly to your zotero.org account, but for best results you should make sure Zotero is open before attempting to save.<br/><br/>
You can <a href="https://www.zotero.org/download/">download Zotero</a> or <a href="https://www.zotero.org/support/kb/connector_zotero_unavailable">troubleshoot the connection</a> if necessary.
`
}).then(function(result) {
switch (result.button) {
case 1:
return 'retry';
case 3:
return 'server';
default:
return 'cancel';
}
});
};
/**
* Prompts about saving to zotero.org if attempting for the first time
* Prompt only available on BrowserExt which supports programmatic injection
* Otherwise just resolves to true
*
* return {Promise<Boolean>} whether save to server should proceed
*/
this.checkSaveToServer = function() {
if (Zotero.isBrowserExt) {
return Zotero.Prefs.getAsync('firstSaveToServer')
.then(function (firstSaveToServer) {
if (firstSaveToServer) {
return this.firstSaveToServerPrompt()
.then(function (result) {
if (result == 'server') {
Zotero.Prefs.set('firstSaveToServer', false);
}
return result;
});
}
return 'server';
}.bind(this));
} else {
return Zotero.Promise.resolve('server');
}
}
this.translate = function(translatorID) {
Zotero.Messaging.sendMessage("progressWindow.show", null);
_translate.setTranslator(Zotero.Inject.translators[translatorID]);
_translate.translate();
};
this.saveAsWebpage = function (title) {
var html = document.documentElement.innerHTML;
var data = {
"url": document.location.toString(),
"cookie": document.cookie,
"html": html
};
if (document.contentType == 'application/pdf') {
data.pdf = true;
var image = "attachment-pdf";
} else {
var image = "webpage";
}
var progress = new Zotero.ProgressWindow.ItemProgress(
Zotero.ItemTypes.getImageSrc(image), title || document.title
);
Zotero.Connector.callMethod("saveSnapshot", data,
function(returnValue, status) {
if (returnValue === false) {
// Client unavailable
if (status === 0) {
// Attempt saving to server if not pdf
if (document.contentType != 'application/pdf') {
Zotero.ProgressWindow.changeHeadline('Saving to zotero.org');
let itemSaver = new Zotero.Translate.ItemSaver({});
itemSaver.saveSnapshot().then(function(items) {
if (items.length) progress.setProgress(100);
});
} else {
new Zotero.ProgressWindow.ErrorMessage("clientRequired");
}
} else {
new Zotero.ProgressWindow.ErrorMessage("translationError");
}
Zotero.ProgressWindow.startCloseTimer(8000);
} else {
progress.setProgress(100);
Zotero.ProgressWindow.startCloseTimer(2500);
}
});
};
/**
* Initializes the translate machinery and determines whether this page can be translated
*/
this.detect = function(force) {
// On OAuth completion, close window and call completion listener
if(document.location.href.substr(0, ZOTERO_CONFIG.OAUTH_CALLBACK_URL.length+1) === ZOTERO_CONFIG.OAUTH_CALLBACK_URL+"?") {
Zotero.API.onAuthorizationComplete(document.location.href.substr(ZOTERO_CONFIG.OAUTH_CALLBACK_URL.length+1));
return;
} /*else if(document.location.href.substr(0, ZOTERO_CONFIG.OAUTH_NEW_KEY_URL.length) === ZOTERO_CONFIG.OAUTH_NEW_KEY_URL) {
document.getElementById("submit").click();
return;
}*/
// wrap this in try/catch so that errors will reach logError
try {
if(this.translators.length) {
if(force) {
this.translators = [];
} else {
return;
}
}
if(document.location == "about:blank") return;
if(!_translate) {
var me = this;
_translate = new Zotero.Translate.Web();
_translate.setDocument(document);
_translate.setHandler("translators", function(obj, translators) {
me.translators = {};
for (let translator of translators) {
me.translators[translator.translatorID] = translator;
}
translators = translators.map(function(translator) {return translator.serialize(TRANSLATOR_PASSING_PROPERTIES)});
Zotero.Connector_Browser.onTranslators(translators, instanceID, document.contentType);
});
_translate.setHandler("select", function(obj, items, callback) {
Zotero.Connector_Browser.onSelect(items, function(returnItems) {
// if no items selected, close save dialog immediately
if(!returnItems || Zotero.Utilities.isEmpty(returnItems)) {
Zotero.Messaging.sendMessage("progressWindow.close", null);
}
callback(returnItems);
});
});
_translate.setHandler("itemSaving", function(obj, item) {
// this relays an item from this tab to the top level of the window
Zotero.Messaging.sendMessage("progressWindow.itemSaving",
[Zotero.ItemTypes.getImageSrc(item.itemType), item.title, item.id]);
});
_translate.setHandler("itemDone", function(obj, dbItem, item) {
// this relays an item from this tab to the top level of the window
Zotero.Messaging.sendMessage("progressWindow.itemProgress",
[Zotero.ItemTypes.getImageSrc(item.itemType), item.title, item.id, 100]);
for(var i=0; i<item.attachments.length; i++) {
var attachment = item.attachments[i];
Zotero.Messaging.sendMessage("progressWindow.itemSaving",
[determineAttachmentIcon(attachment), attachment.title, attachment.id,
item.id]);
}
});
_translate.setHandler("attachmentProgress", function(obj, attachment, progress, err) {
if(progress === 0) return;
Zotero.Messaging.sendMessage("progressWindow.itemProgress",
[determineAttachmentIcon(attachment), attachment.title, attachment.id, progress]);
});
_translate.setHandler("done", function(obj, status) {
Zotero.Messaging.sendMessage("progressWindow.done", [status]);
});
_translate.setHandler("pageModified", function() {
Zotero.Connector_Browser.onPageLoad();
Zotero.Messaging.sendMessage("pageModified", null);
});
document.addEventListener("ZoteroItemUpdated", function() {
Zotero.debug("Inject: ZoteroItemUpdated event received");
Zotero.Connector_Browser.onPageLoad();
Zotero.Messaging.sendMessage("pageModified", null);
}, false);
}
return _translate.getTranslators(true);
} catch(e) {
Zotero.logError(e);
}
};
};
// check whether this is a hidden browser window being used for scraping
var isHiddenIFrame = false;
try {
isHiddenIFrame = !isTopWindow && window.frameElement && window.frameElement.style.display === "none";
} catch(e) {}
// don't try to scrape on hidden frames
if(!isHiddenIFrame && (window.location.protocol === "http:" || window.location.protocol === "https:")) {
var doInject = function () {
// add listener for translate message from extension
Zotero.Messaging.addMessageListener("translate", function(data) {
if(data[0] !== instanceID) return;
Zotero.Inject.translate(data[1]);
});
// add a listener to save as webpage when translators unavailable
Zotero.Messaging.addMessageListener("saveAsWebpage", Zotero.Inject.saveAsWebpage);
// add listener to rerun detection on page modifications
Zotero.Messaging.addMessageListener("pageModified", function() {
Zotero.Inject.detect(true);
});
Zotero.Messaging.addMessageListener("firstUse", function () {
return Zotero.Inject.firstUsePrompt();
});
// initialize
Zotero.initInject();
// Send page load event to clear current save icon/data
if(isTopWindow) Zotero.Connector_Browser.onPageLoad();
if(document.readyState !== "complete") {
window.addEventListener("load", function(e) {
if(e.target !== document) return;
Zotero.Inject.detect();
}, false);
} else {
Zotero.Inject.detect();
}
};
// Wait until pages in prerender state become visible before injecting
if (document.visibilityState == 'prerender') {
var handler = function() {
doInject();
document.removeEventListener("visibilitychange", handler);
};
document.addEventListener("visibilitychange", handler);
} else {
doInject();
}
}