-
Notifications
You must be signed in to change notification settings - Fork 6
/
comm.js
61 lines (55 loc) · 1.25 KB
/
comm.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
/**
* Desktop <--> extension communication module
*/
ext.comm = {
send: function(cmd, data, options)
{
options || (options = {});
var req = new XMLHttpRequest();
req.onload = function()
{
var res = this.responseText;
try
{
var obj = JSON.parse(res);
}
catch(e)
{
if(options.error) options.error('comm: error parsing json: '+ res);
return;
}
if(obj.error)
{
if(options.error) options.error(obj.error, obj.code);
}
else
{
if(options.success) options.success(obj);
}
};
req.onerror = function()
{
// signal a timeout
if(options.error) options.error(null, -1);
};
data = ext.comm.process(cmd, data);
req.open('get', 'http://127.0.0.1:7471/'+cmd+'?data='+encodeURIComponent(data), true);
req.send();
},
/**
* process the data we're sending. if we're doing a simple pair request,
* just JSON encode it.
*
* for any other outgoing request, we're going to encrypt the data via the
* public key the desktop app sent us.
*/
process: function(cmd, data)
{
var str = JSON.stringify(data);
if(cmd == 'pair') return str;
var key = ext.pairing.get_key({binary: true});
if(!key) return false;
data = tcrypt.asym.encrypt(key, str);
return tcrypt.to_base64(data);
}
};