-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.js
1469 lines (1246 loc) · 55.1 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// _functionName = nested function
console.log("Last Updated 11-08-2022")
google.charts.load('current', {packages: ['corechart']});
google.charts.load('current', {'packages':['corechart', 'controls']});
google.charts.setOnLoadCallback(EnableSubmitButton);
var submitButton = document.getElementById("submit-file"); // submit button
var selectedFiles = document.getElementById("open-file"); // choose file button
var startDemo = document.getElementById("start-demo-file"); // submit button
var showEmojiImageTable = document.getElementById("emoji-table-replace");
var statusDisplay = {
main: document.getElementById("status-display"),
chartService: document.getElementById("status-googlechart-load"),
analysing: document.getElementById("status-analysing"),
complete: document.getElementById("status-complete")
};
var Conversation = {};
var Participants = [];
var TimeArrays = {
// For day and month, override subData so all possible values are present
'Day': ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
'Month': ["January","February","March","April","May","June","July", "August","September","October","November","December"]
};
var timeDisplay = "Hours"
var fullDateDisplay = "Months"
var wordsDisplay = 15;
var wordsLengthMin = 1;
var wordsLengthMax = 20;
var emojisDisplay = 20;
var messageLengthsDisplay = 0;
var latin_map = {
"à": "a", "è": "e", "ì": "i", "ò": "o", "ù": "u", "À": "A", "È": "E",
"Ì": "I", "Ò": "O", "Ù": "U", "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u",
"ý": "y", "Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ý": "Y", "â": "a",
"ê": "e", "î": "i", "ô": "o", "û": "u", "ð": "o", "Â": "A", "Ê": "E", "Î": "I",
"Ô": "O", "Û": "U", "Ð": "D", "ã": "a", "ñ": "n", "õ": "o", "Ã": "A", "Ñ": "N",
"Õ": "O", "ä": "a", "ë": "e", "ï": "i", "ö": "o", "ü": "u", "ÿ": "y", "Ä": "A",
"Ë": "E", "Ï": "I", "Ö": "O", "Ü": "U", "Ÿ": "Y", "å": "a", "Å": "A", "æ": "ae",
"œ": "oe", "Æ": "AE", "Œ": "OE", "ß": "B", "ç": "c", "Ç": "C", "ø": "o", "Ø": "O",
"¿": "?", "¡": "!"
};
var LatiniseString = Object.keys(latin_map).join('');
var mainDataCategories = ["TimeData", "MessageLengths", "WordsSent", "EmojisSent"];
var timeSubData = ["Day", "Month", "Year", "Time", "Fulldate"];
// ~~~~~ Events
startDemo.addEventListener("click", function () {
fetch("./files/demofile.json")
.then(function(response) {
return response.text();
})
.then(function (fileText) {
var fileJson = JSON.parse(fileText, (key, value) => {
if (key === "participants") {
return value.map(p => p.name)
}
return value;
});
AnalyseConversation(fileJson);
})
.catch(function() {
// This is where you run code if the server returns any errors
console.log("Oops! Didn't get demo file.")
});
});
var conversationParts = []
function extendConversationPart(part1, part2) {
if (part1.title === "") {
part1.title = part2.title
}
if (part1.thread_type === "") {
part1.thread_type = part2.thread_type
}
part1.messages.push(...part2.messages)
for (const name of part2.participants) {
if (!part1.participants.includes(name)) {
part1.participants.push(name)
}
}
return part1;
}
function readFile(index) {
if (index > selectedFiles.files.length - 1) {
let conv = conversationParts.reduce((acc, part) => extendConversationPart(acc, part))
AnalyseConversation(conv)
return;
}
let fr = new FileReader();
fr.onload = function () {
var fileJson = JSON.parse(this.result, (key, value) => {
if (key === "participants") {
return value.map(p => p.name)
}
return value;
});
conversationParts.push(fileJson);
readFile(index + 1);
}
fr.readAsText(selectedFiles.files[index])
}
// Listener for "start"
submitButton.addEventListener("click", function () {
readFile(0)
// Change status displays
statusDisplay.analysing.removeAttribute("hidden");
statusDisplay.complete.setAttribute("hidden", true);
});
// Listener for selecting file - display file name, turn green
selectedFiles.addEventListener("change", function () {
ChangeFileSelectLabel();
});
// Listener for clicking the link to show the backup emoji table.
showEmojiImageTable.addEventListener("click", function() {
document.getElementById("emoji-image-table").removeAttribute("hidden");
});
// Div Generation
BuildChartDivs();
function BuildChartDivs() {
// Main categories
mainDataCategories.forEach(mainCategory => {
// Timedata subcategories
if (mainCategory == "TimeData") {
timeSubData.forEach(timeCategory => {
CreateSingleChartDiv(mainCategory, timeCategory);
});
// No sub categories
} else {
CreateSingleChartDiv(mainCategory, null)
}
});
InsertTableDivs();
CreateChartButtonEvents();
CreateTimeToggleEvents();
InsertWordChartOptions();
InsertMessageLengthChartOptions();
};
function CreateSingleChartDiv(mainData, subData){
var chartContainer = document.getElementById("chart-container");
// Main buttons + chart container
if (subData) {
chartContainer.innerHTML +=
`<div class="mda-spacer"></div>
<div id="container-${mainData}-${subData}" class="mda-chart">
<div class="d-flex">
<h4 class="chart-title">No Data to Chart :(</h4>
<div class="btn-group ml-auto">
<button type="button" class="active btn btn-outline-dark btn-sm btn-normal-cols">Normal Columns</button>
<button type="button" class="btn btn-outline-dark btn-sm btn-stacked-cols">Stacked Columns</button>
<button type="button" class="btn btn-outline-dark btn-sm btn-100-cols">100% Stacked Columns</button>
</div>
</div>
<div class="d-flex d-row justify-content-center">
<div id="chart-${mainData}-${subData}"></div>
</div>
</div>`;
} else {
chartContainer.innerHTML +=
`<div class="mda-spacer"></div>
<div id="container-${mainData}" class="mda-chart">
<div class="d-flex">
<h4 class="chart-title">No Data to Chart :(</h4>
<div class="btn-group ml-auto">
<button type="button" class="active btn btn-outline-dark btn-sm btn-normal-cols">Normal Columns</button>
<button type="button" class="btn btn-outline-dark btn-sm btn-stacked-cols">Stacked Columns</button>
<button type="button" class="btn btn-outline-dark btn-sm btn-100-cols">100% Stacked Columns</button>
</div>
</div>
<div class="d-flex d-row justify-content-center">
<div id="chart-${mainData}"></div>
</div>
</div>`;
}
if (subData == "Time" || subData == "Fulldate") {
chartContainer.querySelector(`#container-${mainData}-${subData} div.btn-group`).classList.remove("ml-auto");
chartContainer.querySelector(`#container-${mainData}-${subData} div.btn-group`).classList.add("ml-2");
}
// Subdata specific
var parent = subData
? document.getElementById(`container-${mainData}-${subData}`).querySelector("div")
: document.getElementById(`container-${mainData}`).querySelector("div");
// Adding buttons for toggling data views
if (subData == "Time") {
var button = document.createElement("button");
var firstChild = parent.querySelector(".btn-group")
button.id = "TimeToggleBtn";
button.classList.add("btn", "btn-outline-dark", "btn-sm", "ml-auto");
button.innerHTML = "Group by 15 minutes";
parent.insertBefore(button, firstChild);
} else if(subData == "Fulldate") {
var button = document.createElement("button");
var firstChild = parent.querySelector(".btn-group")
button.id = "FulldateToggleBtn";
button.classList.add("btn", "btn-outline-dark", "btn-sm", "ml-auto");
button.innerHTML = "Group by Days";
parent.insertBefore(button, firstChild);
}
}
// Adding in HTML sections for charts and tables, as well as buttons.
// Done in this way so that changes to all elements can be made easily.
function CreateChartButtonEvents() {
var btnNormal = document.querySelectorAll(".btn-normal-cols");
var btnStacked = document.querySelectorAll(".btn-stacked-cols");
var btn100 = document.querySelectorAll(".btn-100-cols");
btnNormal.forEach(button => {
button.addEventListener('click', function () {
// remove active look from other button, add it to this button.
for (const sibling of button.parentNode.children) {
sibling.classList.remove("active");
}
button.classList.add("active");
// Get the mainData and subData for passing into charting.
var parentButton = button.parentElement.parentElement.parentElement.id; // eg container-TimeData-Day
var [mainData, subData] = parentButton.replace("container-", '').split('-');
var optionsOverride = {
isStacked: false
};
ChartData(mainData, subData, optionsOverride);
});
});
btnStacked.forEach(button => {
button.addEventListener('click', function () {
// remove active look from other button, add it to this button.
for (const sibling of button.parentNode.children) {
sibling.classList.remove("active");
}
button.classList.add("active");
// Get the mainData and subData for passing into charting.
var parentButton = button.parentElement.parentElement.parentElement.id; // eg container-TimeData-Day
var [mainData, subData] = parentButton.replace("container-", '').split('-');
var optionsOverride = {
isStacked: true
};
ChartData(mainData, subData, optionsOverride);
});
});
btn100.forEach(button => {
button.addEventListener('click', function () {
// remove active look from other button, add it to this button.
for (const sibling of button.parentNode.children) {
sibling.classList.remove("active");
}
button.classList.add("active");
// Get the mainData and subData for passing into charting.
var parentButton = button.parentElement.parentElement.parentElement.id; // eg container-TimeData-Day
var [mainData, subData] = parentButton.replace("container-", '').split('-');
var optionsOverride = {
isStacked: 'percent'
};
ChartData(mainData, subData, optionsOverride);
});
});
}
function CreateTimeToggleEvents() {
document.getElementById("TimeToggleBtn").addEventListener("click", function () {
if (timeDisplay == "Minutes") {
timeDisplay = "Hours"
document.getElementById("TimeToggleBtn").innerHTML = "Group by 15 minutes"
} else {
timeDisplay = "Minutes"
document.getElementById("TimeToggleBtn").innerHTML = "Group by Hours"
}
ChartData("TimeData", "Time");
});
// Fulldate toggle
document.getElementById("FulldateToggleBtn").addEventListener("click", function () {
if (fullDateDisplay == "Months") {
fullDateDisplay = "Days"
document.getElementById("FulldateToggleBtn").innerHTML = "Group by Months"
} else {
fullDateDisplay = "Months"
document.getElementById("FulldateToggleBtn").innerHTML = "Group by Days"
}
ChartData("TimeData", "Fulldate");
});
}
function InsertTableDivs() {
var TableDiv = document.getElementById("container-WordsSent");
TableDiv.innerHTML +=
`<div id="WordsSent-dashboard" class="text-center">
<h5><u>Filter for Words sent</u></h5>
<div id="WordsSent-filter"></div>
<div id="WordsSent-table"></div>
</div>`;
TableDiv = document.getElementById("container-EmojisSent")
TableDiv.innerHTML +=
`<div id="EmojisSent-dashboard" class="text-center">
<h5><u>Filter for Emojis sent</u></h5>
<div id="EmojisSent-filter"></div>
<div id="EmojisSent-table"></div>
<a href="javascript:void(0);" class="my-2" data-toggle="modal" data-target="#emoji-modal">Having trouble seeing emojis?</a>
</div>
<table id="emoji-image-table" class="table-sm table-striped table-bordered text-center" style="margin: auto!important;" hidden>
<thead id="emoji-image-table-head" class="bg-primary text-light">
<th class="px-2">Rank</th>
<th class="px-2">Emoji</th>
</thead>
<tbody id="emoji-image-table-body">
</tbody>
</table>`;
}
function InsertWordChartOptions() {
var parent = document.getElementById("chart-WordsSent").parentElement.parentElement
var child = document.getElementById("chart-WordsSent").parentElement
var node = document.createElement("div")
node.innerHTML =
`<p>Word length: <input id="words-min" type="number" name="quantity" value="1" class="form-control d-inline-block w-05"></input> to <input id="words-max" type="number" name="quantity" value="20" class="form-control d-inline-block w-05"> characters.</p>`;
node.classList.add("d-flex", "flex-row-reverse", "text-right", "mt-2")
parent.insertBefore(node, child);
// Create change events
var wordsMin =document.getElementById("words-min");
var wordsMax =document.getElementById("words-max");
wordsMin.addEventListener("change", function () {
wordsLengthMin = parseInt(wordsMin.value)
ChartData("WordsSent")
});
wordsMax.addEventListener("change", function () {
wordsLengthMax = parseInt(wordsMax.value)
ChartData("WordsSent")
});
}
function InsertMessageLengthChartOptions() {
var parent = document.getElementById("chart-MessageLengths").parentElement.parentElement
var child = document.getElementById("chart-MessageLengths").parentElement
var node = document.createElement("div")
node.innerHTML =
`<p>Chart limit: <input id="lengths-max" type="number" name="quantity" value="0" class="form-control d-inline-block w-05"> words long.</p>`;
node.classList.add("d-flex", "flex-row-reverse", "text-right", "mt-2")
parent.insertBefore(node, child);
// Create change events
var lengthMax = document.getElementById("lengths-max");
lengthMax.addEventListener("change", function () {
messageLengthsDisplay = Number(lengthMax.value);
// var optionsOverride =
// { hAxis: {
// viewWindow: {
// max: messageLengthsDisplay
// }
// }};
ChartData("MessageLengths", null);
});
}
// ~~~~~
function ConversationReset() {
Conversation = {}
Participants = [];
Conversation._AddTimeData = function (timeData, senderName) {
// add to person-specfic data in the participant data
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Day"], timeData["Day"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Month"], timeData["Month"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Year"], timeData["Year"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Time"]["Minutes"], timeData["Time"]["Minutes"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Time"]["Hours"], timeData["Time"]["Hours"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Fulldate"]["Days"], timeData["Fulldate"]["Days"]);
ObjectAddNewValueOrIncrement(this[senderName]["TimeData"]["Fulldate"]["Months"], timeData["Fulldate"]["Months"]);
// add to overall Conversation information
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Day"], timeData["Day"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Month"], timeData["Month"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Year"], timeData["Year"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Time"]["Minutes"], timeData["Time"]["Minutes"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Time"]["Hours"], timeData["Time"]["Hours"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Fulldate"]["Days"], timeData["Fulldate"]["Days"]);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["TimeData"]["Fulldate"]["Months"], timeData["Fulldate"]["Months"]);
};
Conversation._AddContentTypeData = function (messageType, senderName) {
ObjectAddNewValueOrIncrement(
this[senderName]["MessageContentTypes"],
messageType);
ObjectAddNewValueOrIncrement(
this["ConversationTotals"]["MessageContentTypes"],
messageType);
};
Conversation._AddWordData = function (words, senderName) {
words.forEach(word => {
ObjectAddNewValueOrIncrement(this[senderName]["WordsSent"], word);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["WordsSent"], word)
})
};
Conversation._AddEmojiData = function (emojis, senderName) {
emojis.forEach(emoji => {
ObjectAddNewValueOrIncrement(this[senderName]["EmojisSent"], emoji);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["EmojisSent"], emoji)
})
};
Conversation._AddMessageLengthData = function (messageLength, senderName) {
ObjectAddNewValueOrIncrement(this[senderName]["MessageLengths"], messageLength);
ObjectAddNewValueOrIncrement(this["ConversationTotals"]["MessageLengths"], messageLength);
}
};
function AnalyseConversation(inputJSON) {
var t1 = performance.now();
// RESET
ConversationReset();
// INIT
Conversation["ConversationTitle"] = inputJSON.title;
InitialiseConversation(inputJSON.participants);
var t2 = performance.now();
console.log("Init done: " + (t2-t1).toFixed(2) + " milliseconds");
// Start filling Data
Conversation.ConversationTotals.MessagesSentCount = inputJSON.messages.length;
inputJSON.messages.forEach(message => {
// ~~~ MESSAGE COUNT
/* Add one to the sender message count.
It is possible for the sender to have been removed
from the Conversation, and they will not be in the
participant list. This adds them to the data structure
in that scenario. */
try {
Conversation[message.sender_name]["MessagesSentCount"] += 1;
} catch (error) {
InitaliseParticipant(message.sender_name);
Conversation[message.sender_name]["MessagesSentCount"] += 1;
}
// ~~~ TIME
var timeData = TimeAnalysis(message.timestamp_ms);
Conversation._AddTimeData(timeData, message.sender_name);
// ~~~ CONTENT TYPE
var messageType = ContentTypeAnalysis(message);
Conversation._AddContentTypeData(messageType, message.sender_name);
// ~~~ TEXT MESSAGES
if (messageType === "Text Messages") {
var messageContentArray = GetMessageContentArray(
decodeURIComponent(escape(message.content))
);
// Length
var messageLength = message.content.split(' ').length;
Conversation._AddMessageLengthData(messageLength, message.sender_name);
// Words
var words = MessageWordsAnalysis(messageContentArray);
Conversation._AddWordData(words, message.sender_name);
// Emojis
var emojis = MessageEmojiAnalysis(messageContentArray);
Conversation._AddEmojiData(emojis, message.sender_name);
}
});
var t3 = performance.now();
console.log("Analysis done: " + (t3-t2).toFixed(2) + " milliseconds");
console.log("Raw Data:", Conversation);
document.querySelector("#analysis-results").removeAttribute("hidden");
if (Object.keys(Conversation["ConversationTotals"]["TimeData"]["Fulldate"]).length !== 0) {
ChartData("TimeData", "Day");
ChartData("TimeData", "Month");
ChartData("TimeData", "Year");
ChartData("TimeData", "Time");
ChartData("TimeData", "Fulldate");
}
if (Object.keys(Conversation["ConversationTotals"]["MessageLengths"]).length !== 0) {
ChartData("MessageLengths");
}
if (Object.keys(Conversation["ConversationTotals"]["WordsSent"]).length !== 0) {
ChartData("WordsSent");
ChartPieData("MessagesSentCount");
ChartPieData("WordsSentCount");
CreateMessageTypesInfoTable();
CreateParticipantWordInfoTable();
}
if (Object.keys(Conversation["ConversationTotals"]["EmojisSent"]).length !== 0) {
ChartData("EmojisSent");
}
WriteConversationInfo()
statusDisplay.analysing.setAttribute("hidden", true);
statusDisplay.complete.removeAttribute("hidden");
var t4 = performance.now();
console.log("Charting done: " + (t4-t3).toFixed(2) + " milliseconds");
}
function InitialiseConversation(participants) {
InitaliseParticipant("ConversationTotals");
participants.forEach(participant => {
// TODO: handle multiple people with same name?
// Basically impossible, in the files there is only "name"
// with no user id or other unique identifier.
InitaliseParticipant(participant)
});
}
function InitaliseParticipant(participantName) {
Participants.push(participantName);
Conversation[participantName] = {};
Conversation[participantName]["MessagesSentCount"] = 0;
Conversation[participantName]["TimeData"] = {};
Conversation[participantName]["TimeData"]["Day"] = new Object();
Conversation[participantName]["TimeData"]["Month"] = new Object();
Conversation[participantName]["TimeData"]["Year"] = new Object();
Conversation[participantName]["TimeData"]["Time"] = new Object();
Conversation[participantName]["TimeData"]["Time"]["Minutes"] = new Object();
Conversation[participantName]["TimeData"]["Time"]["Hours"] = new Object();
Conversation[participantName]["TimeData"]["Fulldate"] = new Object();
Conversation[participantName]["TimeData"]["Fulldate"]["Days"] = new Object();
Conversation[participantName]["TimeData"]["Fulldate"]["Months"] = new Object();
Conversation[participantName]["MessageContentTypes"] = new Object();
Conversation[participantName]["MessageLengths"] = new Object();
Conversation[participantName]["WordsSent"] = new Object();
Conversation[participantName]["EmojisSent"] = new Object();
}
function TimeAnalysis(timestamp) {
// takes a timestamp input and creates a datetime object
var messageDateTime = new Date(timestamp);
// time data, a structure containing the time information about each message.
var timeData = {};
// get the day, month and year of each message
timeData["Day"] = TimeArrays["Day"][messageDateTime.getDay()]; // day of the week (Words)
timeData["Month"] = TimeArrays["Month"][messageDateTime.getMonth()]; // month (wprds)
timeData["Year"] = messageDateTime.getFullYear(); // year
// get the time of the message so it is always in HH:MM form. Also round the minutes to the users preference (to the hour, or in 10m blocks)
var hours = messageDateTime.getHours(); // hour 0-23
var minutes = messageDateTime.getMinutes(); // minutes 0-59
minutes = _RoundMinutes(minutes);
// Timedata is stored as a date so that tooltip formatting can be used in google charts.
// 'Timeofday' is a valid format but its options are more limited.
timeData["Time"] = {};
timeData["Time"]["Minutes"] = new Date(2018, 1, 1).setHours(hours, minutes, 0, 0);
timeData["Time"]["Hours"] = new Date(2018, 1, 1).setHours(hours, 0, 0, 0);
// Full Time - set hours of day to zero so that each message only has date information
var date = new Date(timestamp).setHours(1, 0, 0, 0);
timeData["Fulldate"] = {};
timeData["Fulldate"]["Days"] = date;
timeData["Fulldate"]["Months"] = new Date(date).setDate(1);
function _RoundMinutes(minutes) {
// Round minutes to 10 min blocks
if (String(minutes).length == 1) {
return "00";
}
else {
return minutes.toString()[0] + "0";
}
}
return timeData;
}
function ContentTypeAnalysis(message) {
if (message.sticker) {
return "Stickers";
}
else if (message.videos) {
return "Videos";
}
else if (message.photos) {
return "Photos";
}
else if (message.files) {
return "Files";
}
else if (message.gifs) {
return "GIFs";
}
else if (message.share || message.type == "Share") {
return "Shared Links";
}
else if (message.audio_files) {
return "Audio Files";
}
else if (message.plan) {
return "Plan (linked date/time)";
}
else if (message.content) {
return "Text Messages";
}
else {
return "Link to External Site";
}
}
function GetMessageContentArray(content) {
// facebooks emoticons shortcuts (only used for old messages)
var fixedContent = content.replace(/( :\))/g, " 🙂 ")
.replace(/( <\("\))/g, " 🐧 ")
.replace(/( :\()/g, " 😞 ")
.replace(/( :\/)/g, " 😕 ")
.replace(/( :P)/g, " 😛 ")
.replace(/ :D/g, " 😀 ")
.replace(/ :o/g, " 😮 ")
.replace(/ ;\)/g, " 😉 ")
.replace(/ B-\)/g, " 😎 ")
.replace(/ >:\(/g, " 😠 ")
.replace(/ :'\(/g, " 😢 ")
.replace(/ 3:\)/g, " 😈 ")
.replace(/ O:\)/gi, " 😇 ")
.replace(/ :\*/g, " 😗 ")
.replace(/<3/g, " ❤ ")
.replace(/\^_\^/g, " 😊 ")
.replace(/-_-/g, " 😑 ")
.replace(/ >:O/gi, " 😠 ")
.replace(/\(y\)/gi, " 👍 ");
/* uses regex to replace certain patterns. All punctuation, including
space-apostrophe/apostrophe-space patterns also removes punctuation and
symbols not in words */
return fixedContent
.toLowerCase()
.replace(/['"]\s+/g, '') // apostrophe space
.replace(/\s+['"]/g, '') // space apostrophe
.replace(/[.,/\\#!$%^&*;:{}=\-_`"~()[\]@?+><]/g, '') // punctuation
.replace(/\s+/g, ' ') // multiple spaces
.split(' ');
}
function MessageEmojiAnalysis(content) {
// ~~~~~ EMOJIS ~~~~~
// Doesn't contain a valid char - meaning contents is ONLY an emoji
var emojiCharacters = new RegExp("[^\\w‘’“”'" + LatiniseString + "]", "g");
// match anything that contains something that IS NOT an alphanumeric
// charater or apostophe (i.e. must be an emoji)
var messageAllEmojis = content
.filter(n => n.match(emojiCharacters));
// array used to store INDIVIDUAL emojis sent. Eg 3 hearts in a row
// become 3 induvidual hearts
var messageEmojisSent = [];
// use emoji splitter tool to split by emojis.
var splitter = new GraphemeSplitter();
messageAllEmojis.forEach(word => {
// split emojis and other characters
var splitwords = splitter.splitGraphemes(word);
// remove other characters, only leaving emojis
var emojis = splitwords.filter(n => n.match(emojiCharacters));
// add them to the emoji list
emojis.forEach(emoji => {
if (escape(unescape(encodeURIComponent(emoji))).match(/%E2%9D%A4/gi)) {
emoji = "❤";
}
messageEmojisSent.push(emoji);
})
})
return messageEmojisSent;
}
function MessageWordsAnalysis(content) {
// ~~~~~ WORDS ~~~~~
var regularCharacters = new RegExp("[\\w‘’“”'" + LatiniseString + "]", "g");
// Doesn't contain a valid char - meaning contents is ONLY an emoji
var emojiCharacters = new RegExp("[^\\w‘’“”'" + LatiniseString + "]", "g");
/* Match anthing that DOES CONTAIN an alphanumeric character or apostrophe.
this unfiltered list will still contain words that have emojis at the
start/end with no space in between. */
var messageWordsUnfiltered = content
.filter(n => n.match(regularCharacters));
// Remove the emojis so just the word is left.
var messageWordsSent = [];
messageWordsUnfiltered.forEach(word => {
messageWordsSent.push(
word.replace(emojiCharacters, '')
);
})
// remove empty entries, if there are any.
messageWordsSent = messageWordsSent.filter(function (e) { return e });
return messageWordsSent;
}
// ~~~~~ Charting ~~~~~
function ChartData(mainData, subData = null, optionsOverride = null) {
var data = new google.visualization.DataTable();
var colours = palette('mpn65', Participants.length);
var styles = [];
var ctx; // location for chart (set later)
var view; // Google charts DataView, initialised later
// First column setup
if (subData == "Time") {
data.addColumn('datetime', 'Time');
}
else if(subData == "Fulldate"){
data.addColumn('date','Date')
}
else if(mainData == "MessageLengths"){
data.addColumn('number', 'Length');
}
else { // day/ month/year
var displayName = GetColumnDisplayName(mainData, subData);
data.addColumn('string', displayName);
}
// Add other columns. Format:
// [Series1] [Series1 Style] [Series2] [Series2 Style]...
var stylesIndex = 0;
// Conv totals always grey
colours.unshift("6d6d6d");
Participants.forEach(participant =>{
// Add styles for each series using the colours generated from palette()
styles.push(
'fill-color:'+ colours[stylesIndex]+
';fill-opacity: 0.6;'+
'stroke-color:'+ colours[stylesIndex]+
';stroke-width: 0.5;');
// Add columns for participants, and style them induvidually
data.addColumn('number', participant);
data.addColumn({type:'string', role:'style'});
stylesIndex++;
});
if (subData) {
// Add to TimeArrays object depending on the data collected.
SetTimeArrays(mainData, subData);
// ~~~ Adding datarows ~~~
TimeArrays[subData].forEach(element => {
var newRow = [];
// Column 1: Data counted
if(subData == "Time" || subData == "Fulldate") {
newRow.push(new Date(Number(element)));
}
else{
newRow.push(String(element));
}
// Other columns: [Data][Style] [Data][Style] [Data][Style]
stylesIndex = 0;
Participants.forEach(participant => {
// Even Columns: Participant data
if (subData == "Time") {
newRow.push(Conversation[participant][mainData][subData][timeDisplay][element]);
}
else if (subData == "Fulldate") {
newRow.push(Conversation[participant][mainData][subData][fullDateDisplay][element]);
}
else{
newRow.push(Conversation[participant][mainData][subData][element]);
}
// Odd Columns: Participant Style
newRow.push(styles[stylesIndex]);
stylesIndex++;
});
data.addRow(newRow);
});
// Format tooltips depending on the time.
try {
GetTooltipFormat(subData).format(data, 0);
} catch (error) {
console.log("No tooltip formatting required for " + subData + ".")
}
// Set the location for the chart
ctx = document.getElementById("chart-" + mainData + "-" + subData);
}
else { // No subData -> Means only mainData needs to be analysed
// ~~~ Adding datarows ~~~
var messageData = Object.keys(Conversation["ConversationTotals"][mainData]);
if (mainData == "MessageLengths") {
messageData = ArrayString2Number(messageData);
var maxLength = Math.max(...messageData);
// For initally setting the correct max value, and for resetting when it hits zero or less
if (messageLengthsDisplay <= 0) {
document.getElementById("lengths-max").value = maxLength;
}
messageLengthsDisplay = Number(document.getElementById("lengths-max").value);
}
/* This is a bit messy. Words, Emojis and Message lengths code is all
fairly similar, but still different, so they each need their own
set of code */
for (var element of messageData) {
var newRow = NonTimeDataRow(element, mainData, styles)
data.addRow(newRow);
}
if (mainData == "WordsSent" || mainData == "EmojisSent") {
// Sort according to ConversationTotals
data.sort([{column: 1, desc: true}]);
view = new google.visualization.DataView(data);
// Do different things depending of if Words or Emojis
switch (mainData) {
case "WordsSent":
// For words, filter by the min/max lenght specified
var filteredView = GetWordsFilteredRows(view);
// Set the rows to the display limit specified.
// If words availables is less than words display, show that many
if (view.getNumberOfRows() < wordsDisplay) {
view.setRows([...Array(view.getNumberOfRows()).keys()]);
} else {
view.setRows(filteredView.slice(0, wordsDisplay));
}
break;
case "EmojisSent":
emojisDisplay = 20;
// If words availables is less than emojisDisplay, show that many
if (view.getNumberOfRows() < emojisDisplay) {
view.setRows([...Array(view.getNumberOfRows()).keys()]);
emojisDisplay = view.getNumberOfRows();
} else {
view.setRows([...Array(emojisDisplay).keys()]);
}
break;
default:
break;
}
}
// Set the location context for the chart
ctx = document.getElementById("chart-" + mainData);
}
if (mainData == "WordsSent" || mainData == "EmojisSent") {
var dashboard = new google.visualization.Dashboard(document.getElementById(mainData + "-dashboard"));
var tableView = new google.visualization.DataView(data)
if (mainData == "WordsSent") {
var filteredView = GetWordsFilteredRows(tableView);
tableView.setRows(filteredView);
}
var displayColumns = [0].concat([...
Array(data.getNumberOfColumns()).keys()] // e.g. [0,1,2,3,4,5]
.filter(n => n%2)); // keep odd numbers only
tableView.setColumns(displayColumns);
var stringFilter = new google.visualization.ControlWrapper({
controlType: 'StringFilter',
containerId: mainData + '-filter',
options: {
filterColumnIndex: 0
}
});
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: mainData + '-table',
options: {
showRowNumber: true,
page: 'enable',
pageSize: 10,
allowHtml: true,
cssClassNames: {
tableCell: 'emoji-font',
headerRow: 'bg-primary text-light'
}
}
});
dashboard.bind([stringFilter], [table]);
dashboard.draw(tableView);
// draw backup image emoji table
if (mainData == "EmojisSent") {
CreateEmojisImageTable(tableView);
}
}
// Get options
var options = GetChartOptions(mainData, subData, colours);
// Loop through options passed in and add them to options,
// or override if they already exist.
if (optionsOverride) {
for (var attribute in optionsOverride) {
options[attribute] = optionsOverride[attribute];
}
}
// When the user makes a change to one of the options, the chart should
// update with the same column type. This gets the column chart options
// and adds it to the options.
var columnOptions = CheckChartColumnOptions(mainData, subData)
for (var attribute in columnOptions) {
options[attribute] = columnOptions[attribute];
}
var chartTitle = GetChartTitle(mainData, subData);
var titleDiv;
if (subData) {
titleDiv = document.getElementById(`container-${mainData}-${subData}`).querySelector(".chart-title").innerHTML = chartTitle;
} else {
titleDiv = document.getElementById(`container-${mainData}`).querySelector(".chart-title").innerHTML = chartTitle;
}
// Instantiate and draw chart, passing in the options.
var chart = new google.visualization.ColumnChart(ctx);
if (view) {
// Remove ConversationTotals from being displayed
var displayColumns = [...Array(data.getNumberOfColumns()).keys()];