-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhabitica_user_data_display.html
6867 lines (6469 loc) · 320 KB
/
habitica_user_data_display.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Habitica User Data Display Tool</title>
<base target="_blank">
<!--
This code is licensed under the same terms as Habitica:
https://raw.githubusercontent.com/HabitRPG/habitica/develop/LICENSE
https://github.com/habitrpg/tools-for-habitica/blob/master/habitica_user_data_display.html
AND required JavaScript libraries:
https://github.com/habitrpg/tools-for-habitica/blob/master/js-for-habitica_user_data_display.tar.gz
https://tools.habitica.com/habitica_user_data_display.html
Contributors:
Kalista Payne, sabe@habitica.com https://github.com/SabreCat
Natalie Luhrs, natalie@habitica.com https:/github.com/CuriousMagpie
Phillip Thelen, phillip@habitica.com https://github.com/phillipthelen
Alys (Alice Harris), lady_alys@oldgods.net https://github.com/Alys
thepeopleseason (James Hsiao) https://github.com/thepeopleseason
goldfndr (Richard Finegold) https://github.com/goldfndr
Blade Barringer https://github.com/crookedneighbor
donoftime https://github.com/donoftime
me_and (Adam Dinwoodie) https://github.com/me-and
cTheDragons https://github.com/cTheDragons
Pitii (Piti the Grey) https://github.com/PitiTheGrey
Tenali (BlakeTNC) https://github.com/BlakeTNC
TO ADD A NEW SECTION TO THIS PAGE:
Search through this code to find all the comments that start
with "TO ADD NEW SECTION" and follow the (brief) instructions
you'll find there.
XXX TODO: Most Recent Streak https://github.com/habitrpg/tools-for-habitica/issues/34
-->
<!--
/////
/////
///// IMPORTANT NOTE TO PROGRAMMERS EDITING THIS PAGE:
/////
///// Do not add ANY features to this page which can modify a user's
///// account. This page is a read-only view of their current data.
/////
/////
-->
<meta name="description" content="Habitica User Data Display Tool" />
<meta name="author" content="HabitRPG Inc." />
<link href="js/DataTables/media/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="js/DataTables/extras/ColumnFilterWidgets/media/css/ColumnFilterWidgets.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.6.2/remarkable.min.js"></script>
<script src="js/DataTables/media/js/jquery.dataTables.js"></script>
<script src="js/DataTables/extras/ColumnFilterWidgets/media/js/ColumnFilterWidgets.js"></script>
<script src="js/emoji-images/emoji-images.js"></script>
<!-- TST - FOR TESTING
For more information on using jquery-mockjax for simulating ajax requests, see https://github.com/jakerella/jquery-mockjax
--><!-- The testdata files have not been updated for API v3. If you'd like to update and use them, you're welcome to submit a PR for them!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.min.js" type="text/javascript"></script>
<script src="testdata/content.js" type="text/javascript"></script>
<script src="testdata/habits-many.js" type="text/javascript"></script>
<script src="testdata/habits-very-many.js" type="text/javascript"></script>
<script src="testdata/tavern.js" type="text/javascript"></script>
<script src="testdata/user.js" type="text/javascript"></script>
-->
<script type="text/javascript">
$(function() { // wraps around all our code to not pollute global namespace
//////////////////////////////////////////////////////////////////////
//// Global Variables /////////////////
//////////////////////////////////////////////////////////////////////
var content; // holds site-wide content (gear names and stats, quests, etc)
var tavern; // holds tavern data
var party; // holds party data
var user; // holds user's data
var tasksFromDb; // holds user's tasks except for ...
var completedTodosFromDb; // completed To Do's
//////////////////////////////////////////////////////////////////////
//// Global Connection Variables //////////////////////////////
//////////////////////////////////////////////////////////////////////
var serverName = 'Habitica'; // used in "loading" message
var serverUrl = 'https://habitica.com/api/v3';
var serverPathContent = '/content?language=en';
var serverPathTavern = '/groups/habitrpg';
var serverPathParty = '/groups/party';
var serverPathUser = '/user';
var serverPathTasks = '/tasks/user';
var serverPathCompletedTodos = '/tasks/user?type=_allCompletedTodos';
var clientId = 'd904bd62-da08-416b-a816-ba797c9ee265-DataDisplayTool';
var userId = '';
var apiToken = '';
var debug = false;
var markdown = new Remarkable({
'html': false,
'linkify': true,
'linkTarget': '_blank',
});
/* TST - FOR TESTING:
// Use this section if you do not have a local webserver and want to use the provided test data.
// You can compose test data by doing things like:
// var userJson = JSON.parse(userJsonString);
// var habitsVeryManyJson = JSON.parse(habitsVeryManyJsonString);
// userJson.habits = habitsVeryManyJson;
// userJsonString = JSON.stringify(userJson);
$.mockjax({
url: serverUrl + serverPathContent,
dataType: 'json',
responseText: contentJsonString,
});
$.mockjax({
url: serverUrl + serverPathTavern,
dataType: 'json',
responseText: tavernJsonString,
});
$.mockjax({
url: serverUrl + serverPathParty,
dataType: 'json',
responseText: partyJsonString,
});
$.mockjax({
url: serverUrl + serverPathUser,
dataType: 'json',
responseText: userJsonString,
});
$.mockjax({
url: serverUrl + serverPathTasks,
dataType: 'json',
responseText: tasksJsonString,
});
$.mockjax({
url: serverUrl + serverPathCompletedTodos,
dataType: 'json',
responseText: completedTodosJsonString,
});
*/
/* TST - FOR TESTING:
// Use this section if you have a local webserver set up to handle the requests.
serverName = 'localhost';
serverUrl = 'http://localhost';
serverPathTavern = '/cgi-bin/hrpg_tavern.pl';
serverPathParty = '/cgi-bin/hrpg_party.pl';
serverPathContent = '/cgi-bin/hrpg_content.pl';
serverPathUser = '/cgi-bin/hrpg_user.pl';
serverPathTasks = '/cgi-bin/XXX.pl';
serverPathTodosCompleted = '/cgi-bin/XXX.pl';
apiToken = 'null';
userId = 'test';
userId = 'work';
userId = 'home';
*/
/* TST - FOR TESTING:
$('body').css({'background-color':'#C4B4A4'});
$('#userApiDetailsForm #userId').val(userId);
$('#userApiDetailsForm #apiToken').val(apiToken);
fetchData();
*/
if (debug) console.log('debug 1');
var sectionOpen = ''; // holds the ID attribute of a section of the page;
// persists through re-fetch of data so we can
// reopen that section when the new data arrives
var hideDropsInDashboard = true; // changes to false as soon as the user
// looks at the drops section, then remains
// false through all future re-fetches
var tellMe = '<a href="mailto:admin@habitica.com">tell us</a>';
var weekdayArray = [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ]; // TODO: replace this with momentjs code
//////////////////////////////////////////////////////////////////////
//// Allow Show/Hide Toggling to work ///////////////////////////
//////////////////////////////////////////////////////////////////////
enableShowHideToggling(); // needed here to enable Version Changes link
var openRelatedSections = function(){} // redefined later when user data exists
function enableShowHideToggling() {
// $('.showHideToggle').click(function(event)
$('body').on('click', '.showHideToggle', function(event){
var target = $(this).data("target");
var wantToShow = (! $('#' + target).is(':visible')
|| $(this).data("forceopen"));
// wantToShow is false if the target is already open
// (i.e., the user wants to close it)
// unless the toggle's attributes force it to always be
// opened (e.g., a link from the dashboard)
var linktext = $(this).data("linktext") || false;
if ($(this).data("closemainsections")) {
$('#MAIN > *').hide();
}
if (wantToShow) {
sectionOpen = target;
$('#' + target).show();
if (linktext) {
$(this).text('hide ' + linktext);
}
openRelatedSections();
}
else {
$('#' + target).hide();
if (linktext) {
$(this).text('show ' + linktext);
}
if ($(this).data("scrolltotop")) {
window.scrollTo(0, 0);
}
}
var toggleTarget = $(this).data("resettoggletext") || false;
if (toggleTarget) {
$('#' + toggleTarget).text('show '
+ $('#' + toggleTarget).data("linktext"));
}
});
$('body').on('click', '.mainSectionClose', function(event){
$('#MAIN > *').hide();
window.scrollTo(0, 0);
});
}
//////////////////////////////////////////////////////////////////////
//// Get UUID etc from URL ////////////////////////////////////
//////////////////////////////////////////////////////////////////////
var url_vars = getUrlVars();
if (url_vars.uuid) {
$("#userId").val(url_vars.uuid);
}
if (url_vars.sectionOpen) {
sectionOpen = url_vars.sectionOpen;
// e.g., to start with the 'Drops Received Today' section open:
// https://tools.habitica.com/habitica_user_data_display.html?sectionOpen=dropsTodaySection&uuid=
if (sectionOpen === 'dropsTodaySection') hideDropsInDashboard = false;
}
function getUrlVars() {
// Function found at http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url#answer-4656873
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//////////////////////////////////////////////////////////////////////
//// Login events /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
$('#userApiDetailsForm').submit(function(event){
/* The user manually submitted the API connection form. */
userId = $('#userId').val();
apiToken = $('#apiToken').val();
fetchData();
});
//////////////////////////////////////////////////////////////////////
//// Login and Data Fetch Functions //////////////////////////////
//////////////////////////////////////////////////////////////////////
function fetchData() {
if (debug) console.log('debug 2');
$('#loading #serverName').text(serverName);
$('#loading .good').show();
$('#loading .bad' ).hide();
// test that the User ID and API Token are UUIDs
var uuidPattern = /^\s*[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}\s*$/i;
if (! uuidPattern.test(userId)) {
fetchFailure({ responseJSON: { message: "The User ID you have entered is not a valid User ID." }}, 'checkCredentials');
}
else if (! uuidPattern.test(apiToken)) {
fetchFailure({ responseJSON: { message: "The API Token you have entered is not a valid API Token." }}, 'checkCredentials');
}
// else if (true) { fetchFailure({ responseJSON: { error: 'TooManyRequests'}}); } // FOR TESTING
else { // attempt to fetch data
var ajaxRunningCount = 6; // drops to 0 when all calls have succeeded
// fetch the user's own content (gear owned, etc):
$.ajax({
url: serverUrl + serverPathUser,
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchUserSuccess,
error: fetchFailure
});
// fetch the user's tasks (except completed To Do's):
$.ajax({
url: serverUrl + serverPathTasks,
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchTasksSuccess,
error: fetchFailure
});
// fetch the user's completed To Do's:
$.ajax({
url: serverUrl + serverPathCompletedTodos,
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchCompletedTodosSuccess,
error: fetchFailure
});
// fetch the site-wide content (gear names and stats, etc):
$.ajax({
url: serverUrl + serverPathContent,
type: 'GET',
dataType: 'json',
cache: true,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
},
success: fetchContentSuccess,
error: fetchFailure
});
// fetch tavern-specific content
$.ajax({
url: serverUrl + serverPathTavern,
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchTavernSuccess,
error: fetchFailure,
});
// fetch party-specific content
$.ajax({
url: serverUrl + serverPathParty,
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchPartySuccess,
error: function() { // assume no party
party = {}; // no party
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
},
});
}
function fetchFailure(jqXHR, textStatus, errorThrown) {
if (debug) console.log('debug fetchFailure start');
$('#loading .good').hide();
var msg = '';
var summary = '';
var details = '';
if (jqXHR.responseJSON) {
if (jqXHR.responseJSON.error && jqXHR.responseJSON.error === 'TooManyRequests') {
msg = "Habitica has temporarily rate-limited your account,"
+ " which prevents you from using any third-party tool for a short time."
+ "<br />Please wait <em>one full minute</em> and then click the 'Fetch My Data' button below."
details = "This rate limiting has happened because one or more third-party tools that you"
+ " have used have tried to fetch your account too many times in the past couple of minutes."
+ "<br />This is not a serious error and has no long-term consequences."
+ "<br />Everything should be back to normal in a minute or two."
+ "<br />"
+ "<br />If you keep seeing this error, even after waiting one full minute before trying again,"
+ " then you are probably using another third-party tool that has been running"
+ " all this time (e.g., a chat extension, a Google Apps script, etc)."
+ "<br />Disable all other third-party tools that you are using, then wait one full minute, then try again."
+ "<br />If this error persists after that, contact me using the details in"
+ " 'Help and Contact Details' at the bottom of this page.";
}
else if (jqXHR.responseJSON.error && jqXHR.responseJSON.error === 'NotAuthorized') {
textStatus = 'checkCredentials';
msg = "The User ID and/or API Token that you entered are not correct.";
details = "If you keep seeing this error and you are sure you are using the correct details, "
+ " you may be affected by"
+ " <a href=\"https://github.com/HabitRPG/habitica/issues/12383\">Habitica's CORS bug</a>."
+ "<br />Please reload the page with your browser's refresh button and try again."
+ "<br />You may need to reload two or three times."
+ "<br />If this error persists after that, contact me using the details in"
+ " 'Help and Contact Details' at the bottom of this page.";
}
else if (jqXHR.responseJSON.message) {
msg = jqXHR.responseJSON.message;
}
}
if (textStatus === 'checkCredentials') {
msg += "<br />Please see the information below about where to find your Habitica API credentials.";
summary = 'ERROR:';
}
if (summary) $('#loading #badSummary').text(summary);
if (msg) {
var fullMsg = '<p>' + msg + '</p>';
if (details) {
fullMsg += '<p class="details">' + details + '</p>';
}
$('#loading #badDetails').html(fullMsg);
}
$('#loading .bad' ).show();
$('#documentationAndForm').show(); // in case user has done a re-fetch
$('#documentationAndFormClose').hide();
if (debug) console.log('debug fetchFailure end');
}
function fetchContentSuccess(data) {
if (debug) console.log('debug parseData Content success start');
content = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchTavernSuccess(data) {
if (debug) console.log('debug parseData Tavern success start');
tavern = data.data; // XXX_LATER test for world boss
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchPartySuccess(data) {
if (debug) console.log('debug parseData Party success start');
party = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchUserSuccess(data) {
if (debug) console.log('debug parseData User success start');
user = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchTasksSuccess(data) {
if (debug) console.log('debug parseData Tasks success start');
tasksFromDb = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchCompletedTodosSuccess(data) {
if (debug) console.log('debug parseData CompletedTodos success start');
completedTodosFromDb = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
}
function parseData() {
if (debug) console.log('debug parseData start');
// variables for storing the content:
var MAIN = {}; // each element defines the HTML for one section on the page
var TOC = {}; // each element defines one Table of Contents entry
var DASHBOARD = {}; // each element defines the HTML for one dashboard tile
convertTasksToApiV2Format();
// save the fetch time early:
var fetchtime = moment().format('YYYY-MM-DD HH:mm');
// extract some commonly-used data:
var sleeping = user.preferences.sleep; // true if resting in the inn
var userKlass = user.stats.class;
var health = getCurrentHealth(); // also sets dashboard tile
var quest = {};
var questProgressUp = 0;
var questProgressCollect = 0;
var userIsOnBossQuest = false;
var userIsOnCollectionQuest = false;
var questPending = {}; //messy but don't want to conflict
var questPendingBoss = false; //messy but don't want to conflict
var questPendingCollection = false; //messy but don't want to conflict
if (party && user.party && user.party.quest) {
if (party.quest && party.quest.active && party.quest.key && party.quest.members[userId]) {
quest = $.extend({}, user.party.quest);
quest.content = $.extend({}, content.quests[ party.quest.key ] );
if (quest.content.collect) userIsOnCollectionQuest = true;
if (!quest.content.collect) userIsOnBossQuest = true;
}
else if (party.quest && party.quest.key && party.quest.members[userId]) {
//This is messy but I didn't want to conflict current code.
questPending = $.extend({}, user.party.quest);
questPending.content = $.extend({}, content.quests[ party.quest.key ] );
if (questPending.content.collect) questPendingCollection = true;
if (!questPending.content.collect) questPendingBoss = true;
}
else {
questPendingCollection = true;
questPendingBoss = true;
}
if (user.party.quest.progress && user.party.quest.progress.up) {
// might not be in a quest but want to know damage done to world boss
questProgressUp = user.party.quest.progress.up;
}
if (user.party.quest.progress && user.party.quest.progress.collectedItems) {
questProgressCollect = user.party.quest.progress.collectedItems;
}
}
var customDayStart = user.preferences.dayStart || 0; // CDS
var timezoneOffset = user.preferences.timezoneOffset || 0;
// Find the correct date for "today". If the user has a CDS set, then
// we need to subtract the CDS hour from the current date and time to
// see if today is actually "yesterday". E.g., if the CDS is 5am, and
// the user is using this tool at 4am on Monday, then the actual
// "Habitica day" is Sunday (not Monday) because the CDS time has not
// yet been reached; subtracting 5 hours from the current date and time
// gives us yesterday's date. We then ignore the time portion of the
// date because from now on we're comparing only days, not hours.
var todayUser = moment().subtract(customDayStart, 'hours');
todayUser = todayUser.startOf('day');
var tavernBoss = tavern.quest && tavern.quest.active; // true/false
var bossesLabel = '';
var bossesWord = 'boss';
if (userIsOnBossQuest) {
bossesLabel = 'your quest boss';
if (tavernBoss) {
bossesLabel += ' and ';
bossesWord += 'es';
}
}
if (tavernBoss) {
bossesLabel += 'the World boss';
}
// put the user's equipped battle gear into an object, with all
// details about each piece:
var equippedKeys = {};
for (var i in user.items.gear.equipped) {
var key = user.items.gear.equipped[i];
equippedKeys[key] = content.gear.flat[key];
}
var computedStats = computeStats(true); // computed CON, INT, etc
var computedStatsNoBuffs = computeStats(false); // ... without buffs
// XXX_SOON my computedStats code is just getting worse and worse
// When calculating drop chance for a task, some of the user's stats
// are used. We calculate those parts of the drop chance here since
// they'll be identical for all tasks:
var userStatsDropChance =
(1 + ( computedStats.per / 100)) *
(1 + ( (user.contributor.level || 0) / 40 )) *
(1 + ( (user.achievements.rebirths || 0) / 20 )) *
(1 + ( (user.achievements.streak || 0) / 200));
// console.log("computedStats.per: " + computedStats.per); // TST
// console.log("userStatsDropChance: " + userStatsDropChance); // TST
userDataInHeader();
// create the content, section by section:
//
// TO ADD NEW SECTION: add a function here, OR add it within one of the
// functions that is already here if appropriate for correct scoping
// (e.g., features related to tasks should have their function put
// inside collateAndDisplayTaskData):
collateAndDisplayTaskData();
dropCountAndCap();
questProgress();
questsCompleted();
analyseEquipment(); // missing gear, current gear, recommended gear
subscriptionData();
//////////////////////////////////////////////////////////////////////
//// Display the HTML that the functions have created ////////////
//////////////////////////////////////////////////////////////////////
$('#loading .good').hide();
$('#documentationAndFormClose').show();
$('#documentationAndForm').hide();
formatAndDisplayDASHBOARD();
formatAndDisplayTOC();
formatAndDisplayMAIN();
// everything below here is functions used within this function
function formatAndDisplayDASHBOARD() {
// TO ADD NEW SECTION: To create a dashboard tile (which is optional),
// add the unique identifier for the new section to this array (the array
// elements are in the order that the dashboard tiles appear on the page):
var keys = ['currentHealth', 'dailiesIncomplete', 'damageToUser',
'damageToParty', 'questProgress', 'questProgressSecond',
'todosDated', 'dropsToday', 'sleeping'];
var html = '<ul>';
for (var i=0,ic=keys.length; i<ic; i++) {
var data = DASHBOARD[keys[i]];
if (! data) {
continue;
}
var classes = (data.hidden) ? 'hide' : '';
html += '<li ';
if (data.id) {
// id is needed only if other code will change tile background
html += 'id="' + data.id + '" ';
}
html += 'title="' + data.hoverText + '" ';
if (data.target) {
html += 'data-target="' + data.target +
'" data-closemainsections="true" data-forceopen="true" ' +
'class="showHideToggle ' + classes + '"';
}
html += '><div class="' +
data.status + '"><div class="value">' +
data.value + '</div><div class="label">' +
data.label + '</div></div></li>';
}
html += '</ul><div class="clear"></div>';
$('#DASHBOARD').html(html);
}
function formatAndDisplayTOC() {
// TO ADD NEW SECTION: To create a Table of Content entry (required),
// add the unique identifier for the new section to this array (the array
// elements are in the order that the TOC links appear on the page):
var keys = [
'HEADING Tasks',
'taskOverview', 'taskStatistics', 'untaggedTasks',
// 'HEADING Habits',
'habitTrends', 'habitHistoryList', 'habitHistoryTable',
'HEADING',
// 'HEADING Dailies',
'dailiesHistory', 'dailiesIncomplete',
// 'HEADING To Do's',
'todosDated', 'todosCompleted',
'HEADING Drops, Quests, Damage', 'dropsToday',
'questProgress', 'questsCompleted', 'damageDailies', 'statsAndStreaks',
'HEADING Other',
'missingEquipment',
'currentGear', 'equipmentRecommendations', 'skillsAndBuffs',
'subscriptionData'];
var html = '';
for (var i=0,ic=keys.length; i<ic; i++) {
if (keys[i].match(/^HEADING/)) { // new section in Table of Contents
var title = keys[i].replace(/^HEADING/, '');
if (html) {
html += '</ul></li>'; // close the previous section
}
html += '<li>' + title + (title ? ':' : ' ') + '<ul>';
}
else {
var data = TOC[keys[i]];
if (! data) {
continue;
}
html += '<li class="showHideToggle" data-target="' +
data['target'] + '" data-closemainsections="true">' +
data['title'] + '</li>';
}
}
html += '</ul></li></ul>'; // close the final section, and the parent ul
$('#TOC').html('<ul id="tableOfContents">' + html +
'</ul><div class="clear"></div><hr class="padded" />');
}
function formatAndDisplayMAIN() {
// TO ADD NEW SECTION: To make your new section appear on the page,
// add the unique identifier for the new section to this array (the array
// elements are in the order that the sections would appear on the page
// if they were all visible at once):
var keys = ['taskOverview', 'taskStatistics', 'untaggedTasks',
'habitTrends', 'habitHistoryList', 'habitHistoryTable', 'dailiesHistory', 'todosDated',
'todosCompleted', 'dropsToday', 'questProgress', 'questsCompleted',
'damageDailies','dailiesIncomplete',//keep in that order
'statsAndStreaks',
'missingEquipment', 'currentGear', 'equipmentRecommendations',
'skillsAndBuffs', 'subscriptionData'];
var html = '';
var functions = []; // functions to run after HTML code has been loaded
for (var i=0,ic=keys.length; i<ic; i++) {
var data = MAIN[keys[i]];
if (! data) {
continue;
}
html += '<div id="' +
data.id + '"><h2>' +
data.title + '</h2>' +
data.html +
((data.longContent) ? '<div class="mainSectionClose closer">' +
'close / back to top</div>' : '') +
'</div>';
if (data['function']) {
functions.push(data['function']);
}
}
$('#MAIN').html(html);
// execute any functions that need to be run AFTER the bulk of the
// HTML has been created:
$.each(functions, function(index,fn){
fn();
});
if (sectionOpen && sectionOpen != 'documentationAndForm'
&& sectionOpen != 'versionChanges'
) {
// reopen the section that the user had open before re-fetching
// data (except for sections that don't display the user's own data):
$('#' + sectionOpen).show();
openRelatedSections();
}
}
function myDateConverter(date, style) { // XXX_SOON replace with moment
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
if (!date || isNaN(date.getTime())) {
// Either the object that was passed in is not a Date object,
// OR the date string that was passed in could not be converted
// to a Date object, presumably because it's in a non-standard
// format. We handle this by using today's date. It's a nasty
// hack, but it's unlikely to occur, and no one's paying for
// anything better.
date = new Date();
}
if (style === 'XXX pretty') {
// Format date as (weekday date month) and hh:mm:ss;
// toDateString ordering might be locale-specific
// var dateStr = date.toDateString().split(' ').slice(0,3).join(' ') +
// ' ' + date.toTimeString().split(' ')[0];
var dateStr = date.toLocaleString(undefined,
{ weekday: 'long', day: 'numeric', month: 'long',
hour: '2-digit', minute: '2-digit' });
}
else {
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var H = date.getHours();
var M = date.getMinutes();
var S = date.getSeconds();
var dateStr = y +
'-' + (m<=9 ? '0'+m : m) +
'-' + (d<=9 ? '0'+d : d);
if (style === 'short') {
dateStr = dateStr.replace(/^20/, ""); // remove century
}
if (style === 'long') {
dateStr += ' ' + (H<=9 ? '0'+H : H) +
':' + (M<=9 ? '0'+M : M) +
':' + (S<=9 ? '0'+S : S);
}
}
return dateStr;
}
function formatIsoDateString(date) {
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
if (!date || isNaN(date.getTime())) {
// Either the object that was passed in is not a Date object,
// OR the date string that was passed in could not be converted
// to a Date object, presumably because it's in a non-standard
// format. We handle this by using today's date. It's a nasty
// hack, but it's unlikely to occur, and no one's paying for
// anything better.
date = new Date();
}
var y = date.getUTCFullYear();
var m = date.getUTCMonth() + 1;
var d = date.getUTCDate();
var H = date.getUTCHours();
var M = date.getUTCMinutes();
var S = date.getUTCSeconds();
var dateStr = y +
'-' + (m<=9 ? '0'+m : m) +
'-' + (d<=9 ? '0'+d : d);
return dateStr;
}
function wiki(wikilink, pipelink) {
// http://stackoverflow.com/a/1145525
var wiki_link = wikilink.split(' ').join('_');
return '<a href="http://habitica.fandom.com/wiki/' + wiki_link + '">' +
((typeof pipelink === "undefined") ? wikilink : pipelink) +
'</a>';
}
openRelatedSections = function() {
if ($('#damageDailiesSection').is(':visible')) {
$('#dailiesIncompleteSection').show();
}
if ($('#questsCompletedSection').is(':visible')) {
$('#questsCompletedSection').show();
}
if ($('#dropsTodaySection').is(':visible')) {
hideDropsInDashboard = false;
$('#dropsTodayDashboard').show();
// NOTE: We unhide the number of drops in the dashboard
// only after the user has opened the main drops section,
// because some users might prefer to not know (less
// motivation if they know they've got all of today's drops).
// BUT we do not reset the dashboard drops show/hide status
// on re-fetch, because if the user wanted to see drops once,
// they'll presumably want it again.
if (userIsOnCollectionQuest) {
// The user is on a collection quest and has viewed the
// Drops Received Today section, so also show them the
// Quest Progress section (collection quests have drops):
$('#questProgressSection').show();
}
}
}
function pluralise(word, number) {
var lcWord = word.toLowerCase();
var needUpperCase = (lcWord == word) ? false : true;
if (number != 1) {
var pluralWords = {
'has': 'have',
'it': 'them',
'this': 'these',
'is': 'are',
'daily': 'dailies',
'Daily': 'Dailies',
};
if (pluralWords[lcWord]) { word = pluralWords[lcWord]; }
else { word += 's'; }
}
if (needUpperCase) { // must improve this if ever need ALL upper case
word = upperCaseFirst(word);
}
return word;
}
function upperCaseFirst(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
function renderFormattedText(text, options) {
function renderMarkdown(text) {
text = markdown.render(text);
if (options && options.removeParaTags) {
text = String(text).replace(/^<p>|<\/p>\n$/g, '');
}
else if (options && options.setParaClass) {
text = String(text).replace(/<p>/g,
'<p class="' + options.setParaClass + '">');
}
return text;
}
function renderEmoji(text) {
return emoji(text, 'js/emoji-images/pngs', 25);
}
return renderEmoji(
renderMarkdown(
String(text).replace(/\ /g, ' ')
)
);
}
function userDataInHeader() {
var displayName =
renderFormattedText(user.profile.name, {'removeParaTags':true});
$('#headerExtras').html('<div id="userNameDisplay">' +
displayName +
'</div>' +
'<div id="explanationAndClearLinks">' +
'<input id="refetch" type="submit" value="' +
'Re-Fetch Data (last fetched ' + fetchtime + ')" />' +
'<span id="documentationAndFormToggle" class="showHideToggle" data-target="documentationAndForm" data-linktext="documentation" data-closemainsections="true">show documentation</span>' +
'</div>'
);
$('#refetch').click(function(event){
/* The user clicked on the Re-Fetch My Data button. */
fetchData();
});
}
function getCurrentHealth() {
var health = Math.round(user.stats.hp * 10) / 10;
// If the user's health is so low that it rounds to 0, then show
// them a more-precise (hopefully non-zero) number, because 0
// makes them wonder why they aren't dead:
if (health == 0) {
health = Math.round(user.stats.hp * 1000) / 1000;
if (health == 0) {
health = Math.round(user.stats.hp * 100000) / 100000;
}
}
DASHBOARD.currentHealth = {'id': 'currentHealthDashboard',
'label': 'Current Health', 'hoverText': 'your health',
'value': health, 'status': 'neutral'};
return health;
}
function collateAndDisplayTaskData() {
// Set up data structures for storing task information:
var taskOrder = 0; // default order of tasks in Habitica
var allTasks = []; // except completed To Do's
var untaggedTasks = {'habits':[], 'dailies':[], 'todos':[], 'rewards':[]};
var template = {'total':0, 'con':0, 'int':0, 'per':0, 'str':0};
var countTasks = {
'habits': $.extend(true, {}, template),
'dailiesDue': $.extend(true, {}, template),
'dailies': $.extend(true, {}, template),
'todosIncomplete': $.extend(true, {}, template),
'todosComplete': $.extend(true, {}, template),
'todosAll': $.extend(true, {}, template),
'statsTotals': $.extend(true, {}, template),
'rewards': {'total': 0}
};
var exampleTaskType = ''; // Used to develop...
var exampleAttribute = ''; // ... a useful customised example...
var exampleFound = false; // ... for the Task Statistics section.
// Define some static stuff:
var entityMap = { "&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
var colours = { 1: {'order':1, 'name':'Blue',
'label': '1) Blue',
'nameNoSpace': 'Blue',
'id': 'colourBlue'
},
2: {'order':2, 'name':'Teal',
'label': '2) Teal',
'nameNoSpace': 'Teal',