Parent: [2f9679] (diff)

Child: [087c8b] (diff)

Download this file

content.js    373 lines (328 with data), 12.3 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
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
/*
* RecollWebext - WebExtension - Background Page
*
* A lot of code was copied from or inspired by the Save Page WE
* extension.
*
* Copyright (C) 2017 jfd@recoll.org
* Copyright (C) 2016-2017 DW-dev
*
* Distributed under the GNU General Public License version 2
* See LICENCE.txt file and http://www.gnu.org/licenses/
*/
"use strict";
/* Global variables */
var isFirefox;
var menuAction;
var autosave;
var httpsalso;
var nomatchsave;
var conflictsave;
var urlRules = {
inc: [],
exc: []
};
var htmlStrings = new Array();
/* Initialize on script load */
chrome.storage.local.get(
null,
function(object) {
/* Load environment */
isFirefox = object["environment-isfirefox"];
/* Load options */
loadOptions(object);
addListeners();
});
function loadOptions(object)
{
/* for (var key in object) {
console.log("Content init: " + key + " => " + object[key]);
}*/
autosave = object["options-autosave"];
httpsalso = object["options-httpsalso"];
nomatchsave = object["options-nomatch-dosave"],
conflictsave = object["options-conflict-dosave"];
var keys = ["options-url-include", "options-url-exclude"];
var sks = ["inc", "exc"];
for (var t = 0; t < 2; t++) {
var key = keys[t];
var sk = sks[t];
if (key in object) {
for (var i = 0; i < object[key].length; i++) {
urlRules[sk].push(object[key][i]);
}
}
}
}
/* Add listeners */
function addListeners()
{
window.addEventListener(
"load",
function(event) {
if (document.readyState == "complete") {
if (autosave &&
(document.location.protocol == "http:" ||
(httpsalso && document.location.protocol == "https:"))) {
maybeSave();
}
}
}, false);
/* Storage changed listener */
chrome.storage.onChanged.addListener(
function(changes,areaName) {
chrome.storage.local.get(null, loadOptions);
});
/* Message received listener */
chrome.runtime.onMessage.addListener(
function(message,sender,sendResponse) {
var panel;
switch (message.type) {
/* Messages from background page */
case "performAction":
/* to confirm content script has been loaded */
sendResponse({ });
menuAction = message.menuaction;
/* Wait for page to complete loading */
if (document.readyState == "complete") {
window.setTimeout(
function() {
performAction(message.srcurl);
}, 50);
} else {
window.addEventListener(
"load",
function(event) {
if (document.readyState == "complete")
performAction(message.srcurl);
}, false);
}
break;
case "loadSuccess":
loadSuccess(message.index, message.content,
message.contenttype, message.alloworigin);
break;
case "loadFailure":
loadFailure(message.index);
break;
}
});
/* Maybe addListeners() was called after doc complete. In which
* case we will never have the "load" event. This happens with
* "Open in new tab" for some reason. Initiate save at once. */
if (document.readyState == "complete") {
if (autosave &&
(document.location.protocol == "http:" ||
(httpsalso && document.location.protocol == "https:"))) {
maybeSave();
}
}
}
/* This is called when we receive a message from the background page,
initiated by a button or context menu choice */
function performAction(srcurl)
{
if (menuAction == 0) {
/* Save page */
htmlStrings.length = 0;
doSave();
} else if (menuAction == 1 || menuAction == 2) {
var hostname = location.hostname;
var sk, key;
if (menuAction == 1) {
sk = 'inc';
key = 'options-url-include';
} else {
sk = 'exc';
key = 'options-url-exclude';
}
/* Already there ? */
for (var i = 0; i < urlRules[sk].length; i++) {
if (urlRules[sk][i][1] == hostname &&
urlRules[sk][i][2] == 'domain') {
return;
}
}
var rule = ['ca_'+ hostname, hostname, 'domain'];
urlRules[sk].push(rule);
/*console.log("Url rules: key: " + key + " new value: "
+ urlRules[sk]);*/
var obj = {};
obj[key] = urlRules[sk];
if (menuAction == 1) {
/* Also set autosave */
obj["options-autosave"] = true;
if (document.location.protocol == "https:") {
obj["options-httpsalso"] = true;
}
/* Remove the 'save by default' option, otherwise the
positive rule makes no sense */
obj["options-nomatch-dosave"] = false;
}
chrome.storage.local.set(obj);
}
}
/********************/
/* Copied from tested module in ../tested/wildcard.js */
function wildcard2RE(s)
{
/* Quote some characters which are not special for wildcard exprs
(or which we don't want to support), and are special for
regexps */
s = s.replace(/([\.\+\{\}\^\$])/g, "\\$1");
/* Replace unescaped question marks with '.' and '*' with '.*'
Note that this does not work if the backslash is itself
escaped in the wildcard exp. Also we don't match / or : */
s = s.replace(/(^|[^\\])\?/g, "$1[^/]").replace(/(^|[^\\])\*/g,"$1[^/]*")
/* Replace '!' as first character of bracketed expr with '^' */
s = s.replace(/(^|[^\\])\[!/g, "$1[^");
/* Anchor expression */
return "^" + s + "$";
}
function wildcardMatch(e, v)
{
var re = RegExp(wildcard2RE(e));
/*console.log("RE: " + re + " V: [" + v + "] result: " + re.test(v))*/
return re.test(v);
}
/* End copied code ***************/
function maybeSave()
{
var location = document.location;
/*console.log("maybeSave. mtype " + document.contentType +
" url " + document.location.href);*/
/* We are only called from the automatic save after load situation, and
the protocol (http or https), and checks against
autosave/httpsalso were performed in the listener.
So we just need to check the url against the selection/exclusion lists.
*/
var sks = ['exc', 'inc'];
var flags = [false, false];
var hostname = location.hostname;
var href = location.href;
for(var j = 0; j < 2; j++) {
var sk = sks[j];
var flag = false;
for(var i = 0; i < urlRules[sk].length && !flag; i++) {
var lpattern = urlRules[sk][i][1];
var ptype = urlRules[sk][i][2];
switch (ptype) {
case 'domain':
// www.google.com matched by google.com and .com
// www.agoogle.com not matched by google.com but matched by com
// www.com.google. not matched by .com
var pattern = lpattern;
if (pattern[0] != '.')
pattern = "." + pattern;
flag = hostname.endsWith(pattern) || (hostname == lpattern);
console.log("Host match [" + lpattern + "] to [" +
hostname + "] -> " + flag);
break;
case 'wildcard':
flag = wildcardMatch(lpattern, href);
console.log("Wildcard match [" + lpattern + "] to [" + href +
"] -> " + flag);
break;
case 'regexp':
var re = RegExp(list[i]['pattern']);
flag = (href.match(re) != null)
console.log("Regexp match [" + lpattern + "] to [" + href +
"] -> " + flag);
break;
default:
console.log("Invalid " + sk + " rule " + urlRules[sk][i]);
break;
}
}
flags[j] = flag;
}
console.log("maybeSave ? Exclude list match: " + flags[0] +
". Include list match: " + flags[1]);
/* If both lists are empty, save by default, even if nomatchsave
is not set: the user did not bother to set rules, let the
autosave variable decide */
// flags[0]: exclude. flags[1]: include
if (urlRules['inc'].length == 0 && urlRules['exc'].length == 0) {
flags[1] = true;
} else {
if (!flags[0] && !flags[1])
flags[1] = nomatchsave;
if(flags[0] && flags[1])
flags[1] = conflictsave;
}
if (flags[1]) {
doSave();
}
}
/* Return the content base file name for a given URL */
function getContentName(url)
{
return "recoll-we-c-" + recoll_md5.hex_md5(url) + ".rclwe";
}
/* Return the metadata base file name path for a given url */
function getMetaName(url)
{
return "recoll-we-m-" + recoll_md5.hex_md5(url) + ".rclwe";
}
function metadata(url, contentType, charset)
{
var meta = [
url + "\n",
"WebHistory\n",
contentType + "\n",
"k:_unindexed:encoding=" + charset + "\n"
];
return meta;
}
function downloadDataThroughLink(data, filename)
{
var blob, objURL, link;
function handleClick(event)
{
event.stopPropagation();
}
blob = new Blob(data, {type: "text/x-recoll-data"});
objURL = window.URL.createObjectURL(blob);
link = document.createElement("a");
link.download = filename;
link.href = objURL;
console.log("Recoll: generate link click for filename " + filename +
" href " + link.href);
document.body.appendChild(link);
link.addEventListener("click", handleClick, true);
link.click();
link.removeEventListener("click", handleClick, true);
window.setTimeout(
function() {
document.body.removeChild(link);
window.URL.revokeObjectURL(objURL);
chrome.runtime.sendMessage({type: "setSaveBadge",
text: "", color: "#000000" });
}, 1000);
}
function doSave()
{
var i,j,mimetype, filename
chrome.runtime.sendMessage({type: "setSaveBadge", text: "SAVE",
color: "#0000E0" });
/* Save metadata to file using HTML5 download attribute */
let meta = metadata(document.location.href, document.contentType,
document.characterSet);
filename = getMetaName(document.location.href);
downloadDataThroughLink(meta, filename);
if(document.contentType.match(/(text|html|xml)/i)) {
/* Save data to file using HTML5 download attribute */
htmlStrings.length = 0;
htmlStrings[0] = document.documentElement.outerHTML;
filename = getContentName(document.location.href);
downloadDataThroughLink(htmlStrings, filename);
htmlStrings.length = 0;
} else {
console.log("Recoll: send download message for " +
document.location.href + " filename " + filename);
filename = getContentName(document.location.href);
chrome.runtime.sendMessage({type: "downloadFile",
location: document.location.href,
filename: filename });
}
}