forked from munrexio/yandex2mqtt
-
Notifications
You must be signed in to change notification settings - Fork 20
/
app.js
187 lines (164 loc) · 5.74 KB
/
app.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
'use strict';
const fs = require('fs');
const path = require('path');
/* */
const {createLogger, format, transports} = require('winston');
/* express and https */
const ejs = require('ejs');
const express = require('express');
const app = express();
const https = require('https');
/* parsers */
const cookieParser = require('cookie-parser');
/* error handler */
const errorHandler = require('errorhandler');
/* seesion and passport */
const session = require('express-session');
const passport = require('passport');
/* mqtt client for devices */
const mqtt = require('mqtt');
/* */
const config = require('./config');
config.notification = config.notification || [];
const Device = require('./device');
/* */
const clArgv = process.argv.slice(2);
/* Logging */
global.logger = createLogger({
level: 'info',
format: format.combine(
format.errors({stack: true}),
format.timestamp(),
format.printf(({level, message, timestamp, stack}) => {
return `${timestamp} ${level}: ${stack != undefined ? stack : message}`;
}),
),
transports: [
new transports.Console({
silent: clArgv.indexOf('--log-info') == -1
})
],
});
if (clArgv.indexOf('--log-error') > -1) global.logger.add(new transports.File({filename: 'log/error.log', level: 'error'}));
/* */
app.engine('ejs', ejs.__express);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, './views'));
app.use(express.static('views'));
app.use(cookieParser());
app.use(express.json({
extended: false,
}));
app.use(express.urlencoded({
extended: true,
}));
app.use(errorHandler());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
/* passport */
app.use(passport.initialize());
app.use(passport.session());
/* passport auth */
require('./auth');
/* routers */
const {site: r_site, oauth2: r_oauth2, user: r_user, client: r_client} = require('./routes');
app.get('/', r_site.index);
app.get('/login', r_site.loginForm);
app.post('/login', r_site.login);
app.get('/logout', r_site.logout);
app.get('/account', r_site.account);
app.get('/dialog/authorize', r_oauth2.authorization);
app.post('/dialog/authorize/decision', r_oauth2.decision);
app.post('/oauth/token', r_oauth2.token);
app.get('/api/userinfo', r_user.info);
app.get('/api/clientinfo', r_client.info);
app.get('/provider/v1.0', r_user.ping);
app.get('/provider', r_user.ping);
app.get('/provider/v1.0/user/devices', r_user.devices);
app.post('/provider/v1.0/user/devices/query', r_user.query);
app.post('/provider/v1.0/user/devices/action', r_user.action);
app.post('/provider/v1.0/user/unlink', r_user.unlink);
/* create https server */
const privateKey = fs.readFileSync(config.https.privateKey, 'utf8');
const certificate = fs.readFileSync(config.https.certificate, 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
};
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(config.https.port);
/* cache devices from config to global */
global.devices = [];
if (config.devices) {
config.devices.forEach(opts => {
global.devices.push(new Device(opts));
});
}
/* create subscriptions array */
const subscriptions = [];
global.devices.forEach(device => {
device.data.custom_data.mqtt.forEach(mqtt => {
const {instance, state: topic} = mqtt;
if (instance != undefined && topic != undefined) {
subscriptions.push({deviceId: device.data.id, instance, topic});
}
});
});
/* Create MQTT client (variable) in global */
global.mqttClient = mqtt.connect(`mqtt://${config.mqtt.host}`, {
port: config.mqtt.port,
username: config.mqtt.user,
password: config.mqtt.password
}).on('connect', () => { /* on connect event handler */
mqttClient.subscribe(subscriptions.map(pair => pair.topic));
}).on('offline', () => { /* on offline event handler */
/* */
}).on('message', (topic, message) => { /* on get message event handler */
const subscription = subscriptions.find(sub => topic.toLowerCase() === sub.topic.toLowerCase());
if (subscription == undefined) return;
const {deviceId, instance} = subscription;
const ldevice = global.devices.find(d => d.data.id == deviceId);
ldevice.updateState(`${message}`, instance);
/* Make Request to Yandex Dialog notification API */
Promise.all(config.notification.map(el => {
let {skill_id, oauth_token, user_id} = el;
return new Promise((resolve, reject) => {
let req = https.request({
hostname: 'dialogs.yandex.net',
port: 443,
path: `/api/v1/skills/${skill_id}/callback/state`,
method: 'POST',
headers: {
'Content-Type': `application/json`,
'Authorization': `OAuth ${oauth_token}`
}
}, res => {
res.on('data', d => {
global.logger.log('info', {message: `${d}`});
});
});
req.on('error', error => {
global.logger.log('error', {message: `${error}`});
});
let {id, capabilities, properties} = ldevice.getState();
req.write(JSON.stringify({
"ts": Math.floor(Date.now() / 1000),
"payload": {
"user_id": `${user_id}`,
"devices": [{
id,
capabilities: capabilities.filter(c => c.state.instance == instance),
properties: properties.filter(p => p.state.instance == instance)
}],
}
}));
req.end();
resolve(true);
});
}));
/* */
});
module.exports = app;