-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
322 lines (294 loc) · 9.16 KB
/
background.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
main=function(){
var API_PATH = "/index.php/apps/passwords/api/0.1/passwords";
var RETRY_TIME = 500; // ms
var RETRIES = 20;
var SERVER, USER, PASSWORD; // set via setPopupData
var options;
var data;
var count;
if(PASSWORD==undefined) {
chrome.browserAction.setPopup({popup: "popup.html"});
chrome.browserAction.setIcon({path: "icons/icon-32.png"});
}
chrome.browserAction.onClicked.addListener(function() {
if(SERVER){
if(data==undefined){
loadData(action);
} else {
action();
loadData();
}
}
});
///////////// Options /////////////
chrome.storage.onChanged.addListener(function(changes){
if(changes.options) {
options = changes.options.newValue;
}
});
chrome.storage.sync.get({options: {
matchSubdomain: true, // default values
}}, function(items) {
options = items.options;
}
);
///////////////////////////////////
function indicatorListener() {
if(SERVER){
if(data==undefined){
loadData(indicatorAction);
} else {
indicatorAction();
}
}
}
function urlMatch(url) {
url=url.split("/")[2];
if(!options.matchSubdomain) {
url = url.match(/([^.]*)\.([^.]*)$/)[0]; // get domain.tld
Object.keys(data).some(function(x){
if(url==x.match(/([^.]*)\.([^.]*)$/)[0]) { // match domain.tld
url = x;
return data[x];
}
});
}
return data[url];
}
function indicatorAction() {
getCurrentTabUrl(function(url){
if(data!=undefined) {
if(urlMatch(url)) {
chrome.browserAction.setPopup({popup: ""});
chrome.browserAction.setIcon({path: "icons/icon-green-32.png"});
} else {
chrome.browserAction.setPopup({popup: "popup-add.html"});
chrome.browserAction.setIcon({path: "icons/icon-32.png"});
}
}
});
}
function action(){
getCurrentTabUrl(function(url){
var cred = urlMatch(url);
if(cred) { // URL match
chrome.tabs.executeScript(null, {code: getInsertCode(cred[0], cred[1])});
}
console.log(url);
});
count++;
//chrome.browserAction.setBadgeText({text:" "});
//chrome.browserAction.setBadgeBackgroundColor({color: [r(0,255),r(0,255),r(0,255),255]});
}
function r(min,max){return Math.floor((Math.random() * max) + min) }
function setPopupData(server,username,password) { // calles from popup.js
SERVER = server;
USER = username;
PASSWORD = password;
console.log("received data!",SERVER,USER);
loadData(function(){
if(data!=undefined) {
chrome.browserAction.setPopup({popup: ""});
chrome.tabs.onUpdated.addListener(indicatorListener);
chrome.tabs.onActivated.addListener(indicatorListener);
indicatorAction();
//action();
} else {
chrome.browserAction.setIcon({path: "icons/icon-red-32.png"});
}
});
}
function addAcc(website,username, pw) {
addAcc_(website, username, pw, 0);
}
function addAcc_(website, username, pw, parse_error_count){
var website_filtered = website.split("/")[2];
console.log("addAcc called", website_filtered, username);
data[website_filtered] = [username, pw];
indicatorAction();
console.log("POST fetching...");
setBadge("wait");
var body = '{"website":"'+website_filtered+'",' +
'"pass":'+JSON.stringify(pw)+',' +
'"loginname":'+JSON.stringify(username)+',' +
'"address": '+JSON.stringify(website)+',' +
'"notes": ""}';
//console.log("send data:",body);
fetch(SERVER+API_PATH, {
credentials: 'omit', // this is the default value
cache: 'no-store',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": "Basic "+btoa(USER+":"+PASSWORD) // base64 encode credentials
},
body: body
}).then(function(res) {
console.log("POST request ok?", res.ok);
if (!res.ok) {
throw Error(res.statusText);
} else {
res.json().then(function(resJson) {
setBadge("ok");
indicatorAction();
resetBadge();
}).catch(function(error) {
console.log("parse error 2", error);
setBadge("error");
if(parse_error_count<RETRIES) {
parse_error_count++;
setTimeout(function(){
console.log("POST retry #",parse_error_count);
addAcc_(website,username,pw,parse_error_count);
},RETRY_TIME)
}
});
}
}).catch(function(error) {
console.log("Network error", error);
setBadge("error");
resetBadge();
chrome.browserAction.setIcon({path: "icons/icon-red-32.png"});
});
}
function setBadge(s){
var color = "";
switch (s) {
case "ok": color = "#73d216"; break; // Tango Colors:
case "wait": color = "#edd400"; break; // http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines
case "error": color = "#cc0000"; break;
}
chrome.browserAction.setBadgeBackgroundColor({color: color});
chrome.browserAction.setBadgeText({text:" "});
}
function resetBadge(timeout) {
if(timeout==undefined) timeout = 2000;
setTimeout(function(){
chrome.browserAction.setBadgeText({text:""});
},timeout);
}
function loadData(cb) {
loadData_(cb, 0);
}
function loadData_(cb, parse_error_count){
if(SERVER) {
console.log("GET fetching...");
setBadge("wait");
chrome.browserAction.setBadgeText({text:" "});
fetch(SERVER+API_PATH, {
credentials: 'omit', // this is the default value
cache: 'no-store',
headers: {
Authorization: "Basic "+btoa(USER+":"+PASSWORD)
}
}).then(function(res) {
console.log("GET request ok?", res.ok);
if (!res.ok) {
throw Error(res.statusText);
} else {
res.json().then(function(resJson) {
data = resJson.filter(function(ele){return ele.creation_date!=null});
data = data.filter(function(ele){return ele.deleted=="0"});
data = processData(data);
setBadge("ok");
resetBadge();
indicatorAction();
if(cb!=undefined) {
cb();
}
}).catch(function(error) {
console.log("parse error 1", error);
setBadge("error");
if(parse_error_count<RETRIES) {
parse_error_count++;
setTimeout(function(){
console.log("GET retry #",parse_error_count);
loadData_(cb, parse_error_count);
},RETRY_TIME)
}
});
}
return res;
}).catch(function(error) {
console.log("Network/Auth error", error);
setBadge("error");
resetBadge();
chrome.browserAction.setIcon({path: "icons/icon-red-32.png"});
});
} else {
console.warn("loadData without SERVER set");
}
}
function processData(input){
var out = {};
input.forEach(function(x){
if(x.properties){
var prop={};
try{
prop=JSON.parse("{" + x.properties.split(', "notes')[0] + "}")
} catch(e){console.log("exception", e)}
var url="";
try{
url=prop["address"].split("/");
if(url.length>1) {
url=url[2]
} else {
url=url[0]
}
} catch(e){console.log("exception", e)}
//console.log(url,prop.loginname,x.pass);
if(url) {
out[url] = [prop.loginname,x.pass];
}
}
});
return out;
}
function getInsertCode(user,pw){
var UsernameSelectors = "input[name=id], input[name=lid], input[name=username], input[name=Username], input[name=userName], \
input[name=user], input[name=email], input[name=Email], input[name=eMail], input[name=acct], \
input[type=text], input[type=email], input[name=acc], input[name=login][type=text]";
var u = encodeURIComponent(user);
var p = encodeURIComponent(pw);
return "document.querySelector('body').style.backgroundColor='#cfc'; \
document.querySelectorAll('"+UsernameSelectors+"').forEach(function(x){x.value=decodeURIComponent('"+u+"')}); \
document.querySelectorAll('input[type=password]').forEach(function(x){ x.value=decodeURIComponent('"+p+"')});";
}
function getCurrentTabUrl(callback) { // from Chromes tutorial extension
// Query filter to be passed to chrome.tabs.query - see
// https://developer.chrome.com/extensions/tabs#method-query
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
// chrome.tabs.query invokes the callback with a list of tabs that match the
// query. When the popup is opened, there is certainly a window and at least
// one tab, so we can safely assume that |tabs| is a non-empty array.
// A window can only have one active tab at a time, so the array consists of
// exactly one tab.
var tab = tabs[0];
// A tab is a plain object that provides information about the tab.
// See https://developer.chrome.com/extensions/tabs#type-Tab
var url = tab.url;
// tab.url is only available if the "activeTab" permission is declared.
// If you want to see the URL of other tabs (e.g. after removing active:true
// from |queryInfo|), then the "tabs" permission is required to see their
// "url" properties.
console.assert(typeof url == 'string', 'tab.url should be a string');
callback(url);
});
// Most methods of the Chrome extension APIs are asynchronous. This means that
// you CANNOT do something like this:
//
// var url;
// chrome.tabs.query(queryInfo, function(tabs) {
// url = tabs[0].url;
// });
// alert(url); // Shows "undefined", because chrome.tabs.query is async.
}
return {
"setPopupData" : setPopupData,
"addAcc" : addAcc
}
}();