aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/ServicesStore.ts
blob: 8105aa084b7f2be16bf94e3079029fdfc6063588 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
import { join } from 'node:path';
import { clipboard, ipcRenderer, shell } from 'electron';
import { ensureFileSync, pathExistsSync, writeFileSync } from 'fs-extra';
import { debounce, remove } from 'lodash';
import { action, computed, makeObservable, observable, reaction } from 'mobx';
import ms from 'ms';

import type { Stores } from '../@types/stores.types';
import type { Actions } from '../actions/lib/actions';
import type { ApiInterface } from '../api';
import { DEFAULT_SERVICE_SETTINGS, KEEP_WS_LOADED_USID } from '../config';
import { ferdiumVersion } from '../environment-remote';
import { workspaceStore } from '../features/workspaces';
import {
  getDevRecipeDirectory,
  getRecipeDirectory,
} from '../helpers/recipe-helpers';
import matchRoute from '../helpers/routing-helpers';
import { isInTimeframe } from '../helpers/schedule-helpers';
import { SPELLCHECKER_LOCALES } from '../i18n/languages';
import { cleanseJSObject } from '../jsUtils';
import type { UnreadServices } from '../lib/dbus/Ferdium';
import type Service from '../models/Service';
import CachedRequest from './lib/CachedRequest';
import Request from './lib/Request';
import TypedStore from './lib/TypedStore';

const debug = require('../preload-safe-debug')('Ferdium:ServiceStore');

export default class ServicesStore extends TypedStore {
  @observable allServicesRequest: CachedRequest = new CachedRequest(
    this.api.services,
    'all',
  );

  @observable createServiceRequest: Request = new Request(
    this.api.services,
    'create',
  );

  @observable updateServiceRequest: Request = new Request(
    this.api.services,
    'update',
  );

  @observable reorderServicesRequest: Request = new Request(
    this.api.services,
    'reorder',
  );

  @observable deleteServiceRequest: Request = new Request(
    this.api.services,
    'delete',
  );

  @observable clearCacheRequest: Request = new Request(
    this.api.services,
    'clearCache',
  );

  @observable filterNeedle: string | null = null;

  // Array of service IDs that have recently been used
  // [0] => Most recent, [n] => Least recent
  // No service ID should be in the list multiple times, not all service IDs have to be in the list
  @observable lastUsedServices: string[] = [];

  private toggleToTalkCallback = () => this.active?.toggleToTalk();

  constructor(stores: Stores, api: ApiInterface, actions: Actions) {
    super(stores, api, actions);

    makeObservable(this);

    // Register action handlers
    this.actions.service.setActive.listen(this._setActive.bind(this));
    this.actions.service.blurActive.listen(this._blurActive.bind(this));
    this.actions.service.setActiveNext.listen(this._setActiveNext.bind(this));
    this.actions.service.setActivePrev.listen(this._setActivePrev.bind(this));
    this.actions.service.showAddServiceInterface.listen(
      this._showAddServiceInterface.bind(this),
    );
    this.actions.service.createService.listen(this._createService.bind(this));
    this.actions.service.createFromLegacyService.listen(
      this._createFromLegacyService.bind(this),
    );
    this.actions.service.updateService.listen(this._updateService.bind(this));
    this.actions.service.deleteService.listen(this._deleteService.bind(this));
    this.actions.service.openRecipeFile.listen(this._openRecipeFile.bind(this));
    this.actions.service.clearCache.listen(this._clearCache.bind(this));
    this.actions.service.setWebviewReference.listen(
      this._setWebviewReference.bind(this),
    );
    this.actions.service.detachService.listen(this._detachService.bind(this));
    this.actions.service.focusService.listen(this._focusService.bind(this));
    this.actions.service.focusActiveService.listen(
      this._focusActiveService.bind(this),
    );
    this.actions.service.toggleService.listen(this._toggleService.bind(this));
    this.actions.service.handleIPCMessage.listen(
      this._handleIPCMessage.bind(this),
    );
    this.actions.service.sendIPCMessage.listen(this._sendIPCMessage.bind(this));
    this.actions.service.sendIPCMessageToAllServices.listen(
      this._sendIPCMessageToAllServices.bind(this),
    );
    this.actions.service.setUnreadMessageCount.listen(
      this._setUnreadMessageCount.bind(this),
    );
    this.actions.service.setDialogTitle.listen(this._setDialogTitle.bind(this));
    this.actions.service.openWindow.listen(this._openWindow.bind(this));
    this.actions.service.filter.listen(this._filter.bind(this));
    this.actions.service.resetFilter.listen(this._resetFilter.bind(this));
    this.actions.service.resetStatus.listen(this._resetStatus.bind(this));
    this.actions.service.reload.listen(this._reload.bind(this));
    this.actions.service.reloadActive.listen(this._reloadActive.bind(this));
    this.actions.service.reloadAll.listen(this._reloadAll.bind(this));
    this.actions.service.reloadUpdatedServices.listen(
      this._reloadUpdatedServices.bind(this),
    );
    this.actions.service.reorder.listen(this._reorder.bind(this));
    this.actions.service.toggleNotifications.listen(
      this._toggleNotifications.bind(this),
    );
    this.actions.service.toggleAudio.listen(this._toggleAudio.bind(this));
    this.actions.service.toggleDarkMode.listen(this._toggleDarkMode.bind(this));
    this.actions.service.openDevTools.listen(this._openDevTools.bind(this));
    this.actions.service.openDevToolsForActiveService.listen(
      this._openDevToolsForActiveService.bind(this),
    );
    this.actions.service.hibernate.listen(this._hibernate.bind(this));
    this.actions.service.awake.listen(this._awake.bind(this));
    this.actions.service.resetLastPollTimer.listen(
      this._resetLastPollTimer.bind(this),
    );
    this.actions.service.shareSettingsWithServiceProcess.listen(
      this._shareSettingsWithServiceProcess.bind(this),
    );

    this.registerReactions([
      this._focusServiceReaction.bind(this),
      this._getUnreadMessageCountReaction.bind(this),
      this._mapActiveServiceToServiceModelReaction.bind(this),
      this._saveActiveService.bind(this),
      this._logoutReaction.bind(this),
      this._handleMuteSettings.bind(this),
      this._checkForActiveService.bind(this),
    ]);

    // Just bind this
    this._initializeServiceRecipeInWebview.bind(this);
  }

