-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgeneral_monitor.user.js
More file actions
2121 lines (1798 loc) · 87.9 KB
/
Copy pathgeneral_monitor.user.js
File metadata and controls
2121 lines (1798 loc) · 87.9 KB
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
// ==UserScript==
// @name Tau Station: General Monitor
// @namespace https://github.com/taustation-fan/userscripts/
// @downloadURL https://github.com/taustation-fan/userscripts/raw/master/general_monitor.user.js
// @version 0.9
// @description Monitors the page, reacting based on the information available (including scheduling notifications, updating item text based on player details, etc.).
// @author Mark Schurman (https://github.com/quasidart)
// @match https://taustation.space/*
// @grant none
// @require https://code.jquery.com/jquery-3.3.1.min.js
// @require https://github.com/taustation-fan/userscripts/raw/master/taustation-tools-common.js
// @require https://github.com/taustation-fan/tau-push/raw/master/static/push.min.js
// @require https://github.com/taustation-fan/userscripts/raw/master/userscript-preferences.js
// ==/UserScript==
//
// License: CC-BY-SA
//
// Disclaimer:
// These are quick-and-dirty one-off scripts, and do not reflect the author's style or quality of work when developing production-ready software.
//
// Changelist:
// - v0.1: Notification when Stats are fully refilled.
// - v0.2: Enhance Stim info: Show % effect on current player (toxicity given player's Tier, boost to Stat(s) X(,Y,Z) given player's Stats & Medical Stim skill level, etc.)
// - v0.3: Notification before shuttle departure / on arrival, when Brig / Sick Bay confinement ends, before Hotel Room reservation expires, and/or when player gains Experience or Bonds.
// - v0.4: Notification: Checks if stats change again (& reschedules if needed); if multiple tabs, only one tab schedules notifications.
// - v0.5: Added dynamic UI; also notifies when ship finishes refueling.
// - v0.6: Notify Career XP changes (gain or loss), filter notifying via jQuery selector, workaround for credits (exact amts no longer available w/o click), handle >1 day since last "daily" update, updated Ruins timers to check for the Wrecks.
// - v0.7: Change self-managed config to use userscript-preferences.
// - v0.7.1: Firefox now requires a user-generated event before it will ask user for Notification permissions.
// - v0.8: Catch back up with site after using w/o updating for *checks calendar* ~16 months(!).
//
// Issues:
//
// Todo:
// - Additional monitoring:
// - notify_syndicate_credits_increase & notify_syndicate_bonds_increase
// - Add multi-day timers:
// - Visa expiration
// - University class completion
// - Well Fed boon: Possible to tell duration anymore?
// - Move Hotel Room expiration to this approach/section?
// - Improve "multiple-timers" UI support:
// - Userscript's icon drops/rolls down a list of icons that are active?
// - In expanded UI, show when a single category has multiple active timers. (Have $('#tSM-timer-display') show multiple rows? Have category's icon roll down a 2nd icon for the second timer?)
//
'use strict';
//////////////////////////////
// Begin: User Configuration.
//
var local_config = {
debug: localStorage.tST_debug || false,
dump_notifications: false,
};
const monitor_prefs_key = 'general_monitor_prefs';
const possible_notification_areas = new Map( [
['/', 'Character details page'],
['/character/inventory', 'Inventory page'],
['/area/hotel-rooms/enter-room', 'Hotel Room (safe area)'],
['jquery:.on-board', 'Public/private Ship (safe area)'],
['/area/career', 'Employment area'],
['/area/the-wrecks', 'Ruins: The Wrecks (Sewers, LfT, Search Ruins)'],
['/area/the-wilds', 'Ruins: The Wilds (Syndicate Campaigns)'],
] );
function general_monitor_preferences_definition() {
return {
key: monitor_prefs_key,
label: 'General Monitor',
options: [
{
type: "heading",
text: "General configuration:"
},
// TODO: Add support for this?
// {
// key: 'show_expiry_as_gct',
// label: 'Show "expires at" times as GCT',
// help: "Show notifications' scheduled time using GCT, instead of Auld Earth's 24h time format (default).",
// type: 'boolean',
// default: false
// },
{
key: 'also_notify_console',
label: "Echo all notifications in browser's JavaScript Console",
type: 'boolean',
default: true
},
{
key: 'use_brief_notifications',
label: 'Show brief messages in notifications',
help: "With some browsers/devices, compacting text within notifications can be helpful.\n" +
"(E.g.: Mobile browsers tend to use the mobile OS's notifications bar. On Windows 10,\n" +
"Chrome uses Windows' notification popups/system, while Firefox uses its own popups.)",
type: 'boolean',
default: (window.navigator.userAgent.match(/\bWindows\b[^;]+ 10.0/) !== null &&
window.navigator.userAgent.match(/\bChrome\//) !== null)
},
{
key: 'stats_rescan_period',
label: 'Rescan page how often? (in minutes)',
help: "The page will be rescanned every N minutes, to check if any new notifications need to be scheduled.\n" +
"For example: if the player uses up some of a stat in one tab, the site updates your stats in all Tau Station tabs.\n" +
"Rescanning allows you to get a \"Stats refilled!\" notification even if a different tab is handling notifications.",
type: 'text',
default: 15
},
{
key: 'reuse_notification_delta',
label: "Rescans: Don't schedule new event if within N seconds of existing event",
help: "When scheduling, reuse an existing notification if it's within N seconds of new notification (of same type).\n" +
"For example: During a rescan, the new stats notification could be slightly off from the previously-scheduled\n" +
"notification (if web page is slow), or very far off from it (if stats decreased due to action in another tab).",
type: 'text',
default: '60'
},
// Notifications for misc. events.
{
type: "heading",
text: "Select desired notifications:"
},
{
key: 'notify_stats_refilled',
label: 'Notify when Focus & stat bars have refilled',
type: 'boolean',
default: true
},
{
key: 'notify_confinement_timer',
label: 'Notify when released from Brig / Sick Bay',
type: 'boolean',
default: true
},
{
key: 'notify_hotel_timer',
label: 'Notify a few minutes before Hotel Room reservation expires',
help: "Shows notification shortly before your Hotel reservation is set to expire.\n" +
"Note: Tracks the reservation for the last Hotel Room you entered.",
type: 'boolean',
default: true
},
{
key: 'notify_repair_timer',
label: 'Notify when finished with repairs (items or ship)',
type: 'boolean',
default: true
},
{
key: 'notify_ruins_timers',
label: 'Notify when Ruins campaigns become available\n' +
'(Look For Trouble, Sewers, Syndicate Campaign)',
help: "If sewers/campaign is won before the cooldown period expires (making Tau's global timer\n" +
"disappear), you can still set this notification using the in-area timers in The Wrecks / The Wilds.",
type: 'boolean',
default: true
},
{
key: 'notify_shuttle_timers',
label: 'Notify when Ship/Shuttle about to leave or just arrived',
help: "Shows a notification before Shuttle departs, and when Shuttle or private Ship arrives at its destination.\n" +
"(For departure: shows a warning 90s before, and an alert 20s before -- unless Player is already in Local Shuttles.)",
type: 'boolean',
default: true
},
{
key: 'notify_refuel_timer',
label: 'Notify when finished refueling Ship(s)',
help: 'Tracks multiple ships independently.\n' +
'(Timer UI shows when the first ship will finish.)',
type: 'boolean',
default: true
},
{
key: 'notify_syndicate_experience_increase',
label: 'Notify when Syndicate XP increases',
help: "This notification is shown only in the Syndicate details page.",
type: 'boolean',
default: true
},
{
key: 'notify_career_experience_increase',
label: 'Notify when Player Career XP increases',
help: "This notification is shown only in the Character details page.\n" +
"For players with multiple careers, each career's XP is tracked separately.",
type: 'boolean',
default: true
},
{
key: 'notify_experience_increase',
label: 'Notify when Player XP increases',
type: 'boolean',
default: true
},
{
key: 'warn_experience_when_over',
label: 'Notify when Player XP at/over n%',
help: "Warn Player when their Experience is at or over the specified percentage value.\n" +
"Useful for players on an XP diet. To disable, set this to 0.",
type: 'text',
default: 99
},
{
key: 'where_notify_experience',
label: 'Show Player XP notification in areas:',
help: "These options limit where Experience notifications are shown.\n" +
"To show Experience notifications everywhere, clear these options.",
type: "boolean_array",
options: possible_notification_areas
},
{
key: 'where_notify_experience_jquery',
label: 'Show Player XP notification in areas: (JQuery selector; optional)',
help: "Show Experience notification when page matches one of the following jQuery selectors.",
type: 'text',
default: ''
},
{
key: 'notify_credits_increase',
label: 'Notify when Player gains/loses credits',
type: 'boolean',
default: true
},
{
key: 'notify_credits_each_day',
label: 'Daily: Notify about Player\'s total Credits gained/lost during previous day',
help: "Shows a notification once per day (first visit to Tau Station website),\n" +
"showing total credits gained since the prior daily notification.",
type: 'boolean',
default: true
},
{
key: 'where_notify_credits',
label: 'Show Player Credits notification in areas:',
help: "These options limit where Credits notifications are shown.\n" +
"To show Credits notifications everywhere, clear these options.",
type: "boolean_array",
options: possible_notification_areas
},
{
key: 'where_notify_credits_jquery',
label: 'Show Player Credits notification in areas: (JQuery selector; optional)',
help: "Show Credits notification when page matches one of the following jQuery selectors.",
type: 'text',
default: ''
},
{
key: 'notify_bonds_increase',
label: 'Notify when Player gains/loses Bonds',
type: 'boolean',
default: true
},
]
};
}
var tSM_config = {};
//
// End: User Configuration.
//////////////////////////////
//////////////////////////////
// All lines below are less-configurable or non-user-configurable.
//
const GCT_SECONDS_PER_UNIT = 0.864;
var log_prefix = '[General Monitor] ';
var ui = {
'Stats' : {
'notify_stats_refilled': {
'icon': '<span>Refilled</span>',
'label': 'Time remaining until Stats have refilled' },
},
'Timers' : {
'notify_confinement_timer' : '<span class="fa fa-lock"/>', // or jail bars: '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4ggXFjYsyYkWmgAAAlBJREFUSMfd1juIFGkQB/Bf9w7YCIrCnC64uN7JYSKcj+QMDUQMVMTAg0MHs4sUU1+JYOADMTtBgxbU1MTA1MRIRTARMZFT2LuWWxHdFt1pA6vxo+lFA00sGLqn/lX/r+qrx0xWlNUbzKLBYiz3SeYxE/oMywKHt4lPhpWYCOz/wDMsy8Nwuh4Np3DIZ5nBNFZjDa4n2PXQrQ6bmQQ7FFzTmM0jinGA48SwwbgeDcehb74SS7maPFJpZaH3L8mCHLnvLD/IAVEsmEuLlegXlKTQUo7Wd4BxUVa/4Ai2JYZTRVmdwQl86CMvymoRTmEqUZ8uymorLmA8wCRu4Qr+6nAcxe+409MpY2zBBmzt+G0Ozskcr7G7Hg3PYSMOYn98fsWuejRseq6mwc6wae0PYmM9Gp7HbrwexFg/Cb+ruNG5z7tFWV3rXNOHoqw2YXsEVSTY+3g+wdtBpJvFNO7B+thD7VX8jKedjstDtxYnk0mewCNcbnkHncwf4Fni8A578VOnU8ZYgX9xE4uSgF6mhN0DDuC3yKDdUUvwvCeDfwI7Ht+zyOAh7qUHNEnEf2NVEE9Ei+5A3XNAHdjZaNX50D9PFmLT1mBzUVZ/Ymk4ZgnRfFKjdJtmCemeRF8UZfUK19oaTEbkx7AOF8P4P2zquZ50Fu7hD9yPOsFhPMaldg5msa8eDW93CvQeL/pmoDMLL5LWhJfBta/9wZmrR8On33rJBedcjqwoq2++VYMzy3uK1/f+JVmQo+2iPFoz7xQxL8pK0uddrOnB8uSZZd/7b8tH9ErQsbBStNsAAAAASUVORK5CYII=">',
'notify_hotel_timer' : {
'icon': '<span class="fa fa-bed"/>',
'label': 'Hotel time remaining (only when <1 day left)' },
'notify_repair_timer' : '<span class="fa fa-wrench"/>',
'notify_ruins_timers' : {
'icon': '<span class="fa tSM-icon tSM-ruins"/>', // Icon added by CSS section below (.tSM-ruins:before) -- allows mobile users to long-press to show timer details, without this text-based icon being highlighted as a text selection.
'label': 'Ruins campaign timers' },
'notify_shuttle_timers' : '<span class="fa fa-rocket"/>', // Not fa-shuttle, since that icon's wider than the others.
'notify_refuel_timer' : {
'icon': '<span class="fa tSM-icon tSM-refuel"/>', // Icon added by CSS section below (.tSM-refuel:before) -- allows mobile users to long-press to show timer details, without this text-based icon being highlighted as a text selection.
'label': 'Ship refueling time remaining' },
},
'XP gain' : {
'notify_experience_increase': {
'icon' : '<span class="fa fa-user"/>', // or 'XP',
'label' : 'Notify when your experience has increased (only when in specific rooms)' },
'notify_career_experience_increase': {
'icon' : '<span class="fa fa-id-badge"/>',
'label' : 'Notify when your Career experience has increased (only while viewing the character details page)' },
//TODO(?): Implement UI w/ editable numeric field.
// 'warn_experience_when_over': {
// 'icon' : '<span class="fa fa-exclamation-triangle"/>', // or '>=', // or '##',
// 'label' : 'Highlight Experience field when XP is greater than some value.',
// 'type' : 'text' },
//TODO(?): Implement UI w/ list of station areas. (Maybe: Leverage existing Areas list?)
// 'where_notify_experience': '<span class="fa fa-map-marker"/>', // or '🗺', (🗺 WORLD MAP)
'notify_syndicate_experience_increase': {
'icon' : '<span class="fa fa-users"/>', // aka '👥', (👥 BUSTS IN SILHOUETTE)
'label' : 'Notify when Syndicate experience has increased (only when viewing Syndicate info)' },
},
'Income': {
'notify_credits_increase' : {
'icon' : '<svg><use xlink:href="/static/images/icons.svg#icon-credchip"></use></svg>', // or '₢', (₢ CRUZEIRO SIGN)
'label' : 'Notify when your credits have increased (only when in specific rooms)' },
'notify_credits_each_day' : {
'icon' : '<span class="fa fa-sun-o"/>', // or '🌙', (🌙 CRESCENT MOON)
'label' : 'In morning, report total change in credits over past day' },
//TODO(?): Implement UI w/ list of station areas. (Maybe: Leverage existing Areas list?)
// 'where_notify_credits': {
// 'icon' : '<span class="fa fa-map-marker"/>', // or '🗺', (🗺 WORLD MAP)
// 'type' : 'select'?
// },
'notify_bonds_increase' : {
'icon' : '<svg><use xlink:href="/static/images/icons.svg#icon-bond"></use></svg>',
'label' : 'Notify when your bonds increase' },
},
}
var next_rescan_delta = 15 * 60 * 1000; // Safe value (15 mins), in case it doesn't get overridden below.
var notifications = {};
notifications.handles = {}
notifications.timestamps = {};
async function start_general_monitor() {
tSM_config = userscript_preferences( general_monitor_preferences_definition() );
// "boolean_array" config options end up containing any option that has ever been enabled,
// even if they're currently disabled. Clean these up by removing currently-disabled options.
tSM_config.where_notify_credits = remove_unset_keys(tSM_config.where_notify_credits);
tSM_config.where_notify_experience = remove_unset_keys(tSM_config.where_notify_experience);
next_rescan_delta = tSM_config['stats_rescan_period'] * 60 * 1000
// Set up a tab-specific ID, so only one tab is generating notifications at a time.
if (! sessionStorage.tS_id) {
sessionStorage.tS_id = Math.random() * 0x0FFFFFFFFFFFFFFF;
}
tSM_add_UI();
ensure_notifications_allowed();
set_up_notifications();
notifications.timestamps.next_rescan = new Date(Date.now() + next_rescan_delta);
window.setInterval(set_up_notifications, next_rescan_delta);
}
//////////////////////////////
// #region UI-related code.
//
function tSM_add_UI() {
// Make sure the common base UI has been added. (Shouldn't be needed, but $(document).ready(...) isn't calling taustation-tools-common.js's entry first, even though it should be added before ours.)
tST_add_base_UI();
// Add the section for this script's UI (vs. sibling scripts).
tST_region.append(`
<div id="tSM-region" class="tST-section tST-control-bar">
<div id="tSM-enabled-header" style="display:flex; width:100%; justify-content:space-between; display:none">
<span style="float:left; width:auto;">Monitors</span>
<span id="tSM-timer-display" style="float:right; width:auto; display:none;"></span>
</div>
<div id="tSM-disabled-header" style="display:flex; width:100%; justify-content:space-between; display:none">
<span id="tSM-region-title" style="float:left; width:auto; vertical-align:bottom;">Monitors</span>
<span style="width:auto; vertical-align:bottom;" title="Another tab is already responsible for handling notifications.">
<font size="-1"><i>(turn <font color="#279702">on</font>/<font color="#2d7ab9">off</font> only)</i></font>
</span>
<span style="float:right; width:auto; vertical-align:bottom;">
<font size="-1"><b><u><a id="tSM-take-control" style="color:#08a1ec; border:none; cursor: pointer;" title="Take control away from the other tab: handle notifications in this tab.">Take Control</a></u></b></font>
</span>
</div>
<div id="tSM-body">
<div id="tSM-request-permission-dialog" style="background-color: #444d;margin: 1em;margin-top: 0; display:none;">
<a id="tSM-request-permission" class="tST-icon-link" style="margin:1em; padding:0.3em; font-size:0.9em; font-style:italic; color:#08a1ec;">
Click to request permission to show Notifications
</a>
</div>
</div>
</div>
`);
// Add an icon that shows/hides the above UI, and can indicate info about the current combat log.
tST_add_icon('#general-monitor-icon', '#tSM-region', `
<a id="general-monitor-icon" class="tST-icon-link" title="General Monitors:">
<li class="tST-icons-list-entry" style="position:relative;">
<span id="gm-scheduled-badge" class="notification" data-badge="0" style="position:absolute; top:-8px; right:4px; display:none"></span>
</li>
</a>`);
tSM_populate_ui();
}
function tSM_set_enabled(is_enabled) {
if (is_enabled) {
tST_nodes['#general-monitor-icon'].find('li').each(function() {
// Update the userscript's icon, but leave the "Push permissions needed" overlay if it's present.
let live_icon = $(this).find('.gm-live-icon');
if (! live_icon.hasClass('gm-enabled')) {
live_icon.detach();
$(this).prepend('<span class="gm-live-icon gm-enabled fa fa-comments" style="vertical-align: top;"/>'); // Other options: '💬' (💬 SPEECH BALLOON), '🔔' (🔔 BELL)
}
});
$('#tSM-disabled-header').hide();
$('#tSM-enabled-header' ).show();
$('#tSM-take-control').off('click');
} else {
tST_nodes['#general-monitor-icon'].find('li').each(function() {
// Update the userscript's icon, but leave the "Push permissions needed" overlay if it's present.
$(this).find('.gm-live-icon').detach();
$(this).prepend('<span class="gm-live-icon gm-disabled" style="vertical-align: top;">💤</span>'); // ('💤' SLEEPING SYMBOL); another option: '🔕' (🔕 BELL WITH CANCELLATION STROKE)
});
$('#gm-scheduled-badge').hide();
$('#tSM-enabled-header' ).hide();
$('#tSM-disabled-header').show();
$('#tSM-take-control').click(function() {
localStorage.setItem('tSM_notifications_tab', sessionStorage.tS_id);
tSM_set_enabled(true);
set_up_notifications();
});
// Clear any notifications we have pending; if another tab took ownership, it will reschedule them.
for (var notification_key in notifications.handles) {
window.clearTimeout(notifications.handles[notification_key]);
notifications.handles [notification_key] = undefined;
notifications.timestamps[notification_key] = undefined;
}
if (notifications.timestamps) {
dump_notifications('This tab is now disabled; cleared any notifications we scheduled.')
}
}
}
function tSM_populate_ui() {
var tSM_area = $("#tSM-body");
// This userscript's UI is a table of icons (with hidden checkboxes):
// - Green icon border = notification currently enabled;
// - Highlighted icon = timer currently active.
//
// The resulting CSS is not short, so it's specified at the end of this file.
//
tST_add_css(css_for_icons_table);
tSM_area.append('<table><tbody id="tSM-togglers-table"/></table>\n');
tSM_area.find('#tSM-timer-display').hide();
var table = tSM_area.find('#tSM-togglers-table');
let total_notifications = 0;
// Show related icons on the same line, with all icons cleanly aligned horizontally & vertically.
for (var group in ui) {
table.append('<tr><td><span class="tSM_group" id="header-group-' + group.replace(/ /g, "_") + '">' + group + ': </span></td><td id="group-' + group.replace(/ /g, '_') + '"/></tr>\n');
var column = table.find('#group-' + group.replace(/ /g, '_'));
for (var key in ui[group]) {
let { icon, label } = lookupIconAndLabel(key, group);
label = label.replace(/^notify_/, '').replace(/_/g, ' ')
.replace(/timers?$/, 'time remaining');
if (label) {
label = label.substr(0, 1).toLocaleUpperCase() +
label.substr(1);
}
// Check if this notification is active.
var key_is_active = check_if_key_active(key);
if (group === 'Timers') {
total_notifications += key_is_active;
}
column.append(`
<div><a id="${key}" title="${label}" default-title="${label}">
<input id="${key}-checkbox" type="checkbox" ${(tSM_config[key] ? 'checked' : '')}
${(key_is_active? 'class="tSM-timer-active"' : '')}>
${icon}
</a></div>
`);
var ctlIcon = $('#' + key);
ctlIcon.click(function(evt) {
var target = evt.currentTarget;
var key = target.id;
var checkbox = $(target).find('input#' + key + '-checkbox');
if (tSM_config[key] === undefined || tSM_config[key] === false) {
tSM_config[key] = true
//d checkbox.attr('checked', undefined);
checkbox.get()[0].checked = tSM_config[key];
console.log(log_prefix + 'Enabled ' + key + '.');
} else if (tSM_config[key] === true) {
tSM_config[key] = false
//d checkbox.removeAttr('checked');
checkbox.get()[0].checked = tSM_config[key];
console.log(log_prefix + 'Disabled ' + key + '.');
}
localStorage.setItem(monitor_prefs_key, JSON.stringify(tSM_config));
});
// Allow Timer icons to show the local clock time when the timer will finish.
if (group == 'Timers' || group == 'Stats') {
// Desktop: React to mouse hover.
ctlIcon.hover(timer_hover_show_time,
timer_mouseout_hide_time);
//TODO: Either change the <a> tag above to a button, or change the header column to buttons that cycle through showing each active timer's deadline.
// Mobile, keyboard, screen-readers: React to keyboard focus.
ctlIcon.focusin (timer_hover_show_time);
ctlIcon.focusout(timer_mouseout_hide_time);
}
}
table.append('</td></tr>');
}
let badge = $('#gm-scheduled-badge');
if (badge.length) {
badge.attr('data-badge', total_notifications);
if (total_notifications) {
badge.show();
}
}
}
function lookupIconAndLabel(key, group) {
let icon;
let label;
// If caller didn't provide a group name, try to find the relevant group.
if (! group) {
for (let known_group in ui) {
if (! ui.hasOwnProperty(known_group)) {
continue;
}
if (ui[known_group].hasOwnProperty(key)) {
group = known_group;
break;
}
}
}
if (! group) {
return;
}
icon = ui[group][key];
label = key;
if (typeof icon === 'object') {
var obj = icon;
icon = obj.icon;
if (obj.label) {
label = obj.label;
}
}
return { icon, label };
}
function check_if_key_active(key) {
var retval = 0;
for (var keyTimestamp in notifications.timestamps) {
if (check_if_this_key_active(keyTimestamp, key)) {
retval++;
break;
}
}
return retval;
}
function check_if_this_key_active(keyTimestamp, key) {
return (keyTimestamp.startsWith(key) && notifications.timestamps[keyTimestamp]);
}
function timer_hover_show_time(evt) {
var target = evt.currentTarget;
var key = target.id;
var nameGroup = $(target).parent().parent().attr('id');
var prefix = '<span class="fa fa-clock-o"/> ';
var labelOverlay;
var firstTimerDate;
$('#tSM-timer-display').html('');
for (var keyTimestamp in notifications.timestamps) {
if (! check_if_this_key_active(keyTimestamp, key)) {
continue;
}
// Determine whether we have enough room to show the label (mainly helpful for mobile
// layout -- which, ironically, ends up with a wider area here than desktop layout).
if (stored_notifications_data[keyTimestamp + '_label']) {
let label = stored_notifications_data[keyTimestamp + '_label'];
let header = $('#tSM-enabled-header');
let header_width = (header.css('width') || '').replace('px', '') * 1;
let header_font = (header.css('font-size') || '').replace('px', '') * 1;
// We need at least 20.75em for "Monitors" + typical label + timer summary.
if (header_width && header_font && header_width / header_font >= 21) {
prefix = label + ' ' + prefix;
}
}
var timerDate = new Date(notifications.timestamps[keyTimestamp]);
// If multiple related notifications, show the one that'll happen first.
if (! firstTimerDate || firstTimerDate > timerDate) {
firstTimerDate = timerDate;
labelOverlay = prefix + summarize_timer_end(timerDate);
if (stored_notifications_data[keyTimestamp + '_tooltip']) {
let tooltip = stored_notifications_data[keyTimestamp + '_tooltip'];
$(target).attr('title', tooltip);
}
}
}
if (! labelOverlay) {
labelOverlay = prefix + '<i>inactive</i>';
}
$('#tSM-timer-display').append(`<div class=alert-time>${labelOverlay}</div>`);
$('#tSM-timer-display').show();
}
function summarize_timer_end(timer_date) {
let retval = ('00' + timer_date.getHours() ).substr(-2) + ':'
+ ('00' + timer_date.getMinutes()).substr(-2);
var cur_date = new Date();
if (timer_date && cur_date.getDate() !== timer_date.getDate()) {
let days_ahead = (timer_date.getTime() - Date.now()) / (24 * 60 * 60 * 1000);
if (days_ahead < 1) {
retval = 'Tomorrow @ ' + retval;
} else {
retval = `+${Math.floor(days_ahead)} days @ ` + retval;
}
}
return retval;
}
function timer_mouseout_hide_time(evt) {
var target = evt.currentTarget;
// Restore the original tooltip, in case we showed a more-detailed one.
$(target).attr('title', $(target).attr('default-title'));
$('#tSM-timer-display').hide();
$('#tSM-timer-display').html('');
}
//
// #endregion UI-related code.
//////////////////////////////
//////////////////////////////
// #region Notification: All Stats regenerated to 100%.
//
function ensure_notifications_allowed() {
if (! Push.Permission.has()) {
$('#general-monitor-icon li').append('<span class="fa fa-exclamation need-notification-permission-warning" style="position:absolute; top:50%; left:85%; color:#d76543;" title="Need permission to show notifications"></span>');
// First, try for an automatic prompt on page load. (Works with Chrome.)
Push.Permission.request(
function () { ; },
function () {
// Firefox only shows the "grant permissions?" dialog for user-generated events.
// Hence, we need to ask the user to click something, before Firefox will show it.
let table = $('#tSM-togglers-table');
let dialog = $('#tSM-request-permission-dialog');
let button = $('#tSM-request-permission');
table.hide();
dialog.show();
button.click(function() {
Push.Permission.request(
function () {
$('.need-notification-permission-warning').detach();
dialog.hide();
table.show();
},
function () {
alert('Permission not granted.\n' +
'The "General Monitor" userscript can\'t show notifications until you grant permission.');
});
});
});
}
}
let stored_notifications_data = {};
var other_tab_owner_reported = false;
var during_init = true;
function set_up_notifications() {
notifications.timestamps.next_rescan = new Date(Date.now() + next_rescan_delta);
load_scheduled_notifications();
// Handle things that should happen in all tabs.
if (during_init) {
if (tSM_config.warn_experience_when_over) {
warn_when_experience_is_over();
}
}
if (! localStorage.tSM_notifications_tab ||
localStorage.tSM_notifications_tab == sessionStorage.tS_id)
{
tSM_set_enabled(true);
localStorage.setItem('tSM_notifications_tab', sessionStorage.tS_id); // Claim (or reassert) ownership.
// Preprocess jQuery-based location matching criteria.
let where_notify_credits_jquery = collect_jquery_selectors(tSM_config.where_notify_credits,
tSM_config.where_notify_credits_jquery);
let where_notify_experience_jquery = collect_jquery_selectors(tSM_config.where_notify_experience,
tSM_config.where_notify_experience_jquery);
var info_notifications = [];
if (tSM_config.notify_stats_refilled) {
schedule_notify_when_stats_refilled();
}
if (tSM_config.notify_experience_increase && (in_matching_location(tSM_config.where_notify_experience) || in_matching_page(where_notify_experience_jquery))) {
info_notifications.push(notify_when_experience_increases('player'));
}
if (tSM_config.notify_syndicate_experience_increase && in_matching_location({ '/syndicates': true })) {
info_notifications.push(notify_when_experience_increases('syndicate'));
}
if (tSM_config.notify_career_experience_increase && in_matching_location({ '/': true })) {
//TEST: Change Career XP & Rank, to trigger a notification.
//t $('th:contains("Career Rank") ~ td').text(($('th:contains("Career Rank") ~ td').text() * 1) - 1);
//t $('th:contains("Career Experience") ~ td').text('97.2%');
//t $('th:contains("Career Experience") ~ td').text('1.3%');
info_notifications.push(notify_when_experience_increases('career'));
}
if (tSM_config.notify_credits_increase && (in_matching_location(tSM_config.where_notify_credits) || in_matching_page(where_notify_credits_jquery))) {
info_notifications.push(notify_when_credits_increase());
}
if (tSM_config.notify_bonds_increase) {
info_notifications.push(notify_when_bonds_increase());
}
// These events are only applicable when the page first loads.
if (during_init) {
if (tSM_config.notify_hotel_timer) {
schedule_notify_hotel_reservation_expiration();
}
if (tSM_config.notify_repair_timer) {
schedule_notify_repair_finished();
}
if (tSM_config.notify_confinement_timer) {
schedule_notify_confinement_release();
}
if (tSM_config.notify_shuttle_timers) {
schedule_notify_shuttle_departing_soon();
schedule_notify_shuttle_arriving_soon();
}
if (tSM_config.notify_refuel_timer) {
schedule_notify_refuel_finished();
}
if (tSM_config.notify_ruins_timers) {
schedule_notify_ruins_campaigns();
}
if (tSM_config.notify_credits_each_day && (in_matching_location(tSM_config.where_notify_credits) || in_matching_page(where_notify_credits_jquery))) {
schedule_notify_credits_each_day();
}
}
if (info_notifications.length) {
show_multi_notification('info', info_notifications);
}
// Finally, store any updated information we saved during the methods above.
save_scheduled_notifications();
} else {
if (! other_tab_owner_reported) {
debug(log_prefix + 'Another tab is handling notifications.');
other_tab_owner_reported = true;
tSM_set_enabled(false);
}
}
debug(log_prefix + 'Will rescan page at: ' + notifications.timestamps.next_rescan);
during_init = false;
}
function load_scheduled_notifications() {
stored_notifications_data = JSON.parse(localStorage.tsM_scheduled_notifications || '{}');
}
function save_scheduled_notifications() {
stored_notifications_data = remove_unset_keys(stored_notifications_data);
localStorage.setItem('tsM_scheduled_notifications', JSON.stringify(stored_notifications_data));
}
function collect_jquery_selectors(objLocations, strLocationsJquery) {
let arrSelectors = [];
for (let key in objLocations) {
if (key.startsWith('jquery:') && objLocations[key] === "true") {
arrSelectors.push(key.replace('jquery:', ''));
}
}
if (strLocationsJquery) {
arrSelectors.push(strLocationsJquery);
}
return arrSelectors;
}
function in_matching_location(objLocations) {
// Use the URL's path, without any "?_mid=87654321" suffix.
const url_path = window.location.pathname.replace(/\?.*$/, '');
return (! objLocations || jQuery.isEmptyObject(objLocations) ||
(objLocations.hasOwnProperty(url_path) &&
(objLocations[url_path] === true ||
objLocations[url_path] === "true")));
}
function in_matching_page(arrSelectors) {
var retval = false;
if (arrSelectors && arrSelectors.length >= 0) {
for (var ii = 0; ii < arrSelectors.length; ii++) {
if ($(arrSelectors[ii]).length) {
retval = true;
break;
}
}
}
return retval;
}
function remove_unset_keys(obj) {
let retval = obj;
if (obj) {
retval = {};
for (let key in obj) {
if (obj[key]) {
retval[key] = obj[key];
}
}
}
return retval;
}
function schedule_notify_when_stats_refilled() {
let timer_type = 'stats';
// First, calculate when this notification should happen (if at all).
var max_time = 0;
$('.player-stats .time-to-full .refill-timer').each(function () {
// Since this runs during every refresh, we need to read the GCT value instead of data-seconds-refill.
// (data-seconds-refill only updates every 5 mins, so our timer could easily bounce around +/- 5 mins.)
var value = get_gct_time_as_numeric($(this)) * GCT_SECONDS_PER_UNIT;
if (max_time < value) {
max_time = value;
}
});
if (max_time > 0) {
var message = 'Your stats have fully regenerated!';
set_notification(max_time * 1000, message, "info", 'notify_stats_refilled');
}
else {
debug(log_prefix + 'Stats are full; no notification needed.');
}
}
function schedule_notify_shuttle_departing_soon() {
var severity = 'warning';
let timer_name = 'notify_shuttle_timers' + '&ETD';
let not_active_debug_msg = 'Not waiting for shuttle';
// This appears as a global timer, and can appear in any area.
// Given that, we always regenerate the timer, instead of reusing the previously-saved timer.
// Scan for the following:
// <div class="timer shuttle-timer" role="region" aria-label="Shuttle countdown"
// --> data-seconds-left="534" data-timer-type="shuttle">
let timer_selector = 'div.shuttle-timer[data-timer-type="shuttle"]';
process_global_timer(timer_name, severity, not_active_debug_msg, timer_selector,
function(details) {
let label = 'Shuttle departure:';
let tooltip = 'Shuttle will depart at:';
let message = 'Shuttle departing soon!';
let shuttle_info = (details.timer_node.find('.eta p').first().text() || '');
if (shuttle_info) {
let destination = shuttle_info.trim().replace(/.*Your shuttle to (.*) leaves .*/, '$1');
if (destination !== shuttle_info) {
tooltip = tooltip.replace(/Shuttle\b/, `Shuttle to ${destination}`);
message = message.replace(/Shuttle\b/, `Shuttle to ${destination}`);
}
}
details.label = label;
details.message = message;
details.tooltip = tooltip;
details.except_in = '/area/local-shuttles';
return details;
},
function(details) {
let seconds_remaining, severity;
// Adjust seconds_remaining & severity, if necessary.
({ seconds_remaining, severity } = choose_early_notification_time(details.seconds_remaining, details.severity));
details.seconds_remaining = seconds_remaining;
details.severity = severity;
});
}
const delay_threshold_warning = 20;
function choose_early_notification_time(seconds_remaining, severity) {
// If it's several minutes from now, have it fire 2 minutes before departure time.
if (seconds_remaining > 150) {
seconds_remaining -= 120;
}
// If it's almost time, notify right now, unless we're already in the right location.
else if (seconds_remaining < delay_threshold_warning) {
seconds_remaining = 0; // Time's almost up -- notify right now!
severity = 'error'; // Get the user's attention.
}
// Otherwise, notify ~20 seconds before
else {
seconds_remaining -= delay_threshold_warning;
}
return { seconds_remaining, severity };
}
function schedule_notify_shuttle_arriving_soon() {
var severity = 'warning';
let timer_name = 'notify_shuttle_timers' + '&ETA';
let not_active_debug_msg = 'Not currently traveling';
// This appears as a global timer, and can appear in any area.
// Given that, we always regenerate the timer, instead of reusing the previously-saved timer.
// Scan for the following:
// <div class="timer shuttle-timer confinement-timer" role="region" aria-label="Travel countdown"
// data-seconds-left="926" data-timer-type="travel">
let timer_selector = 'div.shuttle-timer[data-timer-type="travel"]';
process_global_timer(timer_name, severity, not_active_debug_msg, timer_selector,
function (details) {
let label = 'Ship arrival:';
var message = 'Arrived at destination!\n(Travel finished.)';
let tooltip = "Ship will arrive at:";
let current_station = get_current_station();
if (current_station) {
tooltip = tooltip.replace('arrive', `reach ${current_station}`);
message = message.replace('destination', current_station);
}
let ship_name = ($('.cockpit-container h2 .name').text() || '').replace(/: $/, '');
if (ship_name) {
tooltip = tooltip.replace(/Ship\b/, `"${ship_name}"`);
}
details.label = label;
details.message = message;
details.tooltip = tooltip;