/
index.js
576 lines (466 loc) Β· 15.8 KB
/
index.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
const puppeteer = require('puppeteer');
const _ = require('lodash');
const { env } = require('./env');
const { appendJson } = require('./jsonfile');
const { msg } = require('console-msgs');
const { getBrowser, getIframe, screenshot, setValue, type, getText, click, goto, } = require('./ppt'); // prettier-ignore
const selectors = {
username: '[id="ctl00_ContentPlaceHolder1_loginform_txtUserName"]',
password: '[name="txtPassword"]',
loginSubmit: '[name="ctl00$ContentPlaceHolder1$loginform$signInButton"]',
twoFactorConfirm: '.two-factor-intro',
twoFactorSkip: 'button[type="cancel"]',
sap_dropdown: '.system-select .dropdown-toggle',
dropdown_menu: 'body > .popover-menu.ember-view',
dropdown_saps_list: 'div.content > ul > li > div > a',
};
const navigationIds = {
Settings: 1169,
Settings_MonitoringStation: 22,
Users: 'users',
SettingsURL: 'https://www.alarm.com/web/system/settings',
Settings_MonitoringStationURL:
'https://www.alarm.com/web/Profile/MonitoringStation/MonitoringStation.aspx',
UsersURL: 'https://www.alarm.com/web/system/users',
};
async function run() {
if (![2, 3].includes(process.argv.length)) {
return die.say('INVALID NUMBER OF ARGUMENTS');
}
const debug = false;
const { page } = await getBrowser(debug);
if (debug) {
await openAlarm(page);
} else {
await loginAlram(page);
}
if (process.argv.length === 2) {
await doAllSaps(page);
// await doStore({page, sap_index: 10});
// await doStore({page, sap_index: 28});
// await doStore({page, sap_index: 20});
} else if (process.argv.length === 3) {
await doStore({ page, sap_name: process.argv.pop(2), sap_count: 1 });
}
msg.step('ALL DONE!!!');
await page.close();
// await browser.close();
return process.exit();
}
/** @param {puppeteer.Page} page */
async function doAllSaps(page) {
const sap_count = await getAllSaps(page);
for (let sap_index = 0; sap_index < sap_count; sap_index++) {
await doStore({ page, sap_index, sap_count });
}
}
async function doStore({ page, sap_index, sap_name, sap_count }) {
await selectSap({ page, sap_index, sap_name });
msg.step(env.G_SAP + ': ' + (Number(sap_index) + 1) + '/' + sap_count);
await getUsers(page);
await getNotifications(page);
await getSettings(page);
}
/*
|-----------------------------------------------------------------------
|
| SETTINGS MODULE
|
|-----------------------------------------------------------------------
| */
/** @param {puppeteer.Page} page */
async function getSettings(page) {
msg.step('SETTINGS MODULE');
// await openNavigationLink(page, navigationIds.Settings);
// try {
// await openNavigationLink(
// page,
// navigationIds.Settings_MonitoringStation,
// 5000,
// );
// // await goto(page, navigationIds.Settings_MonitoringStationURL);
// } catch (error) {
// screenshot(page);
// msg.error('MONITORING STATION NOT FOUND - PROTECTION 1?');
// return;
// }
/** @var {puppeteer.Frame} frame */
let frame;
await goto(page, navigationIds.Settings_MonitoringStationURL);
try {
frame = await getIframe(
page,
'/web/Profile/MonitoringStation/MonitoringStation.aspx',
);
} catch (error) {
await screenshot(page);
msg.error('MONITORING STATION NOT FOUND - PROTECTION 1?');
return;
}
let ContactRows = await getContactRows();
const Contacts = [];
if (ContactRows && ContactRows.length) {
for (const row of ContactRows) {
const data = {
FirstName: await getText(frame, row, '#txtFirstName', 'value'),
LastName: await getText(frame, row, '#txtLastName', 'value'),
PinCode: await getText(frame, row, '#txtPinCode', 'value'),
Contact: await getText(frame, row, '.phone-number'),
Order: await getText(frame, row, '[name="ddlOrder"]', 'value'),
};
Contacts.push(data);
msg.info('getSettings -> FirstName', data.FirstName);
}
}
appendJson('Monitoring', Contacts);
async function getContactRows() {
try {
await frame.waitForSelector(
'.emergency-contact-rows>.emergency-contact-row',
{ timeout: 10000 },
);
let ContactRows = await frame.$$(
'.emergency-contact-rows>.emergency-contact-row',
);
msg.substep('getContactRows -> ContactRows ' + ContactRows.length);
return ContactRows;
} catch (error) {
msg.error('No users found in Settings->Monitoring --- Brinks???');
return null;
}
}
}
/*
|-----------------------------------------------------------------------
|
| USERS MODULE
|
|-----------------------------------------------------------------------
| */
/** @param {puppeteer.Page} page */
async function getUsers(page) {
msg.step('USERS MODULE');
await openNavigationLink(page, navigationIds.Users);
// await goto(page, navigationIds.UsersURL);
let users = await getUserRows(page);
msg.substep('getUserRows ' + users.length);
for (let index = 0; index < users.length; index++) {
let users = await getUserRows(page);
// msg.substep('getUsers ' + (index + 1) + '/' + users.length);
await selectPage(users, index);
if (await userDetailsExists()) {
await saveThisPage(index);
}
await page.goBack();
}
async function userDetailsExists() {
return (await page.$('.user-information .display-name')) !== null;
}
async function selectPage(users, r) {
users[r].click();
await page.waitForNavigation({ waitUntil: 'networkidle0' });
await page.waitForSelector('.user-information');
}
async function saveThisPage(index) {
const { UserName, UserPinBadge } = await getUserInfo();
if (UserName) {
let Contacts = [];
let contactRows = await countContactRows();
if (contactRows.length) {
await page.waitForSelector('.contact-information');
Contacts = await page.evaluate(() => {
return Array.from(document.querySelectorAll('.contact-information'))
.filter(cont => !!cont.querySelector('.svg-sms'))
.map(cont => cont.querySelector('.description-right')?.textContent)
.filter(text => text);
});
// for (let index = 0; index < contactRows.length; index++) {
// const element = contactRows[index];
// await page.waitForSelector(
// '.sub-description:nth-child(' + (index + 1) + ')',
// );
// console.log('saveThisPage -> nth-child', index);
// const address = await getText(page, element, '.sub-description');
// if (!address) throw 'NO ADDRESS';
// Contacts.push(address);
// }
// for (const r of contactRows) {
// await page.waitForSelector('.sub-description');
// // const address = await page.evaluate(
// // element =>
// // element.querySelector('.sub-description').textContent.trim(),
// // r,
// // );
// const address = await getText(page, r, '.sub-description');
// console.log('saveThisPage -> address', address);
// if (!address) throw 'NO ADDRESS';
// Contacts.push(address);
// }
}
const json = { UserName, Contacts, Pin: UserPinBadge };
appendJson('Users.' + index, json);
}
}
async function countContactRows() {
let ContactRows = await page.$$('.contact-address');
return ContactRows;
}
async function getUserInfo() {
const UserName = await getText(page, page, '.display-name');
msg.info('getUsers -> UserName', UserName);
let UserPinBadge = '';
const UserPinBadgeSelector = await page.$('.user-pin-badge span');
if (UserPinBadgeSelector) {
UserPinBadge = await getText(page, page, '.user-pin-badge span');
} else {
msg.error('no UserPinBadge');
}
return { UserName, UserPinBadge };
}
async function getUserRows(page) {
try {
await page.waitForSelector('.list-row-content .access-summary-badge');
} catch (error) {
msg.die('Cannot get userRow', await page.url());
}
let UserRows = await page.$$('.list-row-content .access-summary-badge');
return UserRows;
}
}
/*
|-----------------------------------------------------------------------
|
| NOTIFICATIONS MODULE
|
|-----------------------------------------------------------------------
| */
/** @param {puppeteer.Page} page */
async function getNotifications(page) {
msg.step('NOTIFICATIONS MODULE');
await openNotificationsPage(page);
const frame = await getNotificationsFrame();
if (!frame) {
throw 'NO FRAME FOUND';
}
const length = await getNotificationsLength();
msg.substep('getNotificationsLength', length);
for (let index = 0; index < length; index++) {
// msg.substep('openNotificationItem ' + (index + 1) + '/' + length);
let Notification = await openNotificationItem(frame, index);
if (Notification) {
await writeNotificationContacts(Notification, index);
await page.goBack();
}
}
async function writeNotificationContacts(Notification, index) {
await frame.waitForSelector('#addRecipientBtnWrap');
await frame.waitForSelector('.recipientsPanel');
let rows = await frame.$$('.recipientsPanel .contact.highlight-row');
const contacts = [];
if (rows.length) {
for (const r of rows) {
contacts.push({
NotificationName: Notification.name,
NotificationStatus: Notification.status,
Name: await getText(frame, r, '.contact-name'),
Address: await getText(frame, r, '.contact-address'),
});
}
} else {
contacts.push({
NotificationName: Notification.name,
NotificationStatus: Notification.status,
});
}
appendJson('Notifications.' + index, contacts);
}
async function openNotificationItem(frame, itemNumber) {
await frame.waitForSelector('.notifications-div');
const notification = await frame.evaluate(itemNumber => {
const rows = document.querySelectorAll(
'.notifications-div .notification.highlight-row',
);
const row = rows[itemNumber];
const edit = row.querySelector('.edit-notification');
const name = row.querySelector('.name').textContent;
const status =
row.querySelector('.notification-status').textContent.trim() ||
(row.querySelector('.notification-status .switch-on') && 'On') ||
(row.querySelector('.notification-status .switch-off') && 'Off') ||
'N/A';
if (status === 'Create') {
return { name, error: 'status=create' };
} else if (edit) {
edit.click();
return { name, status };
} else {
return { name, error: 'not editable' };
}
}, itemNumber);
if (_.has(notification, 'error')) {
msg.error(`${notification.name} ${notification.error}`);
return null;
}
await frame.waitForNavigation();
msg.info('writeNotificationContacts -> NotificationName', notification);
return notification;
}
async function getNotificationsLength() {
return await frame.evaluate(() => {
return document.querySelectorAll('.notifications-div>div').length;
});
}
async function getNotificationsFrame() {
const frameSrc = '/web/Notifications/NotificationsNew.aspx';
return await getIframe(page, frameSrc);
}
async function openNotificationsPage(page) {
// WE NEED NETWORK IDLE 0 BECAUSE OF IFRAME
await goto(
page,
'https://www.alarm.com/web/Notifications/NotificationsNew.aspx',
);
}
}
/*
|-----------------------------------------------------------------------
|
| ALARM HELPERS
|
|-----------------------------------------------------------------------
| */
/** @param {puppeteer.Page} page */
async function getAllSaps(page) {
await openSapDropdown(page);
const all_saps = await page.$$(selectors.dropdown_saps_list);
const sap_count = all_saps.length;
return sap_count;
}
async function selectSap({ page, sap_index, sap_name }) {
if (!sap_index && sap_index !== 0 && !sap_name)
msg.die('INVALID ARGUMENTS IN selectSapNum');
await openSapDropdown(page);
const sap = sap_name
? await getSapByName({ page, sap_name })
: await getSapByIndex({ page, sap_index });
env.G_SAP = sap.trim().replace('.', ' ').trim();
await page.waitForNavigation();
async function getSapByName({ page, sap_name }) {
const all_saps = await page.$$(selectors.dropdown_saps_list);
for (row of all_saps) {
const text = await page.evaluate(el => el.textContent, row);
if (String(text).toLowerCase().includes(String(sap_name).toLowerCase())) {
row.click();
return text;
}
}
msg.die('NO SUCH SAP FOUND');
}
async function getSapByIndex({ page, sap_index }) {
// SELECT AND GET SAP
const params = { sap_index };
params['selector'] = selectors.dropdown_saps_list;
return await page.evaluate(p => {
const sap_item = document.querySelectorAll(p.selector)[p.sap_index];
sap_item.click();
return sap_item.innerText;
}, params);
}
}
/** @param {puppeteer.Page} page */
async function openSapDropdown(page) {
if (!(await page.$(selectors.dropdown_menu))) {
// OPEN DROPDOWN
await click(page, selectors.sap_dropdown);
// WAIT FOR DROPDOWN UI UPDATE
await page.waitForSelector(selectors.dropdown_saps_list);
}
}
/** @param {puppeteer.Page} page */
async function openNavigationLink(page, module, timeout = 60000) {
msg.substep('openNavigationLink', module);
try {
const selector = navigationLinkSelector(module);
await page.waitForSelector(selector, { timeout });
await page.click(selector);
} catch (error) {
await screenshot(page);
throw new Error('Cannot openNavigationLink ' + module);
}
}
function navigationLinkSelector(module) {
return `[route-id="${module}"] a`;
}
/** @param {puppeteer.Page} page */
async function openAlarm(page) {
msg.step('openAlarm');
// await loginAlram(page);
await goto(page, 'https://www.alarm.com/web/system/home');
}
/** @param {puppeteer.Page} page */
async function loginAlram(page) {
msg.step('loginAlram');
// await screenshot(page);
await goto(page, 'https://www.alarm.com/login.aspx');
await page.waitForSelector(selectors.loginSubmit);
await setValue(page, selectors.username, env.username);
await setValue(page, selectors.password, env.password);
await click(page, selectors.loginSubmit);
await handle2FA(page);
}
/** @param {puppeteer.Page} page */
async function handle2FA(page) {
try {
await page.waitForNavigation({
waitUntil: 'networkidle0',
timeout: 10 * 1000,
});
} catch (error) {
console.log(`π > networkidle0`);
}
try {
await page.waitForSelector(selectors.twoFactorSkip);
msg.substep(`handle2FA`);
} catch (error) {
msg.info(`π > NOOOOO 2FA`, await page.url());
// await writeHtmlAndDie(page);
return openHome(page);
}
try {
await click(page, selectors.twoFactorSkip);
} catch (error) {
console.log(`π > error`, typeof error, error);
msg.die(`π > COULD NOT THWART 2FA: LAYOUT CHANGED???`, await page.url());
}
await openHome(page);
}
async function openHome(page) {
try {
await page.waitForSelector(selectors.sap_dropdown);
} catch (error) {
await goto(page, 'https://www.alarm.com/web/system/home');
}
try {
await page.waitForSelector(selectors.sap_dropdown);
} catch (error) {
msg.die(`π > COULD NOT THWART 2FA: NOT LOGGED IN`, await page.url());
}
}
async function writeHtmlAndDie(page) {
await screenshot(page);
const html = await page.evaluate(
'new XMLSerializer().serializeToString(document.doctype) + document.documentElement.outerHTML',
);
console.log(html.replace(/\s+/gm, ' '));
const fs = require('fs');
fs.writeFileSync('html', html);
process.exit();
}
/*
|-----------------------------------------------------------------------
|
| RUN
|
|-----------------------------------------------------------------------
| */
run();