  setup() {
    // Single key reactions for the sake of your CPU
    reaction(
      () => this.stores.settings.app.enableSpellchecking,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.enableTranslator,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.spellcheckerLanguage,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.darkMode,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.adaptableDarkMode,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.universalDarkMode,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.splitMode,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.splitColumns,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.searchEngine,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.translatorEngine,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.translatorLanguage,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );

    reaction(
      () => this.stores.settings.app.clipboardNotifications,
      () => {
        this._shareSettingsWithServiceProcess();
      },
    );
  }

  initialize() {
    super.initialize();

    ipcRenderer.on('toggle-to-talk', this.toggleToTalkCallback);

    // Check services to become hibernated
    this.serviceMaintenanceTick();
  }

  teardown() {
    super.teardown();

    ipcRenderer.off('toggle-to-talk', this.toggleToTalkCallback);

    // Stop checking services for hibernation
    this.serviceMaintenanceTick.cancel();
  }

  _serviceMaintenanceTicker() {
    this._serviceMaintenance();
    this.serviceMaintenanceTick();
    debug('Service maintenance tick');
  }

  /**
   * Сheck for services to become hibernated.
   */
  serviceMaintenanceTick = debounce(this._serviceMaintenanceTicker, ms('10s'));

  /**
   * Run various maintenance tasks on services
   */
  _serviceMaintenance() {
    for (const service of this.enabled) {
      // Defines which services should be hibernated or woken up
      if (!service.isActive) {
        if (
          !service.lastHibernated &&
          Date.now() - service.lastUsed >
            ms(`${this.stores.settings.all.app.hibernationStrategy}s`)
        ) {
          // If service is stale, hibernate it.
          this._hibernate({ serviceId: service.id });
        }

        if (
          service.isWakeUpEnabled &&
          service.lastHibernated &&
          Number(this.stores.settings.all.app.wakeUpStrategy) > 0 &&
          Date.now() - service.lastHibernated >
            ms(`${this.stores.settings.all.app.wakeUpStrategy}s`)
        ) {
          // If service is in hibernation and the wakeup time has elapsed, wake it.
          this._awake({ serviceId: service.id, automatic: true });
        }
      }

      if (
        service.lastPoll &&
        service.lastPoll - service.lastPollAnswer > ms('1m')
      ) {
        // If service did not reply for more than 1m try to reload.
        if (service.isActive) {
          debug(`Service lost connection: ${service.name} (${service.id}).`);
          service.lostRecipeConnection = true;
        } else if (
          this.stores.app.isOnline &&
          service.lostRecipeReloadAttempt < 3
        ) {
          debug(
            `Reloading service: ${service.name} (${service.id}). Attempt: ${service.lostRecipeReloadAttempt}`,
          );
          // service.webview.reload();
          service.lostRecipeReloadAttempt += 1;

          service.lostRecipeConnection = false;
        }
      } else {
        service.lostRecipeConnection = false;
        service.lostRecipeReloadAttempt = 0;
      }
    }
  }

  // Computed props
  @computed get all(): Service[] {
    if (this.stores.user.isLoggedIn) {
      const services = this.allServicesRequest.execute().result;
      if (services) {
        return observable(
          [...services]
            .slice()
            .sort((a, b) => a.order - b.order)
            .map((s, index) => {
              s.index = index;
              return s;
            }),
        );
      }
    }
    return [];
  }

