-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadlink-webhooks.js
1735 lines (1432 loc) · 116 KB
/
broadlink-webhooks.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
const {Builder, By, Key, until} = require('selenium-webdriver'); // https://www.npmjs.com/package/selenium-webdriver
const prompts = require('prompts'); // https://www.npmjs.com/package/prompts
const sanitizeFilename = require('sanitize-filename'); // https://www.npmjs.com/package/sanitize-filename
// The following requirements are included in selenium-webdriver:
const seleniumFirefoxOptions = require('selenium-webdriver/firefox').Options;
const seleniumChromeOptions = require('selenium-webdriver/chrome').Options;
// The following requirements are included in Node.js:
const homeDir = require('os').homedir();
const pathJoin = require('path').join;
const {existsSync, readFileSync, writeFileSync, mkdirSync} = require('fs');
const {exec, execSync, spawnSync} = require('child_process');
// Adjustable Settings (but should not need to be adjusted unless something isn't working properly):
const debugLogging = false;
const defaultBrowserWindowSize = {width: 690, height: 1000}; // Only used for Firefox and Chrome when not Headless.
const maxTaskAttempts = 3; // Number of times tasks will be attempted if they fail, such as logging in, retrieving Webhooks key, retrieving devices and scenes, and setting up an Applet, etc.
const longWaitForElementTime = 10000; // Generally used when waiting for an element which only gets one chance to show up.
const shortWaitForElementTime = 100; // Generally used when waiting for an element inside a loop with which is given many chances to show up.
const waitForNextPageSleepInLoopTime = 100;
// The next two variables help prevent getting caught in a infinite loop if the page doesn't get updated properly.
const maxButtonClicksCount = 100;
const maxIterationsOnPageAfterButtonNoLongerExists = 100;
// INTERNAL SETTINGS - DO NOT EDIT:
// Values for tasks:
const taskCreateApplets = 'Create Webhooks Applets';
const taskArchiveAppletsNotInBroadLink = 'Archive Webhooks Applets Not in BroadLink';
const taskArchiveApplets = 'Archive Webhooks Applets';
const taskOutputSummary = 'Output Summary';
const taskGenerateHomebridgeIFTTTconfig = 'Generate homebridge-ifttt Configuration';
const taskGenerateHomebridgeHTTPconfig = 'Generate homebridge-http-switch Configuration';
const taskGenerateJSON = 'Generate JSON Details';
const taskOpenEditAppletURLs = 'Open Edit Applet URLs';
const taskOpenGitHubPage = 'Open "broadlink-webhooks" on GitHub';
// Values for BroadLink/Applet group choices:
const groupDevicesAndScenes = 'Devices and Scenes';
const groupDevicesOnly = 'Devices Only';
const groupScenesOnly = 'Scenes Only';
// Values for multiple option questions:
const optionChange = 'change';
const optionQuit = 'quit';
let webDriver = null;
let browserToAutomate = null;
(async function broadlink_webhooks() {
console.info('\nbroadlink-webhooks: Create and Manage IFTTT Webhooks Applets for BroadLink');
try {
let versionFromPackageJson = JSON.parse(readFileSync(`${__dirname}/package.json`)).version;
if (versionFromPackageJson) {
console.info(`Version ${versionFromPackageJson}\n`);
} else {
throw 'NO VERSION KEY';
}
} catch (retrieveVersionErrr) {
console.info(''); // Just for a line break if version retrieval fails.
}
let userQuit = false;
try {
let lastIFTTTusernameUsed = null;
let lastIFTTTpasswordUsed = null;
let lastBrowserToAutomate = null;
while (!userQuit) {
let browserPromptChoices = [
{title: 'Firefox (Hidden Window / Headless)', value: 'firefox-headless'},
{title: 'Firefox (Visible Window)', value: 'firefox'},
{title: '–', value: 'browserSpacer1', disabled: true},
{title: 'Chrome (Hidden Window / Headless)', value: 'chrome-headless'},
{title: 'Chrome (Visible Window)', value: 'chrome'},
{title: '–', value: 'browserSpacer2', disabled: true},
{title: 'Quit', value: optionQuit}
];
let initialBrowserChoiceSelection = 0;
if (browserToAutomate) {
for (let thisBrowserChoiceIndex = 0; thisBrowserChoiceIndex < browserPromptChoices.length; thisBrowserChoiceIndex ++) {
let thisBrowserChoice = browserPromptChoices[thisBrowserChoiceIndex];
if (browserToAutomate == thisBrowserChoice.value) {
initialBrowserChoiceSelection = thisBrowserChoiceIndex;
break;
}
}
}
let optionsPrompts = [
{
type: 'select',
name: 'browserSelection',
message: 'Choose a Web Browser to Automate (Using Selenium WebDriver):',
choices: browserPromptChoices,
initial: initialBrowserChoiceSelection
},
{
type: prev => ((prev == optionQuit) ? null : 'select'),
name: 'taskSelection',
message: 'Choose a Task:',
choices: [
{title: 'Create Webhooks Applets', description: 'No duplicates will be created for identical Webhooks Applets already created by "broadlink-webhooks".', value: taskCreateApplets},
{title: 'Archive Webhooks Applets for Renamed or Deleted Devices/Scenes in BroadLink', description: 'For renamed devices/scenes, you can re-run the "Create Webhooks Applets" task after this task is finished.', value: taskArchiveAppletsNotInBroadLink},
{title: 'Archive All Webhooks Applets Created by "broadlink-webhooks"', description: 'If you ever want the Webhooks Applets back after removing them, you can re-run the "Create Webhooks Applets" task at any time.', value: taskArchiveApplets},
{title: '–', value: 'taskSpacer1', disabled: true},
{title: 'Output Summary of Webhooks Applets Created by "broadlink-webhooks" and Devices/Scenes in BroadLink', value: taskOutputSummary},
{title: 'Generate "homebridge-ifttt" Configuration for Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful only if you use Homebridge. Visit homebridge.io to learn more.', value: taskGenerateHomebridgeIFTTTconfig},
{title: 'Generate "homebridge-http-switch" Configuration for Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful only if you use Homebridge and want more customization options than homebridge-ifttt. Visit homebridge.io to learn more.', value: taskGenerateHomebridgeHTTPconfig},
{title: 'Generate JSON Details of Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful for your own custom scripts.', value: taskGenerateJSON},
{title: 'Open All IFTTT Edit URLs for Webhooks Applets Created by "broadlink-webhooks"', description: 'Edit Applet URLs will open in your default web browser. You should be logged in to IFTTT in your default web browser before running this task.', value: taskOpenEditAppletURLs},
{title: taskOpenGitHubPage, description: 'To learn more, ask questions, make suggestions, and report issues.', value: taskOpenGitHubPage},
{title: '–', value: 'taskSpacer2', disabled: true},
{title: 'Change Web Browser Selection', value: optionChange},
{title: 'Quit', value: optionQuit}
]
},
{
type: prev => (((prev == taskOpenGitHubPage) || (prev == optionChange) || (prev == optionQuit)) ? null : 'select'),
name: 'groupSelection',
message: prev => `Which BroadLink group would you like to ${
((prev == taskCreateApplets) ? 'create Webhooks Applets for' :
((prev == taskArchiveAppletsNotInBroadLink) ? 'archive Webhooks Applets for which have been renamed or deleted in BroadLink' :
((prev == taskArchiveApplets) ? 'archive all Webhooks Applets for' :
((prev == taskOutputSummary) ? 'output summary for' :
((prev == taskGenerateHomebridgeIFTTTconfig) ? 'generate "homebridge-ifttt" configuration for' :
((prev == taskGenerateHomebridgeHTTPconfig) ? 'generate "homebridge-http-switch" configuration for' :
((prev == taskGenerateJSON) ? 'generate JSON details for' :
((prev == taskOpenEditAppletURLs) ? 'open IFTTT edit Applet URLs for' :
'DO UNKNOWN TASK TO')
)
)
)
)
)
)
)
}?`,
choices: [
{title: 'Both Devices & Scenes', value: groupDevicesAndScenes},
{title: 'Only Devices', value: groupDevicesOnly},
{title: 'Only Scenes', value: groupScenesOnly},
{title: '–', value: 'groupSpacer1', disabled: true},
{title: 'Change Web Browser and Task Selection', value: optionChange},
{title: 'Quit', value: optionQuit}
]
}
];
let optionsPromptsResponse = await prompts(optionsPrompts);
let optionsPromptsResponseValues = Object.values(optionsPromptsResponse);
if (optionsPromptsResponseValues.includes(optionQuit)) {
throw 'USER QUIT';
} else if (optionsPromptsResponseValues.includes(optionChange)) {
console.log(''); // Just for a line break before re-displaying options prompt.
continue;
} else if (optionsPromptsResponseValues.includes(taskOpenGitHubPage)) {
let gitHubRepoURL = 'https://github.com/RandomApplications/broadlink-webhooks';
try {
exec(`${((process.platform == 'darwin') ? 'open' : ((process.platform == 'win32') ? 'start' : 'xdg-open'))} ${gitHubRepoURL}`);
console.info(`\n\n${taskOpenGitHubPage}: ${gitHubRepoURL}\n\n`);
} catch (openGitHubRepoURLerror) {
console.error(`\n\nERROR OPENING "${gitHubRepoURL}": ${openGitHubRepoURLerror}\n\n`);
}
continue;
} else if (optionsPromptsResponseValues.length < optionsPrompts.length) {
throw 'CANCELED OPTIONS SELECTION';
}
browserToAutomate = optionsPromptsResponse.browserSelection;
if (lastBrowserToAutomate != browserToAutomate) {
if (webDriver) {
try {
await webDriver.quit();
} catch (quitWebDriverError) {
// Ignore any error quitting WebDriver.
}
}
lastBrowserToAutomate = browserToAutomate;
}
let needNewWebDriver = true;
let iftttLogInURL = 'https://ifttt.com/login?wp_=1';
try {
await webDriver.getCurrentUrl(); // If getCurrentUrl() fails, then WebDriver was not built yet, was quit(), or the window was probably closed, so we'll make a new one and log in.
needNewWebDriver = false;
await webDriver.get('https://ifttt.com/my_services'); // This URL will forward to https://ifttt.com/join if not logged in.
try {
await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox).
if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation');
} catch (acceptLeavePageAlertError) {
// Ignore any error if there is no Leave Page confirmation.
}
if ((await webDriver.getCurrentUrl()) == 'https://ifttt.com/join') throw 'NEED TO RE-LOG IN';
} catch (checkForLogInError) {
let logInMethodPromptResponse = await prompts([
{
type: 'select',
name: 'logInMethod',
message: 'Choose Log In Method:',
choices: [
{title: 'Log In via Command Line', description: 'Only regular IFTTT accounts are supported when logging in via command line.', value: 'logInViaCLI'},
{title: 'Log In Manually via Web Browser', description: 'To log in to IFTTT with a linked Apple, Google, or Facebook account, you must choose this option.', value: 'logInManuallyViaWebBrowser'},
{title: '–', value: 'logInMethodSpacer1', disabled: true},
{title: 'Change Web Browser and Task Selection', value: optionChange},
{title: 'Quit', value: optionQuit}
],
initial: ((lastIFTTTusernameUsed == 'loggedInManuallyViaWebBrowser') ? 1 : 0)
}
]);
let logInMethodPromptResponseValues = Object.values(logInMethodPromptResponse);
if (logInMethodPromptResponseValues.length < 1) {
throw 'CANCELED IFTTT LOG IN';
} else if (logInMethodPromptResponseValues.includes(optionChange)) {
console.log(''); // Just for a line break before re-displaying options prompt.
continue;
} else if (logInMethodPromptResponseValues.includes(optionQuit)) {
throw 'USER QUIT';
}
let logInViaCLI = (logInMethodPromptResponse.logInMethod == 'logInViaCLI');
if (!logInViaCLI && (browserToAutomate.endsWith('-headless'))) {
console.info('\nLOGGING IN MANUALLY VIA WEB BROWSER IS ONLY SUPPORTED WHEN AUTOMATING FIREFOX OR CHROME WITH A VISIBLE WINDOW\n');
let changeBrowserPromptResponse = await prompts([
{
type: 'select',
name: 'newBrowserSelection',
message: 'Change Web Browser to Automate (to Log In Manually via Web Browser):',
choices: [
{title: 'Firefox (Visible Window)', value: 'firefox'},
{title: 'Chrome (Visible Window)', value: 'chrome'},
{title: '–', value: 'changeBrowserSpacer1', disabled: true},
{title: 'Log In via Command Line Instead', description: 'Only regular IFTTT accounts are supported when logging in via command line.', value: 'logInViaCLI'},
{title: '–', value: 'changeBrowserSpacer2', disabled: true},
{title: 'Quit', value: optionQuit}
],
initial: ((browserToAutomate == 'chrome-headless') ? 1 : 0)
}
]);
let changeBrowserPromptResponseValues = Object.values(changeBrowserPromptResponse);
if (changeBrowserPromptResponseValues.length < 1) {
throw 'CANCELED IFTTT LOG IN';
} else if (changeBrowserPromptResponseValues.includes(optionQuit)) {
throw 'USER QUIT';
}
logInViaCLI = (changeBrowserPromptResponse.newBrowserSelection == 'logInViaCLI');
if (!logInViaCLI) {
browserToAutomate = changeBrowserPromptResponse.newBrowserSelection;
lastBrowserToAutomate = browserToAutomate;
needNewWebDriver = true;
}
}
let logInPrompts = [
{
type: 'text',
name: 'iftttUsername',
message: 'IFTTT Username:',
initial: ((lastIFTTTusernameUsed != 'loggedInManuallyViaWebBrowser') ? lastIFTTTusernameUsed : null),
validate: iftttUsername => ((iftttUsername == '') ? 'IFTTT Username Required' : true)
},
{
type: 'password',
name: 'iftttPassword',
message: 'IFTTT Password:',
initial: prev => ((prev == lastIFTTTusernameUsed) ? lastIFTTTpasswordUsed : null),
validate: iftttPassword => ((iftttPassword == '') ? 'IFTTT Password Required' : ((iftttPassword.length < 6) ? 'IFTTT Password Too Short' : true))
}
];
let logInPromptsResponse = null;
if (logInViaCLI) {
console.log(''); // Just for a line break before log in prompts.
logInPromptsResponse = await prompts(logInPrompts);
if (Object.keys(logInPromptsResponse).length < 2) throw 'CANCELED IFTTT LOG IN';
}
if (needNewWebDriver) {
if (webDriver) {
try {
await webDriver.quit();
} catch (quitWebDriverError) {
// Ignore any error quitting WebDriver.
}
}
let browserToAutomateParts = browserToAutomate.split('-');
let actualBrowserToAutomate = browserToAutomateParts[0];
let browserShouldBeHeadless = ((browserToAutomateParts.length > 1) && (browserToAutomateParts[1] == 'headless'));
if ((process.platform == 'darwin') && ((actualBrowserToAutomate == 'firefox') || (actualBrowserToAutomate == 'chrome'))) {
// Make sure WebDriver executable isn't quarantined on Mac (which could result in "cannot be opened because the developer cannot be verified" error).
let webDriverExecutablePath = `/usr/local/bin/${(actualBrowserToAutomate == 'firefox') ? 'gecko' : actualBrowserToAutomate}driver`;
try {
if (existsSync(webDriverExecutablePath)) {
if (spawnSync('xattr', [webDriverExecutablePath]).stdout.toString().includes('com.apple.quarantine')) {
if (debugLogging) console.debug(`DEBUG - "${webDriverExecutablePath}" IS QUARANTINED - ATTEMPTING TO REMOVE QUARANTINE XATTR`);
execSync(`xattr -d com.apple.quarantine ${webDriverExecutablePath}`);
if (debugLogging) {
if (spawnSync('xattr', [webDriverExecutablePath]).stdout.toString().includes('com.apple.quarantine')) {
console.warn(`DEBUG WARNING - "${webDriverExecutablePath}" IS STILL QUARANTINED`);
} else {
console.debug(`DEBUG - "${webDriverExecutablePath}" IS NO LONGER QUARANTINED`);
}
}
} else if (debugLogging) {
console.debug(`DEBUG - "${webDriverExecutablePath}" IS NOT QUARANTINED`);
}
}
} catch (webDriverQuarantineError) {
if (debugLogging) console.error(`DEBUG ERROR - FAILED TO CHECK OR REMOVE "${webDriverExecutablePath}" QUARANTINE - ${webDriverQuarantineError}`);
}
}
webDriver = await new Builder().forBrowser(actualBrowserToAutomate).setFirefoxOptions(
(browserShouldBeHeadless ?
new seleniumFirefoxOptions().headless().windowSize(defaultBrowserWindowSize) :
new seleniumFirefoxOptions().windowSize(defaultBrowserWindowSize))
).setChromeOptions(
(browserShouldBeHeadless ?
new seleniumChromeOptions().headless().windowSize(defaultBrowserWindowSize) :
new seleniumChromeOptions().windowSize(defaultBrowserWindowSize)
).excludeSwitches('enable-logging') // Disable excessive logging with Chrome on Windows.
).build();
}
if (logInViaCLI) {
for (let logInAttemptCount = 1; logInAttemptCount <= maxTaskAttempts; logInAttemptCount ++) {
try {
await webDriver.get(iftttLogInURL);
try {
await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox).
if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation');
} catch (acceptLeavePageAlertError) {
// Ignore any error if there is no Leave Page confirmation.
}
await check_for_server_error_page();
try {
await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Log in"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing.
await webDriver.wait(
until.elementLocated(By.id('user_username')), shortWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Entering IFTTT Username');
await thisElement.clear();
await thisElement.sendKeys(logInPromptsResponse.iftttUsername);
});
await webDriver.wait(
until.elementLocated(By.id('user_password')), shortWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Entering IFTTT Password');
await thisElement.clear();
await thisElement.sendKeys(logInPromptsResponse.iftttPassword);
});
} catch (fillLogInPageError) {
// Allow login page to error in case the user already logged in and submitted in the web browser.
}
let currentURL = await webDriver.getCurrentUrl();
while (currentURL.startsWith('https://ifttt.com/login') || currentURL == 'https://ifttt.com/session') {
if (currentURL == iftttLogInURL) {
try {
await webDriver.wait(
until.elementLocated(By.xpath('//input[@value="Log in" or @value="Signing in..."]')), shortWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Clicking Log In Button');
try {
await thisElement.click();
} catch (innerClickLogInButtonError) {
// Ignore likely stale element error and keep looping.
}
});
} catch (outerClickLogInButtonError) {
// Ignore likely error from element not existing and keep looping.
}
} else if (currentURL.startsWith('https://ifttt.com/login?email=')) {
throw 'INCORRECT IFTTT USERNAME OR PASSWORD';
} else if (currentURL == 'https://ifttt.com/session') {
try {
await webDriver.wait(
until.elementLocated(By.id('user_tfa_code')), shortWaitForElementTime // Don't wait long for TFA input since it may not exist and we want to keep looping if not.
).then(async thisElement => {
if (await thisElement.getAttribute('value') == '') { // Make sure we don't prompt again before the page has reloaded.
console.log(''); // Just for a line break before two-step code prompt.
let twoStepPromptResponse = await prompts({
type: 'text',
name: 'iftttTwoStepVerificationCode',
message: 'IFTTT Two-Step Verification Code:'
});
// Allow Two-Step Verification Code prompt to be clicked through without entering a code in case the code was already entered and submitted in the web browser.
if ((Object.keys(twoStepPromptResponse).length == 1) && (twoStepPromptResponse.iftttTwoStepVerificationCode != '')) {
if (debugLogging) console.debug('DEBUG - Entering IFTTT Two-Step Verification Code');
await thisElement.clear();
await thisElement.sendKeys(twoStepPromptResponse.iftttTwoStepVerificationCode);
}
}
});
await webDriver.wait(
until.elementLocated(By.xpath('//input[@value="Log in" or @value="Signing in..."]')), shortWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Clicking Two-Step Log In Button');
try {
await thisElement.click();
} catch (innerIftttTwoStepVerificationError) {
// Ignore likely stale element error and keep looping.
}
});
} catch (outerIftttTwoStepVerificationError) {
// Ignore likely error from element not existing and keep looping.
}
}
currentURL = await webDriver.getCurrentUrl();
await webDriver.sleep(waitForNextPageSleepInLoopTime);
}
break;
} catch (logInError) {
console.error(`\nERROR: ${logInError}`);
if (debugLogging) {
try {
console.debug(`URL=${await webDriver.getCurrentUrl()}`);
} catch (getCurrentURLerror) {
console.debug('FAILED TO GET CURRENT URL');
}
}
console.error(`\n\nERROR LOGGING IN TO IFTTT - ATTEMPT ${logInAttemptCount} OF ${maxTaskAttempts}\n\n`);
if (logInAttemptCount == maxTaskAttempts) {
throw logInError;
} else {
if (logInError.toString().includes('INCORRECT IFTTT USERNAME OR PASSWORD')) {
logInPrompts[0].initial = logInPromptsResponse.iftttUsername;
logInPromptsResponse = await prompts(logInPrompts);
if (Object.keys(logInPromptsResponse).length < 2) throw 'CANCELED IFTTT LOG IN';
}
}
}
}
lastIFTTTusernameUsed = logInPromptsResponse.iftttUsername;
lastIFTTTpasswordUsed = logInPromptsResponse.iftttPassword;
} else {
for ( ; ; ) {
try {
await webDriver.get('https://ifttt.com/my_services'); // This URL will forward to https://ifttt.com/join if not logged in.
try {
await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox).
if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation');
} catch (acceptLeavePageAlertError) {
// Ignore any error if there is no Leave Page confirmation.
}
if ((await webDriver.getCurrentUrl()) != 'https://ifttt.com/join') {
lastIFTTTusernameUsed = 'loggedInManuallyViaWebBrowser';
lastIFTTTpasswordUsed = null;
break;
} else {
await webDriver.get(iftttLogInURL);
throw 'NEED TO LOG IN';
}
} catch (checkForLogInError) {
console.log(''); // Just for a line break before confirm log in prompt.
let confirmLoggedInManuallyViaWebBrowserPromptResponse = await prompts({
type: 'toggle',
name: 'confirmLogIn',
message: 'Confirm After Logging In Manually via Web Browser:',
initial: true,
active: 'Confirm Log In',
inactive: 'Quit'
});
if ((Object.keys(confirmLoggedInManuallyViaWebBrowserPromptResponse).length == 0) || (confirmLoggedInManuallyViaWebBrowserPromptResponse.confirmLogIn == false)) {
throw 'USER QUIT';
}
}
}
}
}
let startTime = new Date();
console.info(`\nSTARTED "${optionsPromptsResponse.taskSelection}" TASK WITH "${optionsPromptsResponse.groupSelection}" ON ${startTime.toLocaleString().replace(', ', ' AT ')}`);
let iftttWebhooksKey = 'DID_NOT_RETRIEVE_IFTTT_WEBHOOKS_KEY';
if ((optionsPromptsResponse.taskSelection == taskCreateApplets) || (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeIFTTTconfig) || (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeHTTPconfig) || (optionsPromptsResponse.taskSelection == taskGenerateJSON)) {
for (let retrieveWebhooksKeyAttemptCount = 1; retrieveWebhooksKeyAttemptCount <= maxTaskAttempts; retrieveWebhooksKeyAttemptCount ++) {
try {
await webDriver.get('https://ifttt.com/maker_webhooks/settings');
try {
await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox).
if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation');
} catch (acceptLeavePageAlertError) {
// Ignore any error if there is no Leave Page confirmation.
}
await check_for_server_error_page();
if ((await webDriver.getCurrentUrl()) == 'https://ifttt.com/maker_webhooks') {
// If we got redirected, make sure that the Webhooks Service is connected.
try {
await webDriver.wait(until.elementLocated(By.xpath('//a[contains(@href,"/maker_webhooks/redirect_to_connect")]')), shortWaitForElementTime);
throw '"Webhooks" SERVICE NOT CONNECTED IN IFTTT';
} catch (webhooksServiceConnectionError) {
if (webhooksServiceConnectionError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) {
throw webhooksServiceConnectionError;
}
// Otherwise, ignore likely error from element not existing. Which means that the Webhooks Service is connected like we want.
}
}
await webDriver.wait(
until.elementLocated(By.xpath('//span[starts-with(text(),"https://maker.ifttt.com/use/")]')), longWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Retrieving IFTTT Webhooks Key');
iftttWebhooksKey = (await thisElement.getText()).replace('https://maker.ifttt.com/use/', '');
});
break;
} catch (retrieveWebhooksKeyError) {
if (retrieveWebhooksKeyError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) {
throw retrieveWebhooksKeyError; // Don't keep trying if service isn't connected.
}
console.error(`\nERROR: ${retrieveWebhooksKeyError}`);
if (debugLogging) {
try {
console.debug(`URL=${await webDriver.getCurrentUrl()}`);
} catch (getCurrentURLerror) {
console.debug('FAILED TO GET CURRENT URL');
}
}
console.error(`\n\nERROR RETRIEVING WEBHOOKS KEY - ATTEMPT ${retrieveWebhooksKeyAttemptCount} OF ${maxTaskAttempts}\n\n`);
if (retrieveWebhooksKeyAttemptCount == maxTaskAttempts) {
throw retrieveWebhooksKeyError;
}
}
}
console.info(`\nIFTTT Webhooks Key: ${iftttWebhooksKey}`);
}
console.info('\nDetecting Existing Webhooks Applets...');
let existingWebhooksBroadLinkAppletIDsAndNames = {};
let allowedWebhooksBroadLinkAppletNamePrefixes = [];
if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupDevicesOnly)) {
allowedWebhooksBroadLinkAppletNamePrefixes = ['Webhooks Event: BroadLink-On', 'Webhooks Event: BroadLink-Off'];
}
if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupScenesOnly)) {
allowedWebhooksBroadLinkAppletNamePrefixes.push('Webhooks Event: BroadLink-Scene');
}
for (let retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount = 1; retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount <= maxTaskAttempts; retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount ++) {
try {
let totalBroadLinkAppletsDetected = 0;
let existingWebhooksBroadLinkOnAppletsCount = 0;
let existingWebhooksBroadLinkOffAppletsCount = 0;
let existingWebhooksBroadLinkSceneAppletsCount = 0;
existingWebhooksBroadLinkAppletIDsAndNames = {};
await webDriver.get('https://ifttt.com/broadlink');
try {
await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox).
if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation');
} catch (acceptLeavePageAlertError) {
// Ignore any error if there is no Leave Page confirmation.
}
await check_for_server_error_page();
// First, wait a long time for community Applets to exist within the "discover_services" section, which will always exist.
await webDriver.wait(until.elementsLocated(By.xpath('//section[@class="discover_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]')), longWaitForElementTime);
try {
// Then, wait a short time for the "My Applets" button to exist and click it to switch to the "My Applets" section.
// If no personal Applets exist, this link will not exist and we want to fail quickly in this case (which is why we wait a short time).
// Clicking this will set the URL to "https://ifttt.com/broadlink/my_applets" but annoyingly that URL cannot be visited directly (it 404s).
await webDriver.wait(
until.elementLocated(By.xpath('//div[contains(@class,"discover_service_view")]/span[text()="My Applets"]')), shortWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Clicking My Applets Button');
await thisElement.click();
});
// Finally, wait a long time for personal Applets to exist within the "my_services" section (even though they should already be loaded from the first page load) which was revealed by switching to the "My Applets" section.
await webDriver.wait(until.elementsLocated(By.xpath('//section[@class="my_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]')), longWaitForElementTime);
// Next, once we know the page is fully loaded, wait a short time to get the "my_services" Applet titles (so that it will fail quickly if none exist, even though we should have already failed since the "My Applets" button wouldn't exist).
await webDriver.wait(
until.elementsLocated(By.xpath('//section[@class="my_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]/a[contains(@class,"applet-card-body")]')), shortWaitForElementTime
).then(async theseElements => {
totalBroadLinkAppletsDetected = theseElements.length;
if (debugLogging) console.debug(`DEBUG - Detected ${totalBroadLinkAppletsDetected} Total BroadLink Applets - Filtering to Only Webhooks Applets for BroadLink`);
for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) {
try {
let thisAppletWorksWithPermissionsElement = await theseElements[thisElementIndex].findElement(By.xpath('.//div[@class="meta"]/div[@class="works-with"]/ul[@class="permissions"]'));
let thisAppletTriggerServiceName = await thisAppletWorksWithPermissionsElement.findElement(By.xpath('.//li[1]/img')).getAttribute('title');
if (thisAppletTriggerServiceName == 'Webhooks') {
let thisAppletActionServiceName = await thisAppletWorksWithPermissionsElement.findElement(By.xpath('.//li[2]/img')).getAttribute('title');
if (thisAppletActionServiceName == 'BroadLink') { // Since we're on https://ifttt.com/broadlink and the Trigger Service is Webhooks this is an unnecessary check, but better safe than sorry.
let thisBroadLinkAppletName = await theseElements[thisElementIndex].findElement(By.xpath('.//div[contains(@class,"content")]/span[contains(@class,"title")]/span/div/div')).getText(); // "title" class had a space after it at the time of writing, which I don't trust to stay forever, so using contains instead of checking if equals "title ".
if (debugLogging) console.debug(`DEBUG - Found Webhooks/BroadLink Applet: ${thisBroadLinkAppletName}`);
let thisBroadLinkAppletNameParts = thisBroadLinkAppletName.split('+');
let thisBroadLinkAppletNamePrefixPart = thisBroadLinkAppletNameParts[0];
if ((thisBroadLinkAppletNameParts.length == 2) && allowedWebhooksBroadLinkAppletNamePrefixes.includes(thisBroadLinkAppletNamePrefixPart) && !/\s/g.test(thisBroadLinkAppletNameParts[1])) {
let thisAppletURL = await theseElements[thisElementIndex].getAttribute('href');
if (thisAppletURL.includes('/applets/')) {
if (thisBroadLinkAppletNamePrefixPart.endsWith('-On')) {
existingWebhooksBroadLinkOnAppletsCount ++;
} else if (thisBroadLinkAppletNamePrefixPart.endsWith('-Off')) {
existingWebhooksBroadLinkOffAppletsCount ++;
} else if (thisBroadLinkAppletNamePrefixPart.endsWith('-Scene')) {
existingWebhooksBroadLinkSceneAppletsCount ++;
}
existingWebhooksBroadLinkAppletIDsAndNames[thisAppletURL.split('/applets/')[1].split('-webhooks-event-broadlink-')[0]] = thisBroadLinkAppletName;
}
}
}
}
} catch (getAppletInfoError) {
if (debugLogging) console.debug(`DEBUG ERROR - FAILED TO GET APPLET INFO: ${getAppletInfoError}`);
}
}
});
} catch (getExistingBroadLinkAppletsError) {
if (debugLogging) console.debug(`DEBUG ERROR - FAILED TO GET ANY EXISTING APPLETS: ${getExistingBroadLinkAppletsError}`);
}
if (totalBroadLinkAppletsDetected == 0) {
// If we didn't detect any Applets, make sure that the BroadLink Service is connected.
try {
await webDriver.wait(until.elementLocated(By.xpath('//a[contains(@href,"/broadlink/redirect_to_connect")]')), shortWaitForElementTime);
throw '"BroadLink" SERVICE NOT CONNECTED IN IFTTT';
} catch (broadLinkServiceConnectionError) {
if (broadLinkServiceConnectionError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) {
throw broadLinkServiceConnectionError;
}
// Otherwise, ignore likely error from element not existing. Which means that the BroadLink Service is connected like we want.
}
}
let existingWebhooksBroadLinkTotalAppletsCount = Object.keys(existingWebhooksBroadLinkAppletIDsAndNames).length;
let existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount = (existingWebhooksBroadLinkOnAppletsCount + existingWebhooksBroadLinkOffAppletsCount + existingWebhooksBroadLinkSceneAppletsCount);
console.info(`\n${existingWebhooksBroadLinkTotalAppletsCount} Existing Webhooks Applet${((existingWebhooksBroadLinkTotalAppletsCount == 1) ? '' : 's')} for BroadLink Detected${(((optionsPromptsResponse.groupSelection != groupDevicesAndScenes) || (existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount > 0)) ?
`:\n\t${((optionsPromptsResponse.groupSelection == groupScenesOnly) ?
'CHOSE NOT TO DETECT EXISTING WEBHOOKS APPLETS FOR DEVICES' :
`${existingWebhooksBroadLinkOnAppletsCount} Turn Device On Applet${((existingWebhooksBroadLinkOnAppletsCount == 1) ? '' : 's')}\n\t${existingWebhooksBroadLinkOffAppletsCount} Turn Device Off Applet${((existingWebhooksBroadLinkOffAppletsCount == 1) ? '' : 's')}`
)}\n\t${((optionsPromptsResponse.groupSelection == groupDevicesOnly) ?
'CHOSE NOT TO DETECT EXISTING WEBHOOKS APPLETS FOR SCENE' :
`${existingWebhooksBroadLinkSceneAppletsCount} Scene Applet${((existingWebhooksBroadLinkSceneAppletsCount == 1) ? '' : 's')}`
)}` :
''
)}`);
if (existingWebhooksBroadLinkTotalAppletsCount != existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount) {
console.warn(`WARNING: TOTAL EXISTING APPLETS COUNT (${existingWebhooksBroadLinkTotalAppletsCount}) != ON APPLETS + OFF APPLETS + SCENE APPLETS COUNT (${existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount})`);
}
break;
} catch (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError) {
if (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) {
throw retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError; // Don't keep trying if service isn't connected.
}
console.error(`\nERROR: ${retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError}`);
if (debugLogging) {
try {
console.debug(`URL=${await webDriver.getCurrentUrl()}`);
} catch (getCurrentURLerror) {
console.debug('FAILED TO GET CURRENT URL');
}
}
console.error(`\n\nERROR RETRIEVING EXISTING WEBHOOKS APPLETS FOR BROADLINK - ATTEMPT ${retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount} OF ${maxTaskAttempts}\n\n`);
if (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount == maxTaskAttempts) {
throw retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError;
}
}
}
let existingWebhooksBroadLinkAppletNames = Object.values(existingWebhooksBroadLinkAppletIDsAndNames); // Get array of Applet names to be able to easily check if an Applet already exists.
let currentBroadLinkDeviceNamesArray = [];
let currentBroadLinkSceneNamesArray = [];
if ((optionsPromptsResponse.taskSelection == taskCreateApplets) || (optionsPromptsResponse.taskSelection == taskArchiveAppletsNotInBroadLink) || (optionsPromptsResponse.taskSelection == taskOutputSummary)) {
console.info('\nDetecting BroadLink Devices & Scenes...');
for (let retrieveDevicesAndScenesAttemptCount = 1; retrieveDevicesAndScenesAttemptCount <= maxTaskAttempts; retrieveDevicesAndScenesAttemptCount ++) {
try {
await setup_ifttt_webhooks_broadlink_applet('FakeEventName-ToRetrieveRealDeviceAndSceneNames', (optionsPromptsResponse.groupSelection == groupScenesOnly));
currentBroadLinkDeviceNamesArray = [];
if (optionsPromptsResponse.groupSelection != groupScenesOnly) {
await webDriver.wait(until.elementLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option[text()!="Loading…"]')), longWaitForElementTime); // Wait for devices to be loaded.
await webDriver.wait(
until.elementsLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option')), longWaitForElementTime // Now get all the devices.
).then(async theseElements => {
if (debugLogging) console.debug('DEBUG - Retrieving BroadLink Device Names');
for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) {
currentBroadLinkDeviceNamesArray.push(await theseElements[thisElementIndex].getText());
}
});
if ((currentBroadLinkDeviceNamesArray.length == 1) && (currentBroadLinkDeviceNamesArray[0] == 'No options available')) currentBroadLinkDeviceNamesArray = [];
if (currentBroadLinkDeviceNamesArray.length > 1) {
currentBroadLinkDeviceNamesArray.sort(function(thisDeviceName, thatDeviceName) {
return thisDeviceName.localeCompare(thatDeviceName);
});
}
console.info(`\n${currentBroadLinkDeviceNamesArray.length} BroadLink Device${((currentBroadLinkDeviceNamesArray.length == 1) ? '' : 's')} Detected`);
if (optionsPromptsResponse.groupSelection != groupDevicesOnly) {
// Do not keep clicking the "Back" button until the button no longer exists (like we do with other submits) so that we don't accidentally go back multiple pages.
await webDriver.wait(
until.elementLocated(By.xpath('//a[@title="Back"]')), longWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Clicking Back Button');
await thisElement.click();
});
await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose an action"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing.
await click_button_until_no_longer_exists(By.xpath('//a[@title="Choose action: Scene control"]'));
await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields" or text()="Connect service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing.
try {
await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields"]')), shortWaitForElementTime);
} catch (confirmServiceConnectionError) {
throw '"BroadLink" SERVICE NOT CONNECTED IN IFTTT';
}
}
} else {
console.info('\nCHOSE NOT TO DETECT DEVICES IN BROADLINK');
}
currentBroadLinkSceneNamesArray = [];
if (optionsPromptsResponse.groupSelection != groupDevicesOnly) {
await webDriver.wait(until.elementLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option[text()!="Loading…"]')), longWaitForElementTime); // Wait for scenes to be loaded.
await webDriver.wait(
until.elementsLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option')), longWaitForElementTime // Now get all the scenes.
).then(async theseElements => {
if (debugLogging) console.debug('DEBUG - Retrieving BroadLink Scene Names');
for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) {
currentBroadLinkSceneNamesArray.push(await theseElements[thisElementIndex].getText());
}
});
if ((currentBroadLinkSceneNamesArray.length == 1) && (currentBroadLinkSceneNamesArray[0] == 'No options available')) currentBroadLinkSceneNamesArray = [];
if (currentBroadLinkSceneNamesArray.length > 1) {
currentBroadLinkSceneNamesArray.sort(function(thisSceneName, thatSceneName) {
return thisSceneName.localeCompare(thatSceneName);
});
}
console.info(`\n${currentBroadLinkSceneNamesArray.length} BroadLink Scene${((currentBroadLinkSceneNamesArray.length == 1) ? '' : 's')} Detected`);
} else {
console.info('\nCHOSE NOT TO DETECT SCENES IN BROADLINK');
}
break;
} catch (retrieveDevicesAndScenesError) {
if (retrieveDevicesAndScenesError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT') || retrieveDevicesAndScenesError.toString().startsWith('MAXIMUM ALLOWED APPLETS CREATED')) {
throw retrieveDevicesAndScenesError; // Don't keep trying if service isn't connected or maximum allowed Applets created (IFTTT Pro required).
}
console.error(`\nERROR: ${retrieveDevicesAndScenesError}`);
if (debugLogging) {
try {
console.debug(`URL=${await webDriver.getCurrentUrl()}`);
} catch (getCurrentURLerror) {
console.debug('FAILED TO GET CURRENT URL');
}
}
console.error(`\n\nERROR RETRIEVING BROADLINK DEVICES AND SCENES - ATTEMPT ${retrieveDevicesAndScenesAttemptCount} OF ${maxTaskAttempts}\n\n`);
if (retrieveDevicesAndScenesAttemptCount == maxTaskAttempts) {
throw retrieveDevicesAndScenesError;
}
}
}
}
if (optionsPromptsResponse.taskSelection == taskCreateApplets) {
let currentBroadLinkDevicesAndScenesArrays = [currentBroadLinkDeviceNamesArray, currentBroadLinkSceneNamesArray];
for (let thisArrayIndex = 0; thisArrayIndex < currentBroadLinkDevicesAndScenesArrays.length; thisArrayIndex ++) {
let thisDevicesOrScenesArray = currentBroadLinkDevicesAndScenesArrays[thisArrayIndex];
let isScene = (thisArrayIndex == 1);
if (thisDevicesOrScenesArray.length > 0) console.info(`\n\nCreating Webhooks Applet${((thisDevicesOrScenesArray.length == 1) ? '' : 's')} for ${thisDevicesOrScenesArray.length} BroadLink ${isScene ? 'scene' : 'device'}${((thisDevicesOrScenesArray.length == 1) ? '' : 's')}...`);
for (let thisDeviceOrSceneIndex = 0; thisDeviceOrSceneIndex < thisDevicesOrScenesArray.length; thisDeviceOrSceneIndex ++) {
let thisDevicOrSceneName = thisDevicesOrScenesArray[thisDeviceOrSceneIndex];
let statesArray = (isScene ? ['Scene'] : ['On', 'Off']);
for (let thisStateIndex = 0; thisStateIndex < statesArray.length; thisStateIndex ++) {
let thisStateName = statesArray[thisStateIndex];
if (isScene) {
console.info(`\nSCENE ${thisDeviceOrSceneIndex + 1} OF ${thisDevicesOrScenesArray.length}`);
console.info(`\tScene Name: ${thisDevicOrSceneName}`);
} else {
console.info(`\nDEVICE ${thisDeviceOrSceneIndex + 1} OF ${thisDevicesOrScenesArray.length} - ${thisStateName} STATE`);
console.info(`\tDevice Name: ${thisDevicOrSceneName}`);
}
let thisWebhooksEventName = `BroadLink-${thisStateName}+${thisDevicOrSceneName.replace(/\s/g, '_')}`;
let correctOriginalAppletTitle = `If Maker Event "${thisWebhooksEventName}", then ${(isScene ? `the ${thisDevicOrSceneName} will turn on` : `turn ${thisStateName.toLowerCase()} ${thisDevicOrSceneName}`)}`;
let desiredAppletTitle = `Webhooks Event: ${thisWebhooksEventName}`;
if (existingWebhooksBroadLinkAppletNames.includes(desiredAppletTitle)) {
console.info(`SKIPPING: WEBHOOKS APPLET WITH NAME "${desiredAppletTitle}" ALREADY EXISTS`);
continue;
}
for (let appletSetupAttemptCount = 1; appletSetupAttemptCount <= maxTaskAttempts; appletSetupAttemptCount ++) {
// If any error happen within the Applet setup phase, we can just start over and try again because the Applet has not been created yet.
try {
await setup_ifttt_webhooks_broadlink_applet(thisWebhooksEventName, isScene);
await webDriver.wait(
until.elementLocated(By.xpath(`//select[@name="fields[deviceinfo]"]/option[text()="${thisDevicOrSceneName}"]`)), longWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug(`DEBUG - Clicking ${isScene ? 'Scene' : 'Device'} Name Option`);
await thisElement.click();
});
if (!isScene) {
await webDriver.wait(
until.elementLocated(By.xpath('//select[@name="fields[PowerControl_ChangePowerState_string]"]/option[2]')), longWaitForElementTime // Always wait for device states to get loaded.
).then(async thisElement => {
if (thisStateName == 'Off') { // But we only need to click to set the state if we want to change it to "Off".
if (debugLogging) console.debug('DEBUG - Clicking Device State Off Option');
await thisElement.click();
}
});
}
await click_button_until_no_longer_exists(By.xpath('//input[@value="Create action" or @value="Creating action..."]'));
await webDriver.wait(until.elementLocated(By.xpath(`//span[text()="${isScene ? 'Scene control' : 'Turn device on or off'}"]`)), longWaitForElementTime); // Make sure correct page is loaded before continuing.
await click_button_until_no_longer_exists(By.xpath('//button[text()="Continue"]'));
await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Review and finish"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing.
let originalAppletTitle = 'FAILED_TO_RETRIEVE_ORIGINAL_APPLET_TITLE';
await webDriver.wait(
until.elementLocated(By.xpath('//textarea[@name="description"]')), longWaitForElementTime
).then(async thisElement => {
await webDriver.wait(
until.elementLocated(By.xpath('//textarea[@name="description"]/following-sibling::div')), shortWaitForElementTime
).then(async thatElement => {
// Cannot get the originalAppletTitle from the actual textarea, but can get it from the div right after it.
originalAppletTitle = (await thatElement.getAttribute('innerHTML')).trim(); // getText() doesn't work here for some reason. (Need to trim since there will be a trailing line break.)
if (originalAppletTitle != correctOriginalAppletTitle) {
throw `ORIGINAL APPLET TITLE NOT CORRECT ("${originalAppletTitle}" != "${correctOriginalAppletTitle}")`;
}
await thisElement.clear();
await thisElement.sendKeys(Key.ENTER, Key.BACK_SPACE); // Send Enter and then Backspace keys be sure the contents get updated, because the character count doesn't always get updated when only using clear().
await thisElement.clear(); // clear() again after that to be sure the title field is empty.
await thisElement.sendKeys(desiredAppletTitle);
console.info(`\tOriginal Applet Title: ${originalAppletTitle}`);
});
});
// Applets notifications are disabled by default now, but still check just in case.
await webDriver.wait(until.elementLocated(By.xpath('//div[contains(@class,"preview__notification")]/div[@class="switch"]/div[@class="switch-ui disabled"]')), longWaitForElementTime);
break;
} catch (appletSetupError) {
if (appletSetupError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT') || appletSetupError.toString().startsWith('MAXIMUM ALLOWED APPLETS CREATED')) {
throw appletSetupError; // Don't keep trying if service isn't connected or maximum allowed Applets created (IFTTT Pro required).
}
console.error(`\nERROR: ${appletSetupError}`);
if (debugLogging) {
try {
console.debug(`URL=${await webDriver.getCurrentUrl()}`);
} catch (getCurrentURLerror) {
console.debug('FAILED TO GET CURRENT URL');
}
}
console.error(`\n\nERROR SETTING UP WEBHOOKS APPLET FOR "${thisWebhooksEventName}" - ATTEMPT ${appletSetupAttemptCount} OF ${maxTaskAttempts}\n\n`);
if (appletSetupAttemptCount == maxTaskAttempts) {
throw appletSetupError;
}
}
}
for (let finishAppletAttemptCount = 1; finishAppletAttemptCount <= maxTaskAttempts; finishAppletAttemptCount ++) {
// Do not keep clicking the "Finish" button until the correct URL is loaded (like we do with other submits) so that we don't accidentally create multiple instances of the same Applet.
// But, do retry this part maxTaskAttempts times. If there is an issue the large delay between click attempts should help not make duplicates and only catch real issues.
try {
let currentURL = await webDriver.getCurrentUrl();
if (!currentURL.startsWith('https://ifttt.com/applets/')) {
await webDriver.wait(
until.elementLocated(By.xpath('//button[text()="Finish"]')), longWaitForElementTime
).then(async thisElement => {
if (debugLogging) console.debug('DEBUG - Clicking Finish Applet Button');
await thisElement.click();
});
// But, do keep checking for the "Finish" buttons existance while waiting for the correct URL so we can exit this loop if it's been too long.
let finishButtonExistsCount = 0;
let finishButtonNoLongerExistsCount = 0;
while (!currentURL.startsWith('https://ifttt.com/applets/')) {
try {
await webDriver.wait(until.elementLocated(By.xpath('//button[text()="Finish" or text()="Finishing..."]')), shortWaitForElementTime);
finishButtonExistsCount ++;
if (debugLogging) console.debug(`DEBUG - Finish Button Still Exists (${finishButtonExistsCount}) - URL=${currentURL}`);
if (finishButtonExistsCount >= maxButtonClicksCount) {
if (debugLogging) console.warn('DEBUG WARNING - FINISH BUTTON HAS EXISTED FOR TOO LONG WITHOUT URL GETTING UPDATED - EXITING STUCK LOOP');
break;
}
} catch (finishButtonExistsError) {
finishButtonNoLongerExistsCount ++;