-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.js
237 lines (198 loc) · 9.25 KB
/
main.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
'use strict';
const utils = require('@iobroker/adapter-core');
const axios = require('axios').default;
const PushoverNotifications = require('pushover-notifications');
class Pushover extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'pushover',
});
this.pushover = undefined;
this.lastMessageTime = 0;
this.lastMessageText = '';
this.on('ready', this.onReady.bind(this));
this.on('message', this.onMessage.bind(this));
}
async onReady() {
// do nothing. Only answer on messages.
if (!this.config.user || !this.config.token) {
this.log.error('Cannot send notification while not configured');
}
}
/**
* @param {ioBroker.Message} obj
*/
onMessage(obj) {
if (obj && obj.command === 'send' && obj.message) {
obj.message && this.processMessage(obj);
} else if (obj && obj.command === 'glances' && obj.message) {
obj.message && this.sendGlances(obj);
} else {
obj.callback && this.sendTo(obj.from, 'send', { error: 'Unsupported' }, obj.callback);
}
}
processMessage(obj) {
// filter out the double messages
const json = JSON.stringify(obj.message);
if (this.lastMessageTime &&
this.lastMessageText === JSON.stringify(obj.message) &&
Date.now() - this.lastMessageTime < 1000
) {
return this.log.debug(`Filter out double message [first was for ${Date.now() - this.lastMessageTime}ms]: ${json}`);
}
this.lastMessageTime = Date.now();
this.lastMessageText = json;
if (obj.message.user && obj.message.token && obj.message.user !== this.config.user) {
const tempPushover = new PushoverNotifications({
user: obj.message.user,
token: obj.message.token,
onerror: this.onError.bind(this)
});
delete obj.message.user;
delete obj.message.token;
tempPushover.send(obj.message, (err, result, response) => {
this.log.debug(`Pushover response: ${JSON.stringify(response && response.headers)}`);
if (err) {
try {
this.log.error(`Cannot send notification: ${JSON.stringify(err)}`);
} catch (err) {
this.log.error(`Cannot send notification: ${err}`);
}
}
obj.callback && this.sendTo(obj.from, 'send', { err, result: result }, obj.callback);
});
} else {
this.sendNotification(obj.message, (error, result) =>
obj.callback && this.sendTo(obj.from, 'send', { error, result: result }, obj.callback));
}
}
sendGlances(obj) {
const json = JSON.stringify(obj.message);
if (this.lastMessageTime &&
this.lastMessageText === JSON.stringify(obj.message) &&
Date.now() - this.lastMessageTime < 1000
) {
return this.log.debug(`Filter out double message [first was for ${Date.now() - this.lastMessageTime}ms]: ${json}`);
}
this.lastMessageTime = Date.now();
this.lastMessageText = json;
const msg = obj.message;
const formData = {
token: msg.token || this.config.token,
user: msg.user || this.config.user,
title: msg.title !== undefined ? msg.title : this.config.title,
text: msg.message || msg.text,
subtext: msg.subtext || undefined,
count: msg.count || undefined,
percent: msg.percent || undefined,
device: msg.device || undefined
};
if (formData.title && formData.title.length > 100) {
this.log.error('Title too long. Max length is 100');
return obj.callback && this.sendTo(obj.from, 'glances', { error: 'Title too long. Max length is 100' }, obj.callback);
}
if (formData.text && formData.text.length > 100) {
this.log.error('Text too long. Max length is 100');
return obj.callback && this.sendTo(obj.from, 'glances', { error: 'Text too long. Max length is 100' }, obj.callback);
}
if (formData.subtext && formData.subtext.length > 100) {
this.log.error('Subtext too long. Max length is 100');
return obj.callback && this.sendTo(obj.from, 'glances', { error: 'Subtext too long. Max length is 100' }, obj.callback);
}
this.log.debug(`Sending pushover glances: ${JSON.stringify(formData)}`);
axios
.post('https://api.pushover.net/1/glances.json', formData)
.then(async response => {
this.log.debug(`Pushover glances response: ${JSON.stringify(response.status)} ${JSON.stringify(response.data)}`);
await this.setStateChangedAsync('app.totalLimit', { val: Number(response.headers['x-limit-app-limit']), ack: true });
await this.setStateChangedAsync('app.remainingLimit', { val: Number(response.headers['x-limit-app-remaining']), ack: true });
await this.setStateChangedAsync('app.limitRest', { val: Number(response.headers['x-limit-app-reset']) * 1000, ack: true });
if (response.data.status !== 1) {
this.log.error(`Pushover glances error: ${JSON.stringify(response.data.errors)}`);
obj.callback && this.sendTo(obj.from, 'glances', { error: response.data.errors }, obj.callback);
} else {
this.log.debug(`Pushover glances POST succeeded: ${JSON.stringify(response.data)}`);
obj.callback && this.sendTo(obj.from, 'glances', { error: null, result: response.data }, obj.callback);
}
})
.catch(error => {
this.log.error(`Pushover error: ${error}`);
obj.callback && this.sendTo(obj.from, 'glances', { error: `Pushover error: ${error}` }, obj.callback);
});
}
onError(error) {
this.log.error(`Error from Pushover: ${error}`);
}
sendNotification(message, callback) {
message = message || {};
if (!this.pushover) {
if (this.config.user && this.config.token) {
this.pushover = new PushoverNotifications({
user: this.config.user,
token: this.config.token,
onerror: this.onError.bind(this)
});
} else {
this.log.error('Cannot send notification while not configured');
}
}
if (!this.pushover) {
callback && callback('Cannot send notification while not configured');
return;
}
if (typeof message !== 'object') {
message = { message };
}
if (Object.prototype.hasOwnProperty.call(message, 'token')) {
this.pushover.token = message.token;
} else {
this.pushover.token = this.config.token;
}
message.title = message.title || this.config.title;
message.sound = message.sound || (this.config.sound ? this.config.sound : undefined);
message.priority = message.priority || this.config.priority;
message.message = message.message || '';
// if timestamp in ms => makes seconds // if greater than 2000.01.01 00:00:00
if (message.timestamp && message.timestamp > 946681200000) {
message.timestamp = Math.round(message.timestamp / 1000);
}
// mandatory parameters if priority is high (2)
if (message.priority === 2) {
message.retry = parseInt(message.retry, 10) || 60;
message.expire = parseInt(message.expire, 10) || 3600;
}
(this.config.showLog ? this.log.info : this.log.debug)(`Sending pushover notification: ${JSON.stringify(message)}`);
this.pushover.send(message, async (err, result, response) => {
this.log.debug(`Pushover response: ${JSON.stringify(response && response.headers)}`);
if (err) {
try {
this.log.error(`Cannot send notification: ${JSON.stringify(err)}`);
} catch (err) {
this.log.error(`Cannot send notification: ${err}`);
}
callback && callback(err);
return false;
} else {
await this.setStateChangedAsync('app.totalLimit', { val: Number(response.headers['x-limit-app-limit']), ack: true });
await this.setStateChangedAsync('app.remainingLimit', { val: Number(response.headers['x-limit-app-remaining']), ack: true });
await this.setStateChangedAsync('app.limitRest', { val: Number(response.headers['x-limit-app-reset']) * 1000, ack: true });
callback && callback(null, result);
return true;
}
});
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = options => new Pushover(options);
} else {
// otherwise start the instance directly
new Pushover();
}