  @computed get enabled(): Service[] {
    return this.all.filter(service => service.isEnabled);
  }

  @computed get allDisplayed(): Service[] {
    const services = this.stores.settings.all.app.showDisabledServices
      ? this.all
      : this.enabled;
    return workspaceStore.filterServicesByActiveWorkspace(services);
  }

  // This is just used to avoid unnecessary rerendering of resource-heavy webviews
  @computed get allDisplayedUnordered() {
    const { showDisabledServices } = this.stores.settings.all.app;
    const { keepAllWorkspacesLoaded } = this.stores.workspaces.settings;
    const services = this.allServicesRequest.execute().result || [];
    const filteredServices = showDisabledServices
      ? services
      : services.filter(service => service.isEnabled);

    let displayedServices;
    if (keepAllWorkspacesLoaded) {
      // Keep all enabled services loaded
      displayedServices = filteredServices;
    } else {
      // Keep all services in current workspace loaded
      displayedServices =
        workspaceStore.filterServicesByActiveWorkspace(filteredServices);

      // Keep all services active in workspaces that should be kept loaded
      for (const workspace of this.stores.workspaces.workspaces) {
        // Check if workspace needs to be kept loaded
        if (workspace.services.includes(KEEP_WS_LOADED_USID)) {
          // Get services for workspace
          const serviceIDs = new Set(
            workspace.services.filter(i => i !== KEEP_WS_LOADED_USID),
          );
          const wsServices = filteredServices.filter(service =>
            serviceIDs.has(service.id),
          );

          displayedServices = [...displayedServices, ...wsServices];
        }
      }

      // Make sure every service is in the list only once
      displayedServices = displayedServices.filter(
        (v, i, a) => a.indexOf(v) === i,
      );
    }

    return displayedServices;
  }

  @computed get filtered() {
    if (this.filterNeedle !== null) {
      return this.all.filter(service =>
        service.name.toLowerCase().includes(this.filterNeedle!.toLowerCase()),
      );
    }

    // Return all if there is no filterNeedle present
    return this.all;
  }

  @computed get active() {
    return this.all.find(service => service.isActive);
  }

  @computed get activeSettings() {
    const match = matchRoute(
      '/settings/services/edit/:id',
      this.stores.router.location.pathname,
    );
    if (match) {
      const activeService = this.one(match.id);
      if (activeService) {
        return activeService;
      }

      debug('Service not available');
    }

    return null;
  }

  @computed get isTodosServiceAdded() {
    return (
      this.allDisplayed.find(
        service => service.isTodosService && service.isEnabled,
      ) ?? false
    );
  }

  @computed get isTodosServiceActive() {
    return this.active?.isTodosService;
  }

  // TODO: This can actually return undefined as well
  one(id: string): Service {
    return this.all.find(service => service.id === id)!;
  }

  async _showAddServiceInterface({ recipeId }) {
    this.stores.router.push(`/settings/services/add/${recipeId}`);
  }

  // Actions
  async _createService({
    recipeId,
    serviceData,
    redirect = true,
    skipCleanup = false,
  }) {
    if (!this.stores.recipes.isInstalled(recipeId)) {
      debug(`Recipe "${recipeId}" is not installed, installing recipe`);
      await this.stores.recipes._install({ recipeId });
      debug(`Recipe "${recipeId}" installed`);
    }

    // set default values for serviceData
    serviceData = {
      isEnabled: DEFAULT_SERVICE_SETTINGS.isEnabled,
      isHibernationEnabled: DEFAULT_SERVICE_SETTINGS.isHibernationEnabled,
      isWakeUpEnabled: DEFAULT_SERVICE_SETTINGS.isWakeUpEnabled,
      isNotificationEnabled: DEFAULT_SERVICE_SETTINGS.isNotificationEnabled,
      isBadgeEnabled: DEFAULT_SERVICE_SETTINGS.isBadgeEnabled,
      isMediaBadgeEnabled: DEFAULT_SERVICE_SETTINGS.isMediaBadgeEnabled,
      trapLinkClicks: DEFAULT_SERVICE_SETTINGS.trapLinkClicks,
      isMuted: DEFAULT_SERVICE_SETTINGS.isMuted,
      customIcon: DEFAULT_SERVICE_SETTINGS.customIcon,
      isDarkModeEnabled: DEFAULT_SERVICE_SETTINGS.isDarkModeEnabled,
      isProgressbarEnabled: DEFAULT_SERVICE_SETTINGS.isProgressbarEnabled,
      spellcheckerLanguage:
        SPELLCHECKER_LOCALES[this.stores.settings.app.spellcheckerLanguage],
      userAgentPref: '',
      ...serviceData,
    };

    const data = skipCleanup
      ? serviceData
      : this._cleanUpTeamIdAndCustomUrl(recipeId, serviceData);

    const response = await this.createServiceRequest.execute(recipeId, data)
      .promise;

    this.allServicesRequest.patch(result => {
      if (!result) return;
      result.push(response.data);
    });

    this.actions.settings.update({
      type: 'proxy',
      data: {
        [`${response.data.id}`]: data.proxy,
      },
    });

    this.actionStatus = response.status || [];

    if (redirect) {
      this.stores.router.push('/settings/recipes');
    }
  }

