-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpb_push.js
85 lines (62 loc) · 1.74 KB
/
pb_push.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
var support= ('Promise' in window);
if(!support)
{
var script = document.createElement('script');
script.type='text/javascript';
script.src='https://raw.githubusercontent.com/taylorhakes/promise-polyfill/master/Promise.js';
document.body.appendChild(script);
}
var PB = PB || {
base_url: "https://api.pushbullet.com/v2",
push_url: "/pushes",
tokens: new Array(),
init: function(token_array){
if(token_array === undefined)
return null;
else if(token_array.constructor === Array){
this.tokens = this.tokens.concat(token_array);
return this;
}
},
add_token: function(token){
this.tokens.push(token);
},
push_note: function(header,message){
data = {
type: "note",
title: header,
body: message
};
return this.api_request(this.push_url,data);
},
push_link: function(header,message,link){
data = {
type: "link",
title: header,
body: message,
url: link
};
return this.api_request(this.push_url,data);
},
api_request: function(url,send_data){
url = this.base_url + url;
var xhrs = this.tokens.map(function(token){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Authorization', 'Bearer '+token);
//xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') ** I guess not need , it follows XMLHttpRequest 2**
xhr.open('POST',url,!0);
xhr.responseType = 'text';
xhr.onload = function(){ (this.status === 200) && (resolve(this.response)) };
xhr.onerror = function(){ reject(new Error('bad luck !')) };
xhr.send(JSON.stringify(send_data));
})
});
Promise.all(xhrs).then(function(data){
console.log(data); //data is array
})
.catch(function(e){
console.log('Error !')
})
}
};