-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathMMM-CoinMarketCap.js
executable file
·1327 lines (1278 loc) · 43.8 KB
/
MMM-CoinMarketCap.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
/* global Module */
/**
* Magic Mirror
* Module: MMM-CoinMarketCap
*
* By David Dearden
* MIT Licensed.
*/
/**
* Register the module with the MagicMirror program
*/
Module.register("MMM-CoinMarketCap", {
/**
* The default configuration options
*/
defaults: {
apiKey: null,
currencies: [1, 1027], // The currencies to display, in the order that they will be displayed
columns: ["name", "price", "change1h", "change24h", "change7d"], // The columns to display, in the order that they will be displayed
conversion: "USD",
showColumnHeaders: true, // Enable / Disable the column header text. Set to an array to enable by name
columnHeaderText: {},
showRowSeparator: true,
fullWidthMode: true, // If true, the module will fill the space of the region when other modules in the region are wider
fontSize: "small",
fontColor: "", // https://www.w3schools.com/cssref/css_colors_legal.asp
percentChangeColored: false,
significantDigits: 0, // How many significant digits to round to in the price display
decimalPlaces: 2, // How many decimal places to show
usePriceDigitGrouping: true, // Whether to use locale specific separators for currency (1000 vs 1,000)
showCurrencyWithPrice: false,
logoSize: "medium", // small, medium, large, "x-large"
logoColored: false, // if true, use the original logo, if false, use filter to make a black and white version
cacheLogos: true, // Whether to download the logos from coinmarketcap or just access them from the site directly
graphRange: 7, // How many days for the graph data. Options: 1, 7, 30
graphSize: "medium", // The graph size to display. Options: "x-small", "small", "medium", "large", "x-large"
graphColored: false,
updateInterval: 10, // Minutes, minimum 5
retryDelay: 10, // Seconds, minimum 0
tallHeader: null,
developerMode: false,
},
/**
* The minimum version of magic mirror that is required for this module to run.
*/
requiresVersion: "2.2.1",
/**
* Override the setConfig function to change some of the default configuration options (based on the user's view option)
* before they are merged with the user configuration options
*
* @param config (object) The user specified configuration options
*/
setConfig: function (config) {
var self = this;
if (typeof config.view === "string") {
switch (config.view) {
case "detailedSymbol":
self.defaults.columns = [
"symbol",
"price",
"change1h",
"change24h",
"change7d",
];
break;
case "detailedWithUSD":
self.defaults.columns = [
"name",
"price",
"change1h",
"change24h",
"change7d",
];
break;
case "graph":
self.defaults.columns = ["logo", "price", "graph"];
self.defaults.showColumnHeaders = false;
self.defaults.percentChangeColored = true;
self.defaults.fullWidthMode = false;
self.defaults.fontSize = "medium";
break;
case "graphColored":
self.defaults.columns = ["logo", "price", "graph"];
self.defaults.showColumnHeaders = false;
self.defaults.percentChangeColored = true;
self.defaults.fullWidthMode = false;
self.defaults.logoColored = true;
self.defaults.fontSize = "medium";
self.defaults.graphColored = true;
break;
case "graphWithChanges":
self.defaults.columns = ["logo", "priceWithChanges", "graph"];
self.defaults.showColumnHeaders = false;
self.defaults.percentChangeColored = true;
self.defaults.showCurrencyWithPrice = true;
self.defaults.fullWidthMode = false;
break;
case "logo":
self.defaults.columns = ["logo", "price"];
self.defaults.showColumnHeaders = false;
self.defaults.showCurrencyWithPrice = true;
self.defaults.fontSize = "medium";
self.defaults.fullWidthMode = false;
break;
case "logoColored":
self.defaults.columns = ["logo", "price"];
self.defaults.showColumnHeaders = false;
self.defaults.showCurrencyWithPrice = true;
self.defaults.fontSize = "medium";
self.defaults.logoColored = true;
self.defaults.fullWidthMode = false;
break;
default:
// for the case "detailed":
self.defaults.columns = [
"name",
"price",
"change1h",
"change24h",
"change7d",
];
}
}
self.config = Object.assign({}, self.defaults, config);
},
/**
* Override the start function. Set some instance variables and validate the selected
* configuration options before loading the rest of the module.
*/
start: function () {
var self = this;
var i, c;
self.instanceID =
self.identifier + "_" + Math.random().toString().substring(2);
self.sendSocketNotification("INIT", { instanceID: self.instanceID });
self.loaded = false;
self.dataLoaded = false;
self.listings = null;
self.updateTimer = null;
self.lastUpdateTime = new Date(0);
self.currencyData = {};
self.logosURLTemplate =
"https://s2.coinmarketcap.com/static/img/coins/{size}x{size}/{id}.png";
self.graphURLTemplate =
"https://s3.coinmarketcap.com/generated/sparklines/web/{range}d/2781/{id}.svg?noCache={noCache}";
self.apiBaseURL = "https://pro-api.coinmarketcap.com/";
self.apiVersion = "v1/";
self.apiListingsEndpoint = "cryptocurrency/map";
self.maxListingAttempts = 4; // How many times to try downloading the listing before giving up and displaying an error
self.apiTickerEndpoint = "cryptocurrency/quotes/latest";
self.maxTickerAttempts = 2; // How many times to try updating a currency before giving up
self.allColumnTypes = [
"name",
"symbol",
"price",
"logo",
"change1h",
"change24h",
"change7d",
"graph",
"changes",
"priceWithChanges",
];
self.tallColumns = ["graph", "changes", "priceWithChanges"];
self.tableHeader = null;
self.LocalLogoFolder = self.data.path + "logos/";
self.LocalLogoFolderBW = self.data.path + "logos/bw/";
self.httpLogoFolder = "/" + self.name + "/logos/";
self.httpLogoFolderBW = "/" + self.name + "/logos/bw/";
self.validLogoSizes = ["small", "medium", "large", "x-large"];
self.validFontSizes = ["x-small", "small", "medium", "large", "x-large"];
self.validGraphSizes = ["x-small", "small", "medium", "large", "x-large"];
self.validGraphRangeValues = [1, 7, 30];
self.logoSizeToPX = { small: 16, medium: 32, large: 64, "x-large": 128 };
// Process and validate configuration options
if (!axis.isString(self.config.apiKey) || self.config.apiKey.length < 1) {
self.config.apiKey = self.defaults.apiKey;
}
self.apiKey = self.config.apiKey;
self.defaults.columnHeaderText = {
name: self.translate("CURRENCY_TITLE"),
symbol: self.translate("CURRENCY_TITLE"),
price: self.translate("PRICE_TITLE", { conversion_var: "{conversion}" }),
priceWithChanges: self.translate("PRICE_TITLE", {
conversion_var: "{conversion}",
}),
logo: "",
change1h: self.translate("HOUR_TITLE"),
change24h: self.translate("DAY_TITLE"),
change7d: self.translate("WEEK_TITLE"),
graph: self.translate("TREND_TITLE", {
range_var: "{range}",
days_var: "{days}",
}),
changes: self.translate("CHANGES_TITLE"),
};
if (!axis.isObject(self.config.columnHeaderText)) {
self.config.columnHeaderText = {};
}
for (var key in self.config.columnHeaderText) {
if (
self.config.columnHeaderText.hasOwnProperty(key) &&
axis.isString(self.config.columnHeaderText[key])
) {
self.defaults.columnHeaderText[key] = self.config.columnHeaderText[key];
}
}
self.config.columnHeaderText = self.defaults.columnHeaderText;
if (!axis.isArray(self.config.currencies)) {
self.config.currencies = self.defaults.currencies;
} else {
// Filter out invalid currency configurations (must have an id or name)
self.config.currencies = self.config.currencies.filter(function (val) {
return (
(axis.isNumber(val) && !isNaN(val) && val > 0) ||
(axis.isString(val) && val.length > 0) ||
(axis.isObject(val) &&
((axis.isNumber(val.id) && !isNaN(val.id) && val.id > 0) ||
(axis.isString(val.name) && val.name.length > 0)))
);
});
}
if (
axis.isNumber(self.config.retryDelay) &&
!isNaN(self.config.retryDelay) &&
self.config.retryDelay >= 0
) {
self.config.retryDelay = self.config.retryDelay * 1000;
} else {
self.config.retryDelay = self.defaults.retryDelay * 1000;
}
if (
axis.isNumber(self.config.updateInterval) &&
!isNaN(self.config.updateInterval) &&
self.config.updateInterval >= 5
) {
self.config.updateInterval = self.config.updateInterval * 60 * 1000;
} else {
self.config.updateInterval = self.defaults.updateInterval * 60 * 1000;
}
if (!axis.isArray(self.config.columns)) {
self.config.view = self.defaults.columns;
}
if (axis.isArray(self.config.showColumnHeaders)) {
// filter out items from config.showColumnHeaders that are not in allColumnTypes
self.config.showColumnHeaders = self.config.showColumnHeaders.filter(
function (val) {
return this.includes(val);
},
self.allColumnTypes
);
}
if (
(!axis.isBoolean(self.config.showColumnHeaders) &&
!axis.isArray(self.config.showColumnHeaders)) ||
(axis.isArray(self.config.showColumnHeaders) &&
self.config.showColumnHeaders.length < 1)
) {
self.config.showColumnHeaders = self.defaults.showColumnHeaders;
}
if (!self.validLogoSizes.includes(self.config.logoSize)) {
self.config.logoSize = self.defaults.logoSize;
}
if (!axis.isBoolean(self.config.logoColored)) {
self.config.logoColored = self.defaults.logoColored;
}
if (!axis.isBoolean(self.config.cacheLogos)) {
self.config.cacheLogos = self.defaults.cacheLogos;
}
if (!axis.isBoolean(self.config.percentChangeColored)) {
self.config.percentChangeColored = self.defaults.percentChangeColored;
}
if (
!axis.isString(self.config.conversion) ||
self.config.conversion.length < 1
) {
self.config.conversion = self.defaults.conversion;
}
if (
!axis.isNumber(self.config.significantDigits) ||
isNaN(self.config.significantDigits) ||
self.config.significantDigits < 0
) {
self.config.significantDigits = self.defaults.significantDigits;
} else {
self.config.significantDigits = Math.round(self.config.significantDigits);
}
if (
!axis.isNumber(self.config.decimalPlaces) ||
isNaN(self.config.decimalPlaces) ||
self.config.decimalPlaces < 0
) {
self.config.decimalPlaces = self.defaults.decimalPlaces;
} else {
self.config.decimalPlaces = Math.round(self.config.decimalPlaces);
}
if (!axis.isBoolean(self.config.usePriceDigitGrouping)) {
self.config.usePriceDigitGrouping = self.defaults.usePriceDigitGrouping;
}
if (!self.validGraphRangeValues.includes(self.config.graphRange)) {
self.config.graphRange = self.defaults.graphRange;
}
if (!self.validFontSizes.includes(self.config.fontSize)) {
self.config.fontSize = self.defaults.fontSize;
}
if (!self.validGraphSizes.includes(self.config.graphSize)) {
self.config.graphSize = self.defaults.graphSize;
}
if (!axis.isBoolean(self.config.graphColored)) {
self.config.graphColored = self.defaults.graphColored;
}
if (!axis.isBoolean(self.config.showRowSeparator)) {
self.config.showRowSeparator = self.defaults.showRowSeparator;
}
if (!axis.isString(self.config.fontColor)) {
self.config.fontColor = self.defaults.fontColor;
}
if (!axis.isBoolean(self.config.showCurrencyWithPrice)) {
self.config.showCurrencyWithPrice = self.defaults.showCurrencyWithPrice;
}
if (!axis.isBoolean(self.config.developerMode)) {
self.config.developerMode = self.defaults.developerMode;
}
if (!axis.isBoolean(self.config.fullWidthMode)) {
self.config.fullWidthMode = self.defaults.fullWidthMode;
}
if (!axis.isBoolean(self.config.tallHeader)) {
self.config.tallHeader = self.config.columns.some(function (val) {
return this.includes(val);
}, self.tallColumns);
}
// Configure all the currencies as objects with the requested settings
for (i = 0; i < self.config.currencies.length; i++) {
c = self.config.currencies[i];
// Ensure that the currency is an object
if (axis.isNumber(c)) {
c = self.config.currencies[i] = { id: c };
} else if (axis.isString(c)) {
c = self.config.currencies[i] = { name: c };
}
if (!self.validLogoSizes.includes(c.logoSize)) {
c.logoSize = self.config.logoSize;
}
c.logoSizePX = self.logoSizeToPX[c.logoSize];
if (!axis.isBoolean(c.logoColored)) {
c.logoColored = self.config.logoColored;
}
if (!axis.isBoolean(c.percentChangeColored)) {
c.percentChangeColored = self.config.percentChangeColored;
}
if (
!axis.isNumber(c.significantDigits) ||
isNaN(c.significantDigits) ||
c.significantDigits < 0
) {
c.significantDigits = self.config.significantDigits;
} else {
c.significantDigits = Math.round(c.significantDigits);
}
if (
!axis.isNumber(c.decimalPlaces) ||
isNaN(c.decimalPlaces) ||
c.decimalPlaces < 0
) {
c.decimalPlaces = self.config.decimalPlaces;
} else {
c.decimalPlaces = Math.round(c.decimalPlaces);
}
if (!axis.isBoolean(c.usePriceDigitGrouping)) {
c.usePriceDigitGrouping = self.config.usePriceDigitGrouping;
}
if (!self.validFontSizes.includes(c.fontSize)) {
c.fontSize = self.config.fontSize;
}
if (!self.validGraphSizes.includes(c.graphSize)) {
c.graphSize = self.config.graphSize;
}
if (!axis.isString(c.fontColor) || c.fontColor.length < 1) {
c.fontColor = self.config.fontColor;
}
if (!axis.isBoolean(c.showCurrencyWithPrice)) {
c.showCurrencyWithPrice = self.config.showCurrencyWithPrice;
}
}
// Replace variables in the column header text
self.config.columnHeaderText.price = self.replaceAll(
self.config.columnHeaderText.price,
"{conversion}",
self.config.conversion
);
self.config.columnHeaderText.priceWithChanges = self.replaceAll(
self.config.columnHeaderText.priceWithChanges,
"{conversion}",
self.config.conversion
);
var range = self.translate("ONE_WEEK");
if (self.config.graphRange === 1) {
range = self.translate("ONE_DAY");
} else if (self.config.graphRange === 30) {
range = self.translate("ONE_MONTH");
}
self.config.columnHeaderText.graph = self.replaceAll(
self.config.columnHeaderText.graph,
"{range}",
range
);
self.config.columnHeaderText.graph = self.replaceAll(
self.config.columnHeaderText.graph,
"{days}",
self.config.graphRange
);
self.log("start(): self.data: " + JSON.stringify(self.data), "dev");
self.log("start(): self.config: " + JSON.stringify(self.config), "dev");
// Start the loading process by requesting the currency listings
if (!self.apiKey) {
self.updateDom(0);
} else {
self.getListings(1);
}
},
/**
* Override the suspend function that is called when the module instance is hidden.
* This method stops the update timer.
*/
suspend: function () {
var self = this;
self.log(self.translate("SUSPENDED") + ".");
clearInterval(self.updateTimer);
},
/**
* Override the resume function that is called when the module instance is un-hidden.
* This method re-starts the update timer and calls for an update if the update interval
* has been passed since the module was suspended.
*/
resume: function () {
var self = this;
self.log(self.translate("RESUMED") + ".");
self.scheduleUpdate();
var date = new Date();
var threshold = new Date(
self.lastUpdateTime.getTime() + self.config.updateInterval
);
if (date >= threshold) {
self.getAllCurrencyDetails(1);
}
},
/**
* The scheduleUpdate function starts the auto update timer.
*/
scheduleUpdate: function () {
var self = this;
if (self.updateTimer) {
clearInterval(self.updateTimer);
}
self.updateTimer = setInterval(function () {
self.getAllCurrencyDetails(1);
}, self.config.updateInterval);
self.log(
self.translate("UPDATE_SCHEDULED", {
minutes: self.config.updateInterval / (1000 * 60),
})
);
},
/**
* The getListings function sends a request to the node helper to download the list of available currencies.
*
* @param attemptNum (number) The number of attempts to download the listings
*/
getListings: function (attemptNum) {
var self = this;
self.log(self.translate("LISTINGS_REQUESTED"));
var url = self.apiBaseURL + self.apiVersion + self.apiListingsEndpoint;
self.sendSocketNotification("GET_LISTINGS", {
apiKey: self.apiKey,
instanceID: self.instanceID,
url: url,
attemptNum: attemptNum,
notification: "LISTINGS_RECEIVED",
});
},
/**
* The getAllCurrencyDetails function loops through the list of currencies and initiates requests to
* download the latest information for each currency.
*/
getAllCurrencyDetails: function (attemptNum) {
var self = this;
if (axis.isUndefined(attemptNum)) {
attemptNum = 1;
}
self.log(self.translate("UPDATE_STARTED"));
self.lastUpdateTime = new Date();
var id_list = [];
for (var key in self.currencyData) {
if (!self.currencyData.hasOwnProperty(key)) {
continue;
}
id_list.push(key);
}
var id_string = id_list.join(",");
var url =
self.apiBaseURL +
self.apiVersion +
self.apiTickerEndpoint +
"?id=" +
id_string +
"&convert=" +
self.config.conversion;
self.sendSocketNotification("GET_CURRENCY_DETAILS", {
apiKey: self.apiKey,
instanceID: self.instanceID,
url: url,
id: id_string,
attemptNum: attemptNum,
notification: "CURRENCY_DETAILS_RECEIVED",
});
},
/**
* The cacheLogos function sends a download request to the node helper for the logos of the configured currencies.
*/
cacheLogos: function () {
var self = this;
if (!self.config.cacheLogos || !self.config.columns.includes("logo")) {
return;
}
for (var key in self.currencyData) {
if (!self.currencyData.hasOwnProperty(key)) {
continue;
}
var symbol = self.currencyData[key].symbol.toLowerCase();
for (var sizeKey in self.logoSizeToPX) {
if (!self.logoSizeToPX.hasOwnProperty(sizeKey)) {
continue;
}
var sizePX = self.logoSizeToPX[sizeKey];
var imageURL = self.getLogoURL(sizePX, key);
if (
!self.fileExists(self.httpLogoFolder + symbol + "-" + sizePX + ".png")
) {
self.log(
self.translate("REQUEST_LOGO_DOWNLOAD", { filename: imageURL })
);
self.sendSocketNotification("DOWNLOAD_FILE", {
instanceID: self.instanceID,
url: imageURL,
saveToFileName:
self.LocalLogoFolder + symbol + "-" + sizePX + ".png",
attemptNum: 1,
notification: "LOGO_DOWNLOADED",
});
}
}
}
},
/**
* Override the socketNotificationReceived function to handle the notifications sent from the node helper
*
* @param notification (string) The type of notification sent
* @param payload (any) The data sent with the notification
*/
socketNotificationReceived: function (notification, payload) {
var self = this;
// If there is no module ID sent with the notification
if (!axis.isString(payload.original.instanceID)) {
if (notification === "LOG") {
if (payload.translate) {
self.log(
self.translate(payload.message, payload.translateVars),
payload.logType
);
} else {
self.log(payload.message, payload.logType);
}
}
return;
}
// Filter out notifications for other instances
if (payload.original.instanceID !== self.instanceID) {
self.log(
'Notification ignored for ID "' + payload.original.instanceID + '".',
"dev"
);
return;
}
if (notification === "LOG") {
if (payload.translate) {
self.log(
self.translate(payload.message, payload.translateVars),
payload.logType
);
} else {
self.log(payload.message, payload.logType);
}
} else if (notification === "LISTINGS_RECEIVED" && !self.loaded) {
if (payload.isSuccessful && payload.data.status.error_code == 0) {
self.log(
self.translate("LISTINGS_SUCCESS", {
numberOfAttempts: payload.original.attemptNum,
})
);
self.listings = payload.data.data;
self.filterCurrenciesAndSetupDataSet();
self.loaded = true;
self.updateDom(0);
self.scheduleUpdate();
self.getAllCurrencyDetails(1);
self.cacheLogos();
self.log(
"self.config.currencies: " + JSON.stringify(self.config.currencies),
"dev"
);
} else if (payload.original.attemptNum < self.maxListingAttempts) {
self.log(self.translate("LISTINGS_FAILURE", { retryTimeInSeconds: 8 }));
setTimeout(function () {
self.getListings(Number(payload.original.attemptNum) + 1);
}, 8000);
} else {
if (payload.data) {
self.listings = payload.data;
} else {
self.listings = payload.response.statusCode;
}
self.loaded = true;
self.updateDom(0);
}
} else if (notification === "CURRENCY_DETAILS_RECEIVED") {
if (payload.isSuccessful && payload.data.status.error_code == 0) {
self.log(
self.translate("CURRENCY_UPDATE_SUCCESS", {
id: payload.original.id,
numberOfAttempts: payload.original.attemptNum,
})
);
self.updateCurrencyData(payload.data.data);
self.updateDom(0);
} else if (payload.original.attemptNum < self.maxTickerAttempts) {
self.log(
self.translate("CURRENCY_UPDATE_FAILURE", {
id: payload.original.id,
retryTimeInSeconds: self.config.retryDelay / 1000,
})
);
setTimeout(function () {
self.getAllCurrencyDetails(Number(payload.original.attemptNum) + 1);
}, self.config.retryDelay);
}
} else if (notification === "LOGO_DOWNLOADED") {
if (payload.isSuccessful) {
self.log(
self.translate("LOGO_DOWNLOAD_SUCCESS", {
filename: payload.original.saveToFileName,
})
);
} else {
self.log(
self.translate("LOGO_DOWNLOAD_FAILURE", {
filename: payload.original.saveToFileName,
})
);
}
}
},
/**
* The filterCurrenciesAndSetupDataSet function compares the requested currency list with the downloaded listings.
* It filters out requested currencies that are not on the listing and setups up an entry in the currencyData
* object for all the valid currencies.
*/
filterCurrenciesAndSetupDataSet: function () {
var self = this;
var i, c, listing;
var temp = [];
for (i = 0; i < self.config.currencies.length; i++) {
c = self.config.currencies[i];
listing = self.selectListing(c.id, c.name);
if (axis.isUndefined(listing)) {
self.log(
self.translate("INVALID_CURRENCY", { name: c.name, id: c.id }),
"warn"
);
} else {
c.id = listing.id;
c.name = listing.name;
c.symbol = listing.symbol;
c.website_slug = listing.slug;
temp.push(c);
self.currencyData[listing.id] = {
name: listing.name,
symbol: listing.symbol,
data: null,
loaded: false,
};
}
}
self.config.currencies = temp;
},
/**
* The selectListing function is a helper function for filterCurrenciesAndSetupDataSet.
* It searches the listing by id and name to determine whether a currency exists.
*
* @param id (number) The id of the currency to search for
* @param name (string) The symbol, name or slug of the currency to search for
* @return (boolean) returns true if the currency was found in the list, false otherwise
*/
selectListing: function (id, name) {
var self = this;
if (!axis.isNumber(id) || isNaN(id)) {
id = null;
}
if (!axis.isString(name)) {
name = null;
} else {
name = name.toLowerCase();
}
return self.listings.find(
function (listing) {
return (
listing.id === this.id ||
listing.symbol.toLowerCase() === this.name ||
listing.name.toLowerCase() === this.name ||
listing.slug === this.name
);
},
{ id: id, name: name }
);
},
/**
* The updateCurrencyData function sets the data parameter of the currencyData item with the given data set.
* This function is called when new data is received from the API request.
* It also sets variables to track whether data has been received.
*
* @param data (object) The data object received from the API
*/
updateCurrencyData: function (data) {
var self = this;
for (var key in data) {
if (!data.hasOwnProperty(key)) {
continue;
}
var id = data[key].id;
if (!self.currencyData[id].loaded) {
self.currencyData[id].loaded = true;
}
if (!self.dataLoaded) {
self.dataLoaded = true;
}
self.currencyData[id].data = data[key];
}
},
/**
* Override the notificationReceived function.
* For now, there are no actions based on system or module notifications.
*
* @param notification (string) The type of notification sent
* @param payload (any) The data sent with the notification
* @param sender (object) The module that the notification originated from
*/
notificationReceived: function (notification, payload, sender) {
if (sender) {
// If the notification is coming from another module
}
},
/**
* Override the getDom function to generate the DOM objects to be displayed for this module instance
*/
getDom: function () {
// Initialize some variables
var self = this;
var c, i, k;
var wrapper = document.createElement("div");
//wrapper.classList.add("small");
if (!self.apiKey) {
wrapper.classList.add("loading");
wrapper.classList.add("small");
wrapper.innerHTML += self.translate("API_KEY_REQUIRED");
return wrapper;
}
if (!self.loaded) {
wrapper.classList.add("loading");
wrapper.classList.add("small");
wrapper.innerHTML += self.translate("LOADING");
return wrapper;
}
if (!axis.isArray(self.listings)) {
wrapper.classList.add("loading");
wrapper.classList.add("small");
wrapper.innerHTML += self.translate("API_ERROR", {
website: "CoinMarketCap.com",
});
if (self.config.developerMode) {
wrapper.innerHTML += "<br />Error: " + self.listings;
}
return wrapper;
}
if (!self.dataLoaded) {
wrapper.classList.add("loading");
wrapper.classList.add("small");
wrapper.innerHTML += self.translate("LOADING");
return wrapper;
}
var table = document.createElement("table");
if (self.config.showRowSeparator) {
table.classList.add("row-separator");
}
if (self.config.fullWidthMode) {
table.classList.add("fullSize");
} else {
table.classList.add("minimalSize");
}
if (self.config.tallHeader) {
table.classList.add("tallHeader");
}
if (self.tableHeader === null) {
self.tableHeader = self.getTableHeader();
}
if (self.tableHeader !== null) {
table.appendChild(self.tableHeader);
}
for (k = 0; k < self.config.currencies.length; k++) {
c = self.config.currencies[k];
if (self.currencyData[c.id].loaded) {
var row = document.createElement("tr");
if (c.fontColor.length > 0) {
row.style.color = c.fontColor;
}
row.classList.add(c.fontSize);
for (i = 0; i < self.config.columns.length; i++) {
row.appendChild(self.getCell(self.config.columns[i], c));
}
table.appendChild(row);
}
}
wrapper.appendChild(table);
return wrapper;
},
/**
* The getTableHeader function generates the header row of the main display table
*
* @return (object) The DOM object containing the table header row
*/
getTableHeader: function () {
var self = this;
var output = null,
i;
if (
self.config.showColumnHeaders === true ||
(axis.isArray(self.config.showColumnHeaders) &&
self.config.showColumnHeaders.length > 0)
) {
output = document.createElement("tr");
output.classList.add(self.config.fontSize);
if (self.config.fontColor.length > 0) {
output.style.color = self.config.fontColor;
}
for (i = 0; i < self.config.columns.length; i++) {
var cell = document.createElement("th");
cell.classList.add("cell-" + self.config.columns[i]);
if (
self.config.showColumnHeaders === true ||
(axis.isArray(self.config.showColumnHeaders) &&
self.config.showColumnHeaders.includes(self.config.columns[i]))
) {
cell.innerHTML = self.config.columnHeaderText[self.config.columns[i]];
} else {
cell.innerHTML = " ";
}
output.appendChild(cell);
}
}
return output;
},
/**
* The getCell function generates the content for each table cell given the currency (row) and column type
*
* @param (string) colType the type of column to generate
* @param (object) currency a currency object from the self.config.currencies list
* @return (object) a DOM object containing the cell content
*/
getCell: function (colType, currency) {
var self = this;
var data = self.currencyData[currency.id].data;
var cell = document.createElement("td");
var conversion = self.config.conversion;
switch (colType) {
case "name":
cell.classList.add("cell-" + colType);
cell.innerHTML = data.name;
break;
case "symbol":
cell.classList.add("cell-" + colType);
cell.innerHTML = data.symbol;
break;
case "price":
cell.classList.add("cell-" + colType);
if (
axis.isObject(data.quote[conversion]) &&
!axis.isNull(data.quote[conversion])
) {
var price = self.conformNumber(
data.quote[conversion].price,
currency.significantDigits,
currency.decimalPlaces
);
var priceOptions = {
style: "currency",
currency: self.config.conversion,
useGrouping: currency.usePriceDigitGrouping,
};
priceOptions.minimumFractionDigits =
priceOptions.maximumFractionDigits = currency.decimalPlaces;
// Localize the price and remove currency label
cell.innerHTML = Number(price)
.toLocaleString(config.language, priceOptions)
.replace(/[A-Za-z]+/g, "");
// Language Codes (BCP 47) https://github.com/libyal/libfwnt/wiki/Language-Code-identifiers
if (currency.showCurrencyWithPrice) {
cell.innerHTML += " " + self.config.conversion;
}
} else {
cell.innerHTML = "?";
}
break;
case "change1h":
cell.classList.add("cell-" + colType);
if (
currency.percentChangeColored &&
data.quote[conversion].percent_change_1h >= 0
) {
cell.classList.add("positive");
}
if (
currency.percentChangeColored &&
data.quote[conversion].percent_change_1h < 0
) {
cell.classList.add("negative");
}
cell.innerHTML = Number(
data.quote[conversion].percent_change_1h / 100
).toLocaleString(config.language, {
style: "percent",
currency: self.config.conversion,
maximumFractionDigits: 2,
});
break;
case "change24h":
cell.classList.add("cell-" + colType);
if (
currency.percentChangeColored &&
data.quote[conversion].percent_change_24h >= 0
) {
cell.classList.add("positive");
}
if (
currency.percentChangeColored &&
data.quote[conversion].percent_change_24h < 0
) {
cell.classList.add("negative");
}
cell.innerHTML = Number(
data.quote[conversion].percent_change_24h / 100
).toLocaleString(config.language, {
style: "percent",
currency: self.config.conversion,