  @action async _createFromLegacyService({ data }) {
    const { id } = data.recipe;
    const serviceData: {
      name?: string;
      team?: string;
      customUrl?: string;
    } = {};

    if (data.name) {
      serviceData.name = data.name;
    }

    if (data.team) {
      if (data.customURL) {
        // TODO: Is this correct?
        serviceData.customUrl = data.team;
      } else {
        serviceData.team = data.team;
      }
    }

    this.actions.service.createService({
      recipeId: id,
      serviceData,
      redirect: false,
    });
  }

  @action async _updateService({ serviceId, serviceData, redirect = true }) {
    const service = this.one(serviceId);
    const data = this._cleanUpTeamIdAndCustomUrl(
      service.recipe.id,
      serviceData,
    );
    const request = this.updateServiceRequest.execute(serviceId, data);

    const newData = serviceData;
    if (serviceData.iconFile) {
      await request.promise;

      newData.iconUrl = request.result.data.iconUrl;
      newData.hasCustomUploadedIcon = true;
    }

    this.allServicesRequest.patch(result => {
      if (!result) return;

      // patch custom icon deletion
      if (data.customIcon === 'delete') {
        newData.iconUrl = '';
        newData.hasCustomUploadedIcon = false;
      }

      // patch custom icon url
      if (data.customIconUrl) {
        newData.iconUrl = data.customIconUrl;
      }

      Object.assign(
        result.find(c => c.id === serviceId),
        newData,
      );
    });

    await request.promise;
    this.actionStatus = request.result.status;

    if (service.isEnabled) {
      this._sendIPCMessage({
        serviceId,
        channel: 'service-settings-update',
        args: newData,
      });
    }

    this.actions.settings.update({
      type: 'proxy',
      data: {
        [`${serviceId}`]: data.proxy,
      },
    });

    if (redirect) {
      this.stores.router.push('/settings/services');
    }
  }

  @action async _deleteService({ serviceId, redirect }): Promise<void> {
    const request = this.deleteServiceRequest.execute(serviceId);

    if (redirect) {
      this.stores.router.push(redirect);
    }

    this.allServicesRequest.patch((result: Service[]) => {
      remove(result, (c: Service) => c.id === serviceId);
    });

    await request.promise;
    this.actionStatus = request.result.status;
  }

  @action async _openRecipeFile({ recipe, file }): Promise<void> {
    // Get directory for recipe
    const normalDirectory = getRecipeDirectory(recipe);
    const devDirectory = getDevRecipeDirectory(recipe);
    let directory: string;

    if (pathExistsSync(normalDirectory)) {
      directory = normalDirectory;
    } else if (pathExistsSync(devDirectory)) {
      directory = devDirectory;
    } else {
      // Recipe cannot be found on drive
      return;
    }

    // Create and open file
    const filePath = join(directory, file);
    if (file === 'user.js') {
      if (!pathExistsSync(filePath)) {
        writeFileSync(
          filePath,
          `module.exports = (config, Ferdium) => {
  // Write your scripts here
  console.log("Hello, World!", config);
};
`,
        );
      }
    } else {
      ensureFileSync(filePath);
    }
    shell.showItemInFolder(filePath);
  }

  @action async _clearCache({ serviceId }) {
    this.clearCacheRequest.reset();
    const request = this.clearCacheRequest.execute(serviceId);
    await request.promise;
  }

  @action _setIsActive(service: Service, state: boolean): void {
    service.isActive = state;
  }

  @action _setActive({ serviceId, keepActiveRoute = null }) {
    if (!keepActiveRoute) this.stores.router.push('/');
    const service = this.one(serviceId);

    for (const s of this.all) {
      if (s.isActive) {
        s.lastUsed = Date.now();
        this._setIsActive(s, false);
      }
    }
    this._setIsActive(service, true);
    this._awake({ serviceId: service.id });

    if (
      this.isTodosServiceActive &&
      !this.stores.todos.settings.isFeatureEnabledByUser
    ) {
      this.actions.todos.toggleTodosFeatureVisibility();
    }

    // Update list of last used services
    this.lastUsedServices = this.lastUsedServices.filter(
      id => id !== serviceId,
    );
    this.lastUsedServices.unshift(serviceId);

    this._focusActiveService();
  }

  @action _blurActive() {
    const service = this.active;
    if (service) {
      this._setIsActive(service, false);
    } else {
      debug('No service is active');
    }
  }

  @action _setActiveNext() {
    const nextIndex = this._wrapIndex(
      this.allDisplayed.findIndex(service => service.isActive),
      1,
      this.allDisplayed.length,
    );

    this._setActive({ serviceId: this.allDisplayed[nextIndex].id });
  }

