-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathloot.dart
1424 lines (1323 loc) · 49.7 KB
/
loot.dart
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
// Dart imports:
import 'dart:async';
// ignore: unused_import
import 'dart:developer';
import 'dart:io';
// Flutter imports:
import 'package:android_intent_plus/android_intent.dart';
// Package imports:
import 'package:bot_toast/bot_toast.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:torn_pda/drawer.dart';
import 'package:torn_pda/main.dart';
// Project imports:
import 'package:torn_pda/models/chaining/target_model.dart';
import 'package:torn_pda/models/loot/loot_model.dart';
import 'package:torn_pda/models/loot/loot_rangers_model.dart';
import 'package:torn_pda/pages/loot/loot_notification_android.dart';
import 'package:torn_pda/pages/loot/loot_notification_ios.dart';
import 'package:torn_pda/pages/profile_page.dart';
import 'package:torn_pda/providers/api_caller.dart';
import 'package:torn_pda/providers/settings_provider.dart';
import 'package:torn_pda/providers/theme_provider.dart';
import 'package:torn_pda/providers/webview_provider.dart';
import 'package:torn_pda/utils/notification.dart';
import 'package:torn_pda/utils/shared_prefs.dart';
import 'package:torn_pda/utils/time_formatter.dart';
import 'package:torn_pda/widgets/loot/loot_filter_dialog.dart';
import 'package:torn_pda/widgets/loot/loot_rangers_explanation.dart';
import 'package:torn_pda/widgets/webviews/chaining_payload.dart';
import 'package:torn_pda/widgets/webviews/pda_browser_icon.dart';
import 'package:torn_pda/widgets/webviews/webview_stackview.dart';
enum LootTimeType {
dateTime,
timer,
}
class LootPage extends StatefulWidget {
@override
LootPageState createState() => LootPageState();
}
class LootPageState extends State<LootPage> {
var _npcIds = <String>[];
var _filterOutIds = <String>[];
final _images = <NpcImagesModel>[];
final databaseReference = FirebaseDatabase.instance.ref();
bool? _dbLootRangersEnabled = false;
Map<String, LootModel> _mainLootInfo = <String, LootModel>{};
final Map<String, int> _dbLootInfo = <String, int>{};
Future? _getInitialLootInformation;
bool _apiSuccess = false;
late SettingsProvider _settingsProvider;
ThemeProvider? _themeProvider;
late WebViewProvider _webViewProvider;
bool _firstLoad = true;
int _tornTicks = 0;
late Timer _tickerUpdateTimes;
LootTimeType? _lootTimeType;
NotificationType? _lootNotificationType;
late int _lootNotificationAhead;
late int _lootAlarmAhead;
late int _lootTimerAhead;
late bool _alarmSound;
bool? _alarmVibration;
int _lootRangersTime = 0;
String _lootRangersClearAtZeroReason = "";
bool _lootRangersAttackOngoing = false;
final List<String> _lootRangersIdOrder = <String>[];
final List<String?> _lootRangersNameOrder = <String?>[];
// Payload is: 400idlevel (new: 499 for Loot Rangers)
final _activeNotificationsIds = <int>[];
@override
void initState() {
super.initState();
_settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
_getInitialLootInformation = _getLoot();
_getLootRangers();
analytics.setCurrentScreen(screenName: 'loot');
routeWithDrawer = true;
routeName = "loot";
_tickerUpdateTimes = Timer.periodic(const Duration(seconds: 1), (Timer t) => _getLoot());
}
@override
void dispose() {
_tickerUpdateTimes.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
_themeProvider = Provider.of<ThemeProvider>(context);
_webViewProvider = Provider.of<WebViewProvider>(context);
return Scaffold(
backgroundColor: _themeProvider!.canvas,
appBar: _settingsProvider.appBarTop ? buildAppBar() : null,
bottomNavigationBar: !_settingsProvider.appBarTop
? SizedBox(
height: AppBar().preferredSize.height,
child: buildAppBar(),
)
: null,
body: Container(
color: _themeProvider!.canvas,
child: FutureBuilder(
future: _getInitialLootInformation,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (_apiSuccess) {
return RefreshIndicator(
onRefresh: () async {
await _getLoot();
_getLootRangers();
await Future.delayed(const Duration(seconds: 1));
},
child: SingleChildScrollView(
child: Column(
children: <Widget>[
_lootRangersWidget(),
if (activeNpcsFiltered())
Padding(
padding: const EdgeInsets.fromLTRB(15, 10, 15, 0),
child: Text(
"Some NPCs are filtered out",
style: TextStyle(
color: Colors.orange[900],
fontSize: 12,
),
),
)
else
const SizedBox.shrink(),
if (_lootRangersIdOrder.isNotEmpty && _dbLootRangersEnabled!)
Padding(
padding: const EdgeInsets.fromLTRB(15, 10, 15, 0),
child: Text(
"NPCs sorted by ${_lootRangersTime == 0 ? 'previous ' : ''}Loot Rangers' attack order",
style: const TextStyle(
fontSize: 12,
),
),
),
Padding(
padding: const EdgeInsets.all(5),
child: _returnNpcCards(),
),
const SizedBox(height: 20),
],
),
),
);
} else {
return Column(
children: [
_lootRangersWidget(),
_connectError(),
],
);
}
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
),
);
}
AppBar buildAppBar() {
return AppBar(
iconTheme: IconThemeData(color: Colors.white),
elevation: _settingsProvider.appBarTop ? 2 : 0,
title: const Text('Loot', style: TextStyle(color: Colors.white)),
leadingWidth: _webViewProvider.webViewSplitActive ? 50 : 80,
leading: Row(
children: [
IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
final ScaffoldState? scaffoldState = context.findRootAncestorStateOfType();
if (scaffoldState != null) {
if (_webViewProvider.webViewSplitActive &&
_webViewProvider.splitScreenPosition == WebViewSplitPosition.left) {
scaffoldState.openEndDrawer();
} else {
scaffoldState.openDrawer();
}
}
},
),
if (!_webViewProvider.webViewSplitActive) PdaBrowserIcon(),
],
),
actions: <Widget>[
if (_apiSuccess)
IconButton(
icon: Icon(
MdiIcons.filterOutline,
color: activeNpcsFiltered() ? Colors.orange[400] : Colors.white,
),
onPressed: () {
showDialog(
useRootNavigator: false,
context: context,
builder: (BuildContext context) {
return LootFilterDialog(
allNpcs: _mainLootInfo,
filteredNpcs: _filterOutIds,
);
},
);
},
)
else
const SizedBox.shrink(),
if (_apiSuccess)
IconButton(
icon: const Icon(
MdiIcons.timerSandEmpty,
),
onPressed: () {
setState(() {
if (_lootTimeType == LootTimeType.timer) {
_lootTimeType = LootTimeType.dateTime;
Prefs().setLootTimerType('dateTime');
} else {
_lootTimeType = LootTimeType.timer;
Prefs().setLootTimerType('timer');
}
});
},
)
else
const SizedBox.shrink(),
if (_apiSuccess && Platform.isAndroid)
IconButton(
icon: Icon(
Icons.alarm_on,
color: _themeProvider!.buttonText,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LootNotificationsAndroid(
callback: _callBackFromNotificationOptions,
lootRangersEnabled: _dbLootRangersEnabled,
);
},
),
);
},
)
else
const SizedBox.shrink(),
if (_apiSuccess && Platform.isIOS)
IconButton(
icon: Icon(
Icons.alarm_on,
color: _themeProvider!.buttonText,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LootNotificationsIOS(
callback: _callBackFromNotificationOptions,
lootRangersEnabled: _dbLootRangersEnabled,
);
},
),
);
},
)
else
const SizedBox.shrink()
],
);
}
bool activeNpcsFiltered() {
return _npcIds.where((element) => _filterOutIds.contains(element)).isNotEmpty;
}
Widget _connectError() {
return const Padding(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'There was an error contacting the database, please try again later!',
style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Text('If this problem reoccurs, please let us know!'),
],
),
);
}
Widget _returnNpcCards() {
try {
// Final card of every NPC
final npcBoxes = <Widget>[];
// If Loot Rangers is active, return LR's order
if (_lootRangersIdOrder.isNotEmpty && _dbLootRangersEnabled!) {
final sortedMap = <String, LootModel>{};
final originalMap = Map<String, LootModel>.of(_mainLootInfo);
for (final id in _lootRangersIdOrder) {
originalMap.forEach((npcId, npcDetails) {
if (id == npcId) {
sortedMap.addAll({npcId: npcDetails});
}
});
}
_mainLootInfo = Map.from(sortedMap);
// Add the NPCs that might be missing in LootRangers
originalMap.forEach((npcId, npcDetails) {
if (!_lootRangersIdOrder.contains(npcId)) {
_mainLootInfo.addAll({npcId: npcDetails});
}
});
}
// Loop every NPC
_mainLootInfo.forEach((npcId, npcDetails) {
if (!_filterOutIds.contains(npcId)) {
// Get npcLevels in a column and format them
int thisIndex = 1;
final npcLevels = <Widget>[];
final npcLevelsColumn = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: npcLevels,
);
npcDetails.timings!.forEach((levelNumber, levelDetails) {
// Time formatting
final levelDateTime = DateTime.fromMillisecondsSinceEpoch(levelDetails.ts! * 1000);
final time = TimeFormatter(
inputTime: levelDateTime,
timeFormatSetting: _settingsProvider.currentTimeFormat,
timeZoneSetting: _settingsProvider.currentTimeZone,
).formatHour;
// Text string styling
bool isPast = false;
if (DateTime.now().isAfter(levelDateTime)) {
isPast = true;
}
bool isCurrent = false;
if (levelNumber == npcDetails.levels!.current.toString()) {
isCurrent = true;
}
String timeString = "Level $thisIndex";
var style = const TextStyle();
if (isPast && !isCurrent) {
timeString += " at $time";
style = const TextStyle(color: Colors.grey);
} else if (isCurrent) {
timeString += " (now)";
style = const TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
);
} else {
final timeDiff = levelDateTime.difference(DateTime.now());
final diffFormatted = _formatDuration(timeDiff);
if (_lootTimeType == LootTimeType.timer) {
timeString += " in $diffFormatted";
} else {
timeString += " at $time";
}
if (timeDiff.inMinutes < 10) {
if (npcDetails.levels!.next! >= 4) {
style = const TextStyle(
color: Colors.orange,
fontWeight: FontWeight.bold,
);
} else {
style = const TextStyle(
fontWeight: FontWeight.bold,
);
}
}
}
String? typeString;
IconData? iconData;
switch (_lootNotificationType!) {
case NotificationType.notification:
typeString = 'notification';
iconData = Icons.chat_bubble_outline;
case NotificationType.alarm:
typeString = 'alarm';
iconData = Icons.notifications_none;
case NotificationType.timer:
typeString = 'timer';
iconData = Icons.timer;
}
Widget notificationIcon;
if (!isPast && !isCurrent) {
bool isPending = false;
for (final id in _activeNotificationsIds) {
if (id == int.parse('400$npcId$levelNumber')) {
isPending = true;
}
}
notificationIcon = InkWell(
splashColor: Colors.transparent,
child: Icon(
iconData,
size: 20,
color: _lootNotificationType == NotificationType.notification && isPending ? Colors.green : null,
),
onTap: () async {
switch (_lootNotificationType!) {
case NotificationType.notification:
if (isPending) {
setState(() {
isPending = false;
});
await flutterLocalNotificationsPlugin.cancel(int.parse('400$npcId$levelNumber'));
_activeNotificationsIds.removeWhere((element) => element == int.parse('400$npcId$levelNumber'));
} else {
setState(() {
isPending = true;
});
_activeNotificationsIds.add(int.parse('400$npcId$levelNumber'));
if (_settingsProvider.discreteNotifications) {
_scheduleNotification(
levelDateTime,
int.parse('400$npcId$levelNumber'),
'400-$npcId',
"L",
"${npcDetails.name} - $levelNumber!",
);
} else {
_scheduleNotification(
levelDateTime,
int.parse('400$npcId$levelNumber'),
'400-$npcId',
"${npcDetails.name} loot",
"Approaching level $levelNumber!",
);
}
BotToast.showText(
clickClose: true,
text: 'Loot level $levelNumber'
' $typeString set for ${npcDetails.name}!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
}
case NotificationType.alarm:
_setAlarm(
levelDateTime,
"${npcDetails.name} level $levelNumber",
);
BotToast.showText(
clickClose: true,
text: 'Loot level $levelNumber'
' $typeString set for ${npcDetails.name}!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
case NotificationType.timer:
_setTimer(
levelDateTime,
"${npcDetails.name} level $levelNumber",
);
BotToast.showText(
clickClose: true,
text: 'Loot level $levelNumber'
' $typeString set for ${npcDetails.name}!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
}
},
);
} else {
notificationIcon = const SizedBox.shrink();
}
final timeRow = Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
timeString,
style: style,
),
Padding(
padding: const EdgeInsets.only(right: 15),
child: notificationIcon,
),
],
);
npcLevels.add(timeRow);
npcLevels.add(const SizedBox(height: 8));
thisIndex++;
});
Widget hospitalized;
if (npcDetails.status == "hospitalized") {
hospitalized = const Text(
'[HOSPITALIZED]',
style: TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold,
),
);
} else {
hospitalized = const SizedBox.shrink();
}
Widget knifeIcon;
knifeIcon = Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
child: Icon(
MdiIcons.knifeMilitary,
color: npcDetails.levels!.current! >= 4 ? Colors.red : _themeProvider!.mainText,
),
onTap: () async {
final url = 'https://www.torn.com/loader.php?sid=attack&user2ID=$npcId';
await context.read<WebViewProvider>().openBrowserPreference(
context: context,
url: url,
browserTapType: BrowserTapType.short,
);
},
onLongPress: () async {
final url = 'https://www.torn.com/loader.php?sid=attack&user2ID=$npcId';
await context.read<WebViewProvider>().openBrowserPreference(
context: context,
url: url,
browserTapType: BrowserTapType.long,
);
},
),
);
Color cardBorderColor() {
if (npcDetails.levels!.current! >= 4) {
return Colors.orange;
} else {
return Colors.transparent;
}
}
final Widget thisNpcImage = _images.firstWhere((element) => element.id == npcId).image;
npcBoxes.add(
Card(
shape: RoundedRectangleBorder(
side: BorderSide(color: cardBorderColor(), width: 1.5),
borderRadius: BorderRadius.circular(4.0),
),
elevation: 3,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
thisNpcImage,
Padding(
padding: const EdgeInsets.only(top: 10),
child: knifeIcon,
),
],
),
const SizedBox(width: 30),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
children: [
Text(
'${npcDetails.name} [$npcId]',
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(width: 10),
hospitalized,
],
),
),
const SizedBox(height: 10),
npcLevelsColumn,
],
),
),
],
),
),
),
);
}
});
final Widget npcWidget = Column(children: npcBoxes);
return npcWidget;
} catch (e, t) {
BotToast.showText(text: "Error loading @npcCards: $e");
FirebaseCrashlytics.instance.log("PDA Crash @npcCards");
FirebaseCrashlytics.instance.recordError("PDA Error: $e", t);
return const SizedBox.shrink();
}
}
Future _getLootRangers() async {
try {
final response = await http.get(Uri.parse("https://api.lzpt.io/loot"));
if (response.statusCode == 200) {
final lrJson = lootRangersFromJson(response.body);
// DEBUG
//final lrJson = lootRangersFromJson(lootRangersDebug);
if (lrJson.time!.clear == 0) {
_lootRangersTime = 0;
if (lrJson.time!.attack) {
_lootRangersAttackOngoing = true;
}
if (lrJson.time!.reason != null) {
_lootRangersClearAtZeroReason = lrJson.time!.reason!;
}
} else {
_lootRangersTime = lrJson.time!.clear! * 1000;
_lootRangersAttackOngoing = false;
_lootRangersClearAtZeroReason = "";
}
_lootRangersNameOrder.clear();
for (int i = 0; i < lrJson.order!.length; i++) {
final id = lrJson.order![i];
lrJson.npcs!.forEach((key, value) {
// If [clear] is false, the NPC won't participate in this attack
if (value.clear!) {
if (key == id.toString()) {
_lootRangersNameOrder.add(value.name);
_lootRangersIdOrder.add(key);
}
}
});
}
}
} catch (e, t) {
BotToast.showText(text: "Error loading @lootRangers: $e");
FirebaseCrashlytics.instance.log("PDA Crash @lootRangers");
FirebaseCrashlytics.instance.recordError("PDA Error: $e", t);
_lootRangersTime = 0;
_lootRangersIdOrder.clear();
_lootRangersNameOrder.clear();
}
}
Widget _lootRangersWidget() {
if (_lootRangersNameOrder.isEmpty || _lootRangersIdOrder.isEmpty || !_dbLootRangersEnabled!) {
return const SizedBox.shrink();
}
String timeString = "";
final lrDateTime = DateTime.fromMillisecondsSinceEpoch(_lootRangersTime);
final timeDiff = lrDateTime.difference(DateTime.now());
final diffFormatted = _formatDuration(timeDiff);
if (_lootTimeType == LootTimeType.timer) {
timeString += "in $diffFormatted";
} else {
final time = TimeFormatter(
inputTime: DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
timeFormatSetting: _settingsProvider.currentTimeFormat,
timeZoneSetting: _settingsProvider.currentTimeZone,
).formatHour;
timeString += "at $time";
}
// Loot Rangers notification icon
String? typeString;
IconData? iconData;
switch (_lootNotificationType!) {
case NotificationType.notification:
typeString = 'notification';
iconData = Icons.chat_bubble_outline;
case NotificationType.alarm:
typeString = 'alarm';
iconData = Icons.notifications_none;
case NotificationType.timer:
typeString = 'timer';
iconData = Icons.timer;
}
Widget notificationIcon;
bool isPending = false;
for (final id in _activeNotificationsIds) {
if (id == int.parse('499')) {
isPending = true;
}
}
notificationIcon = InkWell(
splashColor: Colors.transparent,
child: Icon(
iconData,
size: 20,
color: _lootNotificationType == NotificationType.notification && isPending ? Colors.green : null,
),
onTap: () async {
switch (_lootNotificationType!) {
case NotificationType.notification:
if (isPending) {
setState(() {
isPending = false;
});
await flutterLocalNotificationsPlugin.cancel(499);
_activeNotificationsIds.removeWhere((element) => element == 499);
} else {
setState(() {
isPending = true;
});
_activeNotificationsIds.add(499);
String? time = TimeFormatter(
inputTime: DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
timeFormatSetting: _settingsProvider.currentTimeFormat,
timeZoneSetting: _settingsProvider.currentTimeZone,
).formatHour;
if (_settingsProvider.discreteNotifications) {
_scheduleNotification(
DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
499,
'499-${_lootRangersIdOrder.join(",")}-${_lootRangersNameOrder.join(",")}-$time',
"LR",
"",
);
} else {
_scheduleNotification(
DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
499,
'499-${_lootRangersIdOrder.join(",")}-${_lootRangersNameOrder.join(",")}-$time',
"Loot Rangers attack!",
"Order: ${_lootRangersNameOrder.join(", ")}",
);
}
BotToast.showText(
clickClose: true,
text: 'Loot Rangers $typeString set!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
}
case NotificationType.alarm:
_setAlarm(
DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
"Loot Rangers",
);
BotToast.showText(
clickClose: true,
text: 'Loot Rangers $typeString set!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
case NotificationType.timer:
_setTimer(
DateTime.fromMillisecondsSinceEpoch(_lootRangersTime),
"Loot Rangers",
);
BotToast.showText(
clickClose: true,
text: 'Loot Rangers $typeString set!',
textStyle: const TextStyle(
fontSize: 14,
color: Colors.white,
),
contentColor: Colors.green[700]!,
duration: const Duration(milliseconds: 1500),
contentPadding: const EdgeInsets.all(10),
);
}
},
);
final int minutesRemaining = DateTime.fromMicrosecondsSinceEpoch(
_lootRangersTime * 1000,
).difference(DateTime.now()).inMinutes;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Loot Rangers", style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(width: 5),
GestureDetector(
onTap: () async {
await showDialog(
useRootNavigator: false,
context: context,
builder: (BuildContext context) {
return LootRangersExplanationDialog(
themeProvider: _themeProvider,
);
},
);
},
child: const Icon(
Icons.info_outline,
size: 20,
),
)
],
),
if (_lootRangersTime == 0 && !_lootRangersAttackOngoing)
Column(
children: [
Text("Next attack not set!", style: TextStyle(color: Colors.orange[700])),
if (_lootRangersClearAtZeroReason.isNotEmpty)
Text(
"Looting will resume after $_lootRangersClearAtZeroReason",
style: TextStyle(color: Colors.orange[700]),
),
],
)
else if (_lootRangersTime == 0 && _lootRangersAttackOngoing)
Text("ATTACK ONGOING NOW", style: TextStyle(color: Colors.red[700], fontWeight: FontWeight.bold))
else
Text("Next attack $timeString"),
if (_lootRangersTime > 0 || (_lootRangersTime == 0 && _lootRangersAttackOngoing))
Text("Order: ${_lootRangersNameOrder.join(", ")}"),
if (_lootRangersTime > 0 || (_lootRangersTime == 0 && _lootRangersAttackOngoing))
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
child: Icon(
MdiIcons.knifeMilitary,
size: 20,
color: minutesRemaining > 0 && minutesRemaining < 2 ? Colors.red : _themeProvider!.mainText,
),
onTap: () async {
// This is a Loot Rangers alert for one or more NPCs
final notes = <String>[];
final colors = <String>[];
for (var i = 0; i < _lootRangersNameOrder.length; i++) {
colors.add("green");
if (i == 0) {
notes.add("Attacks due to commence $timeString!");
} else {
notes.add("");
}
}
// Open chaining browser for Loot Rangers
context.read<WebViewProvider>().openBrowserPreference(
context: context,
url: "https://www.torn.com/loader.php?sid=attack&user2ID=${_lootRangersIdOrder[0]}",
browserTapType: BrowserTapType.chain,
isChainingBrowser: true,
chainingPayload: ChainingPayload()
..attackIdList = _lootRangersIdOrder
..attackNameList = _lootRangersNameOrder
..attackNotesList = notes
..attackNotesColorList = colors
..showNotes = true
..showBlankNotes = false
..showOnlineFactionWarning = false,
);
},
),
),
const SizedBox(width: 15),
notificationIcon,
],
),
],
),
);
}
Future _getLoot() async {
try {
final tsNow = (DateTime.now().millisecondsSinceEpoch / 1000).round();
if (_firstLoad) {
_firstLoad = false;
// Load notifications preferences
await _loadPreferences();
// See if there is any pending notification (to paint the icon in green)
await _retrievePendingNotifications();
// Get real time database and Torn (which fills level info)
final dbSuccess = await _fetchDatabase();
final tornSuccess = await _updateWithTornApi(tsNow);
if (dbSuccess && tornSuccess) {
_apiSuccess = true;
} else {
_apiSuccess = false;
}
_mainLootInfo.forEach((key, value) {
_images.add(
NpcImagesModel()
..id = key
..image = NpcImage(
npcId: key,
level: value.levels!.current,
),
);
});
} else {
// We update Torn every 30 seconds, in case there are some changes
_tornTicks++;
if (_tornTicks > 40) {
await _cancelPassedNotifications();
await _updateWithTornApi(tsNow);
_tornTicks = 0;
}
}
// We need to ensure that we keep all times updated
if (mounted) {
setState(() {
for (final npc in _mainLootInfo.values) {
// Update main timing values comparing stored TS with current time
final timingsList = <Timing>[];
npc.timings!.forEach((key, value) {
value.due = value.ts! - tsNow;
timingsList.add(
Timing(
due: value.due,
ts: value.ts,