-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.js
621 lines (548 loc) · 18.9 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"use strict";
// you have to require the utils module and call adapter function
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
// for communication
const axios = require('axios');
const min_polling_interval = 60; // minimum polling interval in seconds
const trigger_poll_state = 'trigger_poll'; // state for triggering a poll
// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.google-sharedlocations.0
const adapter = new utils.adapter('google-sharedlocations');
let google_polling_interval_id = null;
let google_cookie_header;
// triggered when the adapter is installed
adapter.on('install', function () {
// create connection variable https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#infoconnection
});
// is called when the adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
try {
if (google_polling_interval_id) {
clearTimeout(google_polling_interval_id);
}
callback();
} catch (e) {
callback(e);
}
});
// is called if a subscribed object changes
adapter.on('objectChange', function (id, obj) {
// Warning, obj can be null if it was deleted
//adapter.log.debug('objectChange ' + id + ' ' + JSON.stringify(obj));
});
// is called if a subscribed state changes
adapter.on('stateChange', function (id, state) {
if (state && !state.ack) {
// a poll is triggered
if (id && state && id === 'google-sharedlocations.' + adapter.instance + '.' + trigger_poll_state && state.val === true) {
adapter.log.debug('Poll triggered by user.');
querySharedLocations();
adapter.setState(trigger_poll_state, false, false)
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', function () {
// start main function
main();
});
// messages
adapter.on('message', async function (obj) {
let wait = false;
let credentials;
async function DBUsersToSendTo() {
const ids = [];
try {
// get users
const states = await adapter.getStatesAsync('google-sharedlocations.' + adapter.instance + '.user.*');
for (const stateId of Object.keys(states)) {
if (stateId.endsWith('.id')) {
const parts = stateId.split('.');
ids.push(parts[parts.length - 2]);
}
}
// get photo urls
const res = [];
for (const id of ids) {
res.push({
"id": id,
"photoURL": states['google-sharedlocations.' + adapter.instance + '.user.' + id + '.photoURL'].val,
"name": states['google-sharedlocations.' + adapter.instance + '.user.' + id + '.name'].val
});
}
return res;
} catch (err) {
adapter.log.error('Error during setting states: ' + err);
return [];
}
}
if (obj) {
switch (obj.command) {
case 'checkConnection': {
const cookie = obj.message.cookie;
if (cookie) {
google_cookie_header = cookie;
}
try {
const result = await getSharedLocations();
adapter.sendTo(obj.from, obj.command, result ? true : false, obj.callback);
} catch (err) {
adapter.sendTo(obj.from, obj.command, false, obj.callback);
}
break;
}
case 'triggerPoll': {
await querySharedLocations();
adapter.sendTo(obj.from, obj.command, err, obj.callback);
break;
}
case 'getUsers': {
const cookie = obj.message.cookie;
if (cookie) {
google_cookie_header = cookie;
}
await querySharedLocations();
const res = await DBUsersToSendTo();
adapter.sendTo(obj.from, obj.command, res, obj.callback);
break;
}
case 'getUsersFromDB': {
// get users
const res = await DBUsersToSendTo();
adapter.sendTo(obj.from, obj.command, res, obj.callback);
break;
}
default: {
adapter.log.warn("Unknown command: " + obj.command);
if (obj.callback) {
adapter.sendTo(obj.from, obj.command, obj.message, obj.callback);
}
break;
}
}
}
return true;
});
// synchronize config
async function syncConfig() {
//retrieve iobroker states of this adapter:
const states = await adapter.getStatesAsync('google-sharedlocations.' + adapter.instance + '.fence.*');
function stateInConfig(stateId) {
let fences = adapter.config.fences;
for (let j = 0; j < fences.length; j++) {
if ('google-sharedlocations.' + adapter.instance + '.fence.' + fences[j].fenceid === stateId) {
return true;
}
}
return false;
}
function stateInDB(stateId) {
return !!states[stateId];
}
// check if there are states that have to be removed
for (const stateId of Object.keys(states)) {
if (!stateInConfig(stateId)) {
await adapter.delObjectAsync(stateId);
}
}
let fences = adapter.config.fences;
// create missing states
for (let i = 0; i < fences.length; i++) {
const inDB = await stateInDB('google-sharedlocations.' + adapter.instance + '.fence.' + fences[i].fenceid);
if (!inDB) {
// set all states to false at the beginning and create them if they do not exist
await setStateEx('fence.' + fences[i].fenceid, {
common: {
name: fences[i].description,
desc: 'Fence for user ' + fences[i].userid,
type: 'boolean',
role: 'indicator',
def: false,
read: true,
write: false
}
}, false, true);
}
}
}
async function poll(onlyCookie) {
try {
const state = await adapter.getStateAsync('info.augmented_cookie');
if (state && state.val) {
google_cookie_header = state.val; //read cookie header from state.
}
if (onlyCookie || Date.now() - state.ts >= 24 * 60 * 60 * 1000) {
adapter.log.debug('Need to augment cookie.');
await improveCookie();
await improveCookie();
await adapter.setStateAsync('info.augmented_cookie', google_cookie_header, true);
}
} catch (e) {
adapter.log.warn('Error during cookie augmentation: ' + err);
}
if (!onlyCookie) {
try {
adapter.log.debug('Polling locations.');
await querySharedLocations();
} catch (err) {
adapter.log.warn('Error during poll: ' + err);
}
}
google_polling_interval_id = setTimeout(poll, onlyCookie ? 24 * 60 * 60 * 1000 //24h or pollinterval.
: Number(adapter.config.google_polling_interval) * 1000)
}
// main function
async function main() {
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// adapter.config:
adapter.log.info('Starting google shared locations adapter');
//TODO: maybe do that, too, in order to extend cookie:
// https://github.com/costastf/locationsharinglib/blob/master/locationsharinglib/locationsharinglib.py#L105
// i.e. get account URL and store cookies from that?
// sync config
await syncConfig();
// check polling interval
if (Number(adapter.config.google_polling_interval) < min_polling_interval && Number(adapter.config.google_polling_interval) !== 0) {
adapter.log.info('Configured poll interval of ' + adapter.config.google_polling_interval + 's smaller than minimum poll interval of ' + min_polling_interval + 's, will increase it to prevent 429 errors.');
adapter.config.google_polling_interval = min_polling_interval;
}
if(adapter.config.google_cookie) {
google_cookie_header = adapter.config.google_cookie.replace('Cookie: ', '');
poll(true);
} else {
adapter.log.warn('No cookie. Please set cookie in config.');
}
if (Number(adapter.config.google_polling_interval) === 0) {
// query locations is triggered only
adapter.log.info('Polling disabled, enable cookie refresh only.');
poll(true);
} else {
// first connect and query
// connect to Google
adapter.log.debug('Polling location every ' + adapter.config.google_polling_interval + 's.');
// enable polling
poll(false);
}
// subscribe
adapter.subscribeStates(trigger_poll_state);
//adapter.subscribeStates('fence.*');
}
// get locations
async function querySharedLocations() {
try {
const userobjarr = await getSharedLocations();
if (userobjarr) {
// notify places adapter
await notifyPlaces(userobjarr);
// check fences
await checkFences(userobjarr);
await updateStates(userobjarr);
adapter.setState('info.connection', true, true);
} else {
adapter.setState('info.connection', false, true);
}
} catch (err) {
adapter.log.error('An error occurred during polling the locations: ' + err.stack);
adapter.setState('info.connection', false, true);
}
}
// update states
async function updateStates(userobjarr) {
if(userobjarr) {
for(let i=0;i<userobjarr.length;i++) {
// go through users
for(let cprop in userobjarr[i]) {
// we have a user, create the group
let username = '';
if (userobjarr[i].hasOwnProperty('name') && userobjarr[i]['name']) username = userobjarr[i]['name'];
let obj = {
"_id": "user." + userobjarr[i].id,
"type": "device",
"common": {
"name": username
},
"native": {}
};
await adapter.setObjectNotExistsAsync('user.' + userobjarr[i].id, obj);
if(userobjarr[i].hasOwnProperty(cprop)) {
// cur properties
let cid = 'user.' + userobjarr[i].id + '.' + cprop;
let crole = 'state'; // default role
let cunit = ''; // default unit
switch(typeof userobjarr[i][cprop]) {
case 'number':
switch(cprop) {
case 'lat':
crole = 'value.gps.latitude';
break;
case 'long':
crole = 'value.gps.longitude';
break;
case 'battery':
crole = 'value.battery';
cunit = '%';
break;
case 'accuracy':
crole = 'value.gps.accuracy';
cunit = 'm';
break;
case 'timestamp':
crole = 'date';
break;
default:
crole = 'value';
}
await setStateEx(cid, {
common: {
name: cprop,
desc: '',
type: 'number',
role: crole,
unit: cunit,
read: true,
write: false
}
}, userobjarr[i][cprop], true);
break;
case 'string':
switch(cprop) {
case 'photoURL':
crole = 'text.url';
break;
case 'address':
crole = 'location';
break;
default:
crole = 'text';
}
await setStateEx(cid, {
common: {
name: cprop,
desc: '',
type: 'string',
role: crole,
read: true,
write: false
}
}, userobjarr[i][cprop], true);
break;
case 'boolean':
await setStateEx(cid, {
common: {
name: cprop,
desc: '',
type: 'boolean',
role: 'indicator',
def: false,
read: true,
write: false
}
}, userobjarr[i][cprop], true);
break;
}
}
}
}
}
}
// notify places adapter
async function notifyPlaces(userobjarr) {
let places = adapter.config.places_adapter;
if (places && places !== '') {
// go through all users
for(let j=0;j<userobjarr.length;j++) {
let cuser = userobjarr[j];
// send message to places adapter
await adapter.sendToAsync(
places, {
user: cuser.name,
latitude: cuser.lat,
longitude: cuser.long,
timestamp: Date.now(),
address: cuser.address
});
}
}
}
// check fences
async function checkFences(userobjarr) {
adapter.log.debug('Checking fences.');
let fences = adapter.config.fences;
// check fences
for(let i=0;i<fences.length;i++) {
let cfence = fences[i];
// go through all users in the received structure
for(let j=0;j<userobjarr.length;j++) {
let cuser = userobjarr[j];
// check user
if(cuser.id === cfence.userid) {
// calc distance
let curdist = haversine(cuser.lat, cuser.long, Number(cfence.center_lat), Number(cfence.center_long));
let cstate = curdist <= cfence.radius;
await adapter.setStateAsync('fence.' + cfence.fenceid, cstate, true);
break;
}
}
}
}
// setStateEx
async function setStateEx(id, common, val, ack) {
let a = {
type: 'state',
native: {}
};
let common_full = Object.assign({}, a, common);
try {
await adapter.setObjectNotExistsAsync(id, common_full);
await adapter.setStateAsync(id, val, ack);
} catch (err) {
adapter.log.warn(`Could not update state ${id} because: ${err}`);
}
}
//improve header from server response:
function augmentCookie(current, headers) {
if (headers['set-cookie'] && headers['set-cookie'].length) {
adapter.log.debug('New header received.');
const cookies = google_cookie_header.split('; ').map(c => c.split('='));
//split old cookie and new cookie. Update single values.
for (const header of headers['set-cookie']) {
const incomingCookies = header.split('; ');
for (const cookie of incomingCookies) {
const [name, value] = cookie.split('=');
const cIndex = cookies.findIndex(c => c[0] === name);
if (cIndex < 0) {
cookies.push([name, value]); //add
} else {
cookies[cIndex][1] = value; //update
}
}
}
google_cookie_header = cookies.map(cv => cv.join("=")).join("; ");
}
}
/**
* Tries to improve user cookie by logging in to user home first.
* @returns {Promise<void>}
*/
async function improveCookie() {
//see https://github.com/costastf/locationsharinglib/blob/master/locationsharinglib/locationsharinglib.py#L105
let options_map = {
url: "https://myaccount.google.com/?hl=en",
headers: {
"Cookie": google_cookie_header
},
method: "get"
};
try {
const response = await axios(options_map);
if (response.status !== 200) {
adapter.log.error('Failed getting locations: ' + response.status);
} else {
augmentCookie(google_cookie_header, response.headers);
}
} catch (err) {
adapter.log.error(err);
adapter.log.info('Connection to google maps failure.');
return false;
}
}
// query google shared locations
async function getSharedLocations() {
//see https://github.com/costastf/locationsharinglib/blob/master/locationsharinglib/locationsharinglib.py#L148
let options_map = {
url: "https://www.google.com/maps/rpc/locationsharing/read",
headers: {
"Cookie": google_cookie_header
},
method: "get",
params: {
"authuser": 2,
"hl": "en",
"gl": "us",
//pb is place on map. Is irrelevant, set to google head quarters here.
"pb": "!1m7!8m6!1m3!1i14!2i8413!3i5385!2i6!3x4095!2m3!1e0!2sm!3i407105169!3m7!2sen!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e1!5m4!1e4!8m2!1e0!1e1!6m9!1e12!2i2!26m1!4b1!30m1!1f1.3953487873077393!39b1!44e1!50e0!23i4111425"
}
};
try {
const response = await axios(options_map);
// connection successful
adapter.log.debug('Response: ' + response.status);
// connection established but auth failure
if (response.status !== 200) {
adapter.log.error('Failed getting locations: ' + response.status + ' - ' + response.data);
} else {
//save new cookie infos:
augmentCookie(google_cookie_header, response.headers);
try {
// parse and save user locations
const locationdata = JSON.parse(response.data.split('\n').slice(1, -1).join(''));
const userobjarr = parseLocationData(locationdata);
return userobjarr;
} catch (e) {
adapter.log.error('Could not parse location data. Probably authentication error. Please check cookie.');
return false;
}
}
} catch (err) {
adapter.log.error(err);
adapter.log.info('Connection to google maps failure.');
return false;
}
}
// parse the retrieved location data
function parseLocationData(locationdata) {
// shared location data is contained in the first element
const perlocarr = locationdata[0];
const userdataobjarr = [];
if(perlocarr && perlocarr.length > 0) {
for(const perloc of perlocarr) {
const obj = extractUserLocationData(perloc);
userdataobjarr.push(obj);
}
} else {
throw new Error('No location data in response. Cookie expired or no users share their location with you.');
adapter.log.debug('No location data: ' + JSON.stringify(locationdata, null, 2));
}
return userdataobjarr;
}
// get user date and create states form
function extractUserLocationData(userdata) {
let userdataobj = {
"id": undefined,
"photoURL": undefined,
"name": undefined,
"lat": undefined,
"long": undefined,
"address": undefined,
"battery": undefined,
"timestamp": undefined,
"accuracy": undefined
};
if(userdata && Array.isArray(userdata)) {
// userdata present
if(userdata[0] && userdata[0][0]) userdataobj['id'] = userdata[0][0];
if(userdata[0] && userdata[0][1]) userdataobj['photoURL'] = userdata[0][1];
if(userdata[0] && userdata[0][3]) userdataobj['name'] = userdata[0][3];
if(userdata[1] && userdata[1][1] && userdata[1][1][2]) userdataobj['lat'] = userdata[1][1][2];
if(userdata[1] && userdata[1][1] && userdata[1][1][1]) userdataobj['long'] = userdata[1][1][1];
if(userdata[1] && userdata[1][4]) userdataobj['address'] = userdata[1][4];
if(userdata[13] && userdata[13][1]) userdataobj['battery'] = userdata[13][1];
if(userdata[1] && userdata[1][2]) userdataobj['timestamp'] = userdata[1][2];
if(userdata[1] && userdata[1][3]) userdataobj['accuracy'] = userdata[1][3];
}
return userdataobj;
}
// latitude and longitude in degree decimal notation
function haversine(deg_lat1, deg_lon1, deg_lat2, deg_lon2) {
let lat1 = deg_lat1/180*Math.PI;
let lon1 = deg_lon1/180*Math.PI;
let lat2 = deg_lat2/180*Math.PI;
let lon2 = deg_lon2/180*Math.PI;
const R = 6372.8;
let dLat = lat2 - lat1;
let dLon = lon2 - lon1;
let a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon /2);
return 2.0 * R * Math.asin(Math.sqrt(a)) * 1000;
}