  @action _setActivePrev() {
    const prevIndex = this._wrapIndex(
      this.allDisplayed.findIndex(service => service.isActive),
      -1,
      this.allDisplayed.length,
    );

    this._setActive({ serviceId: this.allDisplayed[prevIndex].id });
  }

  @action _setUnreadMessageCount({ serviceId, count }) {
    const service = this.one(serviceId);

    service.unreadDirectMessageCount = count.direct;
    service.unreadIndirectMessageCount = count.indirect;
  }

  @action _setDialogTitle({ serviceId, dialogTitle }) {
    const service = this.one(serviceId);

    service.dialogTitle = dialogTitle;
  }

  @action _setWebviewReference({ serviceId, webview }) {
    const service = this.one(serviceId);
    if (service) {
      service.webview = webview;

      if (!service.isAttached) {
        debug('Webview is not attached, initializing');
        service.initializeWebViewEvents({
          handleIPCMessage: this.actions.service.handleIPCMessage,
          openWindow: this.actions.service.openWindow,
          stores: this.stores,
        });
        service.initializeWebViewListener();
      }
      service.isAttached = true;
    }
  }

  @action _detachService({ service }) {
    service.webview = null;
    service.isAttached = false;
  }

  @action _focusService({ serviceId }) {
    const service = this.one(serviceId);

    if (service.webview) {
      service.webview.blur();
      service.webview.focus();
    }
  }

  @action _focusActiveService(focusEvent = null) {
    if (this.stores.user.isLoggedIn) {
      // TODO: add checks to not focus service when router path is /settings or /auth
      const service = this.active;
      if (service) {
        if (service._webview) {
          document.title = `Ferdium - ${service.name} ${
            service.dialogTitle ? ` - ${service.dialogTitle}` : ''
          } ${service._webview ? `- ${service._webview.getTitle()}` : ''}`;
          this._focusService({ serviceId: service.id });
          if (this.stores.settings.app.splitMode && !focusEvent) {
            setTimeout(() => {
              document
                .querySelector('.services__webview-wrapper.is-active')
                ?.scrollIntoView({
                  behavior: 'smooth',
                  block: 'end',
                  inline: 'nearest',
                });
            }, 10);
          }
        }
      } else {
        debug('No service is active');
      }
    } else {
      this.allServicesRequest.invalidate();
    }
  }

  @action _toggleService({ serviceId }) {
    const service = this.one(serviceId);

    service.isEnabled = !service.isEnabled;
  }

  @action _handleIPCMessage({ serviceId, channel, args }) {
    const service = this.one(serviceId);

    // eslint-disable-next-line default-case
    switch (channel) {
      case 'hello': {
        debug('Received hello event from', serviceId);

        this._initRecipePolling(service.id);
        this._initializeServiceRecipeInWebview(serviceId);
        this._shareSettingsWithServiceProcess();

        break;
      }
      case 'alive': {
        service.lastPollAnswer = Date.now();

        break;
      }
      case 'message-counts': {
        debug(`Received unread message info from '${serviceId}'`, args[0]);

        this.actions.service.setUnreadMessageCount({
          serviceId,
          count: {
            direct: args[0].direct,
            indirect: args[0].indirect,
          },
        });

        break;
      }
      case 'active-dialog-title': {
        debug(`Received active dialog title from '${serviceId}'`, args[0]);

        this.actions.service.setDialogTitle({
          serviceId,
          dialogTitle: args[0],
        });

        break;
      }
      case 'notification': {
        const { notificationId, options } = args[0];

        const { isTwoFactorAutoCatcherEnabled, twoFactorAutoCatcherMatcher } =
          this.stores.settings.all.app;

        debug(
          'Settings for catch tokens',
          isTwoFactorAutoCatcherEnabled,
          twoFactorAutoCatcherMatcher,
        );

        if (isTwoFactorAutoCatcherEnabled) {
          /*
        parse the token digits from sms body, find "token" or "code" in options.body which reflect the sms content
        ---
        Token: 03624 / SMS-Code = PIN Token
        ---
        Prüfcode 010313 für Microsoft-Authentifizierung verwenden.
        ---
        483133 is your GitHub authentication code. @github.com #483133
        ---
        eBay: Ihr Sicherheitscode lautet 080090. \nEr läuft in 15 Minuten ab. Geben Sie den Code nicht an andere weiter.
        ---
        PayPal: Ihr Sicherheitscode lautet: 989605. Geben Sie diesen Code nicht weiter.
      */

          const rawBody = options.body;
          const { 0: token } = /\d{5,6}/.exec(options.body) || [];

          const wordsToCatch = twoFactorAutoCatcherMatcher
            .replaceAll(', ', ',')
            .split(',');

          debug('wordsToCatch', wordsToCatch);

          if (
            token &&
            wordsToCatch.some(a =>
              options.body.toLowerCase().includes(a.toLowerCase()),
            )
          ) {
            // with the extra "+ " it shows its copied to clipboard in the notification
            options.body = `+ ${rawBody}`;
            clipboard.writeText(token);
            debug('Token parsed and copied to clipboard');
          }
        }

        // Check if we are in scheduled Do-not-Disturb time
        const { scheduledDNDEnabled, scheduledDNDStart, scheduledDNDEnd } =
          this.stores.settings.all.app;

        if (
          scheduledDNDEnabled &&
          isInTimeframe(scheduledDNDStart, scheduledDNDEnd)
        ) {
          return;
        }

        if (service.isMuted || this.stores.settings.all.app.isAppMuted) {
          Object.assign(options, {
            silent: true,
          });
        }

        if (service.isNotificationEnabled) {
          let title: string;
          options.icon = service.iconUrl;
          if (this.stores.settings.all.app.privateNotifications === true) {
            // Remove message data from notification in private mode
            options.body = '';
            title = `Notification from ${service.name}`;
          } else {
            options.body = typeof options.body === 'string' ? options.body : '';
            title =
              typeof args[0].title === 'string' ? args[0].title : service.name;
          }

          this.actions.app.notify({
            notificationId,
            title,
            options,
            serviceId,
          });
        }

        break;
      }
      case 'avatar': {
        const url = args[0];
        if (service.iconUrl !== url && !service.hasCustomUploadedIcon) {
          service.customIconUrl = url;

          this.actions.service.updateService({
            serviceId,
            serviceData: {
              customIconUrl: url,
            },
            redirect: false,
          });
        }

        break;
      }
      case 'new-window': {
        const url = args[0];

        this.actions.app.openExternalUrl({ url });

        break;
      }
      case 'set-service-spellchecker-language': {
        if (args) {
          this.actions.service.updateService({
            serviceId,
            serviceData: {
              spellcheckerLanguage: args[0] === 'reset' ? '' : args[0],
            },
            redirect: false,
          });
        } else {
          console.warn('Did not receive locale');
        }

        break;
      }
      case 'feature:todos': {
        Object.assign(args[0].data, { serviceId });
        this.actions.todos.handleHostMessage(args[0]);

        break;
      }
      // No default
    }
  }

  @action _sendIPCMessage({ serviceId, channel, args }) {
    const service = this.one(serviceId);

    // Make sure the args are clean, otherwise ElectronJS can't transmit them
    const cleanArgs = cleanseJSObject(args);

    if (service.webview) {
      service.webview.send(channel, cleanArgs);
    }
  }

  @action _sendIPCMessageToAllServices({ channel, args }) {
    for (const s of this.all) {
      this.actions.service.sendIPCMessage({
        serviceId: s.id,
        channel,
        args,
      });
    }
  }

  @action _openWindow({ event }) {
    if (event.url !== 'about:blank') {
      event.preventDefault();
      this.actions.app.openExternalUrl({ url: event.url });
    }
  }

  @action _filter({ needle }) {
    this.filterNeedle = needle;
  }

  @action _resetFilter() {
    this.filterNeedle = null;
  }

  @action _resetStatus() {
    this.actionStatus = [];
  }

  @action _reload({ serviceId }) {
    const service = this.one(serviceId);
    if (!service.isEnabled) return;

    service.resetMessageCount();
    service.lostRecipeConnection = false;

    if (service.isTodosService) {
      this.actions.todos.reload();
      return;
    }

    if (!service.webview) return;
    return service.webview.loadURL(service.url);
  }

  @action _reloadActive() {
    const service = this.active;
    if (service) {
      this._reload({
        serviceId: service.id,
      });
    } else {
      debug('No service is active');
    }
  }

  @action _reloadAll() {
    for (const s of this.enabled) {
      this._reload({
        serviceId: s.id,
      });
    }
  }

  @action _reloadUpdatedServices() {
    this._reloadAll();
    this.actions.ui.toggleServiceUpdatedInfoBar({ visible: false });
  }

  @action _reorder(params) {
    const { workspaces } = this.stores;
    if (workspaces.isAnyWorkspaceActive) {
      workspaces.reorderServicesOfActiveWorkspace(params);
    } else {
      this._reorderService(params);
    }
  }

  @action _reorderService({ oldIndex, newIndex }) {
    const { showDisabledServices } = this.stores.settings.all.app;
    const oldEnabledSortIndex = showDisabledServices
      ? oldIndex
      : this.all.indexOf(this.enabled[oldIndex]);
    const newEnabledSortIndex = showDisabledServices
      ? newIndex
      : this.all.indexOf(this.enabled[newIndex]);

    this.all.splice(
      newEnabledSortIndex,
      0,
      this.all.splice(oldEnabledSortIndex, 1)[0],
    );

    const services = {};
    // TODO: simplify this
    for (const [index] of this.all.entries()) {
      services[this.all[index].id] = index;
    }

    this.reorderServicesRequest.execute(services);
    this.allServicesRequest.patch((data: Service[]) => {
      for (const s of data) {
        s.order = services[s.id];
      }
    });
  }

  @action _toggleNotifications({ serviceId }) {
    const service = this.one(serviceId);

    this.actions.service.updateService({
      serviceId,
      serviceData: {
        isNotificationEnabled: !service.isNotificationEnabled,
      },
      redirect: false,
    });
  }

  @action _toggleAudio({ serviceId }) {
    const service = this.one(serviceId);

    this.actions.service.updateService({
      serviceId,
      serviceData: {
        isMuted: !service.isMuted,
      },
      redirect: false,
    });
  }

  @action _toggleDarkMode({ serviceId }) {
    const service = this.one(serviceId);

    this.actions.service.updateService({
      serviceId,
      serviceData: {
        isDarkModeEnabled: !service.isDarkModeEnabled,
      },
      redirect: false,
    });
  }

  @action _openDevTools({ serviceId }) {
    const service = this.one(serviceId);
    if (service.isTodosService) {
      this.actions.todos.openDevTools();
    } else if (service.webview) {
      service.webview.openDevTools();
    }
  }

  @action _openDevToolsForActiveService() {
    const service = this.active;

    if (service) {
      this._openDevTools({ serviceId: service.id });
    } else {
      debug('No service is active');
    }
  }

  @action _hibernate({ serviceId }) {
    const service = this.one(serviceId);
    if (!service.canHibernate) {
      return;
    }

    debug(`Hibernate ${service.name}`);

    service.isHibernationRequested = true;
    service.lastHibernated = Date.now();
  }

  @action _awake({
    serviceId,
    automatic,
  }: {
    serviceId: string;
    automatic?: boolean;
  }) {
    const now = Date.now();
    const service = this.one(serviceId);
    const automaticTag = automatic ? ' automatically ' : ' ';
    debug(
      `Waking up${automaticTag}from service hibernation for ${service.name}`,
    );

    if (automatic) {
      // if this is an automatic wake up, use the wakeUpHibernationStrategy
      // which sets the lastUsed time to an offset from now rather than to now.
      // Also add an optional random splay to desync the wakeups and
      // potentially reduce load.
      //
      // offsetNow = now - (hibernationStrategy - wakeUpHibernationStrategy)
      //
      // if wUHS = hS = 60, offsetNow = now.  hibernation again in 60 seconds.
      //
      // if wUHS = 20 and hS = 60, offsetNow = now - 40.  hibernation again in
      // 20 seconds.
      //
      // possibly also include splay in wUHS before subtracting from hS.
      //
      const mainStrategy = this.stores.settings.all.app.hibernationStrategy;
      let strategy = this.stores.settings.all.app.wakeUpHibernationStrategy;
      debug(`wakeUpHibernationStrategy = ${strategy}`);
      debug(`hibernationStrategy = ${mainStrategy}`);
      if (!strategy || strategy < 1) {
        strategy = this.stores.settings.all.app.hibernationStrategy;
      }
      let splay = 0;
      // Add splay.  This will keep the service awake a little longer.
      if (
        this.stores.settings.all.app.wakeUpHibernationSplay &&
        Math.random() >= 0.5
      ) {
        // Add 10 additional seconds 50% of the time.
        splay = 10;
        debug('Added splay');
      } else {
        debug('skipping splay');
      }
      // wake up again in strategy + splay seconds instead of mainStrategy seconds.
      service.lastUsed = now - ms(`${mainStrategy - (strategy + splay)}s`);
    } else {
      service.lastUsed = now;
    }
    debug(
      `Setting service.lastUsed to ${service.lastUsed} (${
        (now - service.lastUsed) / 1000
      }s ago)`,
    );
    service.isHibernationRequested = false;
    service.lastHibernated = null;
  }

  @action _resetLastPollTimer({ serviceId = null }) {
    debug(
      `Reset last poll timer for ${
        serviceId ? `service: "${serviceId}"` : 'all services'
      }`,
    );

    // eslint-disable-next-line unicorn/consistent-function-scoping
    const resetTimer = (service: Service) => {
      service.lastPollAnswer = Date.now();
      service.lastPoll = Date.now();
    };

    if (serviceId) {
      const service = this.one(serviceId);
      if (service) {
        resetTimer(service);
      }
    } else {
      for (const service of this.allDisplayed) resetTimer(service);
    }
  }

  // Reactions
  _focusServiceReaction() {
    const service = this.active;
    if (service) {
      this.actions.service.focusService({ serviceId: service.id });
      document.title = `Ferdium - ${service.name} ${
        service.dialogTitle ? ` - ${service.dialogTitle}` : ''
      } ${service._webview ? `- ${service._webview.getTitle()}` : ''}`;
    } else {
      debug('No service is active');
    }
  }

  _saveActiveService() {
    const service = this.active;
    if (service) {
      this.actions.settings.update({
        type: 'service',
        data: {
          activeService: service.id,
        },
      });
    } else {
      debug('No service is active');
    }
  }

  _mapActiveServiceToServiceModelReaction() {
    const { activeService } = this.stores.settings.all.service;
    if (this.allDisplayed.length > 0) {
      for (const service of this.allDisplayed) {
        this._setIsActive(
          service,
          activeService
            ? activeService === service.id
            : this.allDisplayed[0].id === service.id,
        );
      }
    }
  }

  _getUnreadMessageCountReaction() {
    const { showMessageBadgeWhenMuted } = this.stores.settings.all.app;
    const { showMessageBadgesEvenWhenMuted } = this.stores.ui;

    const unreadServices: UnreadServices = [];
    let unreadDirectMessageCount = 0;
    let unreadIndirectMessageCount = 0;

    if (showMessageBadgesEvenWhenMuted) {
      for (const s of this.allDisplayed) {
        if (s.isBadgeEnabled) {
          const direct =
            showMessageBadgeWhenMuted || s.isNotificationEnabled
              ? s.unreadDirectMessageCount
              : 0;
          const indirect =
            showMessageBadgeWhenMuted && s.isIndirectMessageBadgeEnabled
              ? s.unreadIndirectMessageCount
              : 0;
          unreadDirectMessageCount += direct;
          unreadIndirectMessageCount += indirect;
          if (direct > 0 || indirect > 0) {
            unreadServices.push([s.name, direct, indirect]);
          }
        }
      }
    }

    // We can't just block this earlier, otherwise the mobx reaction won't be aware of the vars to watch in some cases
    if (showMessageBadgesEvenWhenMuted) {
      this.actions.app.setBadge({
        unreadDirectMessageCount,
        unreadIndirectMessageCount,
      });
      ipcRenderer.send(
        'updateDBusUnread',
        unreadDirectMessageCount,
        unreadIndirectMessageCount,
        unreadServices,
      );
    }
  }

  _logoutReaction() {
    if (!this.stores.user.isLoggedIn) {
      this.actions.settings.remove({
        type: 'service',
        key: 'activeService',
      });
      this.allServicesRequest.invalidate().reset();
    }
  }

  _handleMuteSettings() {
    const { enabled } = this;
    const { isAppMuted } = this.stores.settings.app;

    for (const service of enabled) {
      const { isAttached } = service;
      const isMuted = isAppMuted || service.isMuted;

      if (isAttached && service.webview) {
        service.webview.audioMuted = isMuted;
      }
    }
  }

  _shareSettingsWithServiceProcess(): void {
    const settings = {
      ...this.stores.settings.app,
      isDarkThemeActive: this.stores.ui.isDarkThemeActive,
    };
    this.actions.service.sendIPCMessageToAllServices({
      channel: 'settings-update',
      args: settings,
    });
  }

  _cleanUpTeamIdAndCustomUrl(recipeId: string, data: Service): any {
    const serviceData = data;
    const recipe = this.stores.recipes.one(recipeId);

    if (!recipe) return;

    if (
      recipe.hasTeamId &&
      recipe.hasCustomUrl &&
      data.team &&
      data.customUrl
    ) {
      // @ts-expect-error The operand of a 'delete' operator must be optional.
      delete serviceData.team;
    }

    return serviceData;
  }

  _checkForActiveService() {
    if (
      !this.stores.router.location ||
      this.stores.router.location.pathname.includes('auth/signup')
    ) {
      return;
    }

    if (
      this.allDisplayed.findIndex(service => service.isActive) === -1 &&
      this.allDisplayed.length > 0
    ) {
      debug('No active service found, setting active service to index 0');

      this._setActive({ serviceId: this.allDisplayed[0].id });
    }
  }

  // Helper
  _initializeServiceRecipeInWebview(serviceId: string) {
    const service = this.one(serviceId);

    if (service.webview) {
      // We need to completely clone the object, otherwise Electron won't be able to send the object via IPC
      const shareWithWebview = cleanseJSObject(service.shareWithWebview);

      debug('Initialize recipe', service.recipe.id, service.name);
      service.webview.send(
        'initialize-recipe',
        {
          ...shareWithWebview,
          franzVersion: ferdiumVersion,
        },
        service.recipe,
      );
    }
  }

  _initRecipePolling(serviceId: string) {
    const service = this.one(serviceId);

    const delay = ms('2s');

    if (service) {
      if (service.timer !== null) {
        clearTimeout(service.timer);
      }

      const loop = () => {
        if (!service.webview) return;

        service.webview.send('poll');

        service.timer = setTimeout(loop, delay);
        service.lastPoll = Date.now();
      };

      loop();
    }
  }

  _wrapIndex(index: number, delta: number, size: number) {
    return (((index + delta) % size) + size) % size;
  }
}