/
content.js
586 lines (472 loc) · 18.4 KB
/
content.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
var global = {
//default settings
'settings': {
//use all tokens
'top': 0,
//output currency
'currency': 'usd',
//period for price change
'period': '24h',
//also look for the coin name
'checkNames': true,
//also ignore case
'ignoreCase': true,
//minimal mode or widget mode
'style': 'minimal',
//theme dark or light
'theme': 'dark',
//logging prints in console which matches are detected
'logging': false
}
}
//Get the price from coinmarketcap api
async function getPrice() {
try {
let top = global.settings.top
let currency = global.settings.currency
let response = await fetch("https://api.coinmarketcap.com/v1/ticker/?limit=" + top + "&convert=" + currency);
let data = await response.json();
return data;
} catch (error) {
console.error("Cryptip Error: " + error);
}
}
function filterCoinName(name) {
//Remove meta information in the name surrounded by () or []
name = name.replace(/ \[.*?\]/g, '');
name = name.replace(/ \(.*?\)/g, '');
//Remove spaces from the front and back
name = name.trim();
return name;
}
function createCoinDictionary(coinMarketCapData) {
var coinDictionary = {};
var checkNames = global.settings.checkNames;
for (coin in coinMarketCapData) {
//Note that we make the whole dictionary keys uppercase
var coinSymbol = coinMarketCapData[coin]['symbol'].toUpperCase();
if (!(coinSymbol in coinDictionary)) {
coinDictionary[coinSymbol] = [];
}
coinDictionary[coinSymbol].push(coinMarketCapData[coin]);
//only run this if the user also wants to add cryptip to coin names
if (checkNames) {
var coinName = coinMarketCapData[coin]['name'].toUpperCase();
//remove meta information from coin name
coinName = filterCoinName(coinName);
if (!(coinName in coinDictionary)) {
coinDictionary[coinName] = [];
}
// dont want to double up on the array when it is the same coin
if (coinName != coinSymbol) {
coinDictionary[coinName].push(coinMarketCapData[coin]);
}
}
}
return coinDictionary;
}
//store price information into local storage
async function storePrice() {
try {
var coinMarketCapData = await getPrice();
global.coinDictionary = createCoinDictionary(coinMarketCapData);
var time = (new Date()).getTime();
console.log('Cryptip: Storing new CoinMarketCap data at ' + (new Date(time).toString()));
return await browser.storage.local.set({
'coinDictionary': JSON.stringify(global.coinDictionary),
'time': time
});
} catch (error) {
console.error("Cryptip Error: " + error);
}
}
//Check if plugin is enabled
function checkBlacklist() {
if (global.blacklist) {
var site = window.location.hostname
if (global.blacklist.includes(site)) {
return false;
}
}
return true;
}
async function checkStorage() {
try {
//Get whatever is in the local storage
var storage = await browser.storage.local.get();
//check blacklist
if (storage.blacklist) {
global.blacklist = JSON.parse(storage.blacklist);
global.enabled = checkBlacklist();
//if not enabled, no need to do anything more
if (!global.enabled) {
return null;
}
} else {
global.enabled = true;
}
//Set the settings
if (storage.settings) {
global.settings = JSON.parse(storage.settings);
}
//check time
if (storage.time) {
let currentTime = (new Date()).getTime();
let timeDiff = currentTime - storage.time;
let min = ((timeDiff / 1000) / 60);
//if more than a minute, then get new price information
if (min > 1) {
console.log('Cryptip: Over 1 minute has passed, getting new price data.');
await storePrice();
} else {
global.coinDictionary = JSON.parse(storage.coinDictionary)
console.log('Cryptip: No need to get new data for another ' + Math.round(60 * (1 - min)) + ' seconds.');
}
//if no time information, get data for the first time
} else {
console.log('Cryptip: Getting price data for the first time.');
await storePrice();
}
} catch (error) {
console.error("Cryptip Error: " + error);
}
}
//convert symbols which affect regular expressions into regular expression safe symbols
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function createPriceString(sym) {
try {
var coinDictionary = global.coinDictionary
var currency = global.settings.currency
var period = global.settings.period
sym = sym.toUpperCase()
var priceString = "";
var afterString = currency.toUpperCase() + " ";
//add currency symbol, more work can be done here, probably not worth
switch (currency) {
case 'usd':
priceString += '$';
afterString = '';
break;
case 'eur':
priceString += '€';
break;
}
//adjust for relative size of price
var price = parseFloat(coinDictionary[sym][0][('price_' + currency)])
if (price > 1000) {
price = price.toLocaleString(undefined, { maximumFractionDigits: 0, minimumFractionDigits: 0 })
} else if (price > 1) {
price = price.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 })
}
priceString += price + " "
//add currency text
priceString += afterString;
//add percent change
priceString += "("
if (coinDictionary[sym][0][('percent_change_' + period)] > 0) {
//add plus sign if positive
priceString += "+"
}
priceString += coinDictionary[sym][0][('percent_change_' + period)] + "%)"
return priceString
} catch (error) {
console.error("Cryptip Error: " + error)
}
}
function createRegularExpression() {
var coins = Object.keys(global.coinDictionary)
var ignoreCase = global.settings.ignoreCase
//sort by name length so things like "bitcoin cash" aren't accentially marked as bitcoin
coins.sort(function (a, b) {
return b.length - a.length;
});
//fix any problems in the string that may affect the regular expression
coins = coins.map(escapeRegExp)
//should regex ignore case?
var reSettings = ignoreCase ? 'gi' : 'g'
//turn all coins into a giant 'or' statement
var coinsreg = coins.join('|')
var reCoins = new RegExp('\\b(' + coinsreg + ')\\b', reSettings)
return reCoins
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function marketCapString(value) {
value = parseFloat(value)
if (value >= 1e12) {
return (value / 1e12).toFixed(2) + "T"
} else if (value >= 1e9) {
return (value / 1e9).toFixed(2) + "B"
} else if (value >= 1e6) {
return (value / 1e6).toFixed(2) + "M"
} else if (value >= 1e3) {
return (value / 1e3).toFixed(2) + "K"
} else {
return value.toFixed(2)
}
}
function symbolToId(symbol) {
return symbol.replace(/[\W_]/g, '-')
}
//widget, aka minimal = false
function createWidget(sym, priceString) {
try {
if (!(document.getElementById('template-' + sym.replace(/[\W_]/g, '-').toLowerCase()))) {
sym = sym.toUpperCase();
var coins = global.coinDictionary[sym]
for (c in coins) {
var coin = coins[c]
var template = document.createElement('div');
//template support for same symbol
template.id = 'template-' + sym.replace(/[\W_]/g, '-').toLowerCase() + (c > 0 ? c : '');
template.style.display = 'none';
template.innerHTML = `
<div class="cryptip-container">
<div class="cryptip-row">
<div class="cryptip-image cryptip-col-3"><img class="cryptip-img-responsive" src="https://files.coinmarketcap.com/static/img/coins/64x64/${coin.id}.png"></div>
<div class="cryptip-main cryptip-col-9">
<div class="cryptip-title"><a class="cryptip-link" target="_blank" href="https://coinmarketcap.com/currencies/${coin.id}/?utm_source=cryptip">${coin.name} (${coin.symbol})</a></div>
<div class="cryptip-price">${priceString}</div>
<div class="cryptip-btc">${coin.price_btc} BTC</div>
</div>
</div>
<div class="cryptip-row">
<div class="cryptip-rank cryptip-col-4">
<div class="cryptip-subtitle">RANK</div>
<div class="cryptip-subvalue">${coin.rank}</div>
</div>
<div class="cryptip-rank cryptip-col-4">
<div class="cryptip-subtitle">MARKET CAP</div>
<div class="cryptip-subvalue">${marketCapString(coin.market_cap_usd)}</div>
</div>
<div class="cryptip-rank cryptip-col-4">
<div class="cryptip-subtitle">24H VOLUME</div>
<div class="cryptip-subvalue">${marketCapString(coin['24h_volume_usd'])}</div>
</div>
</div>
</div>
`
document.body.appendChild(template);
}
} else {
//console.log("Already made a cryptip for this: " + sym)
}
} catch (error) {
console.error("Cryptip Error: " + error)
}
}
//tooltip aka style = true
function createTip(sym, priceString) {
try {
if (!(document.getElementById('template-' + sym.replace(/[\W_]/g, '-').toLowerCase()))) {
sym = sym.toUpperCase();
var coins = global.coinDictionary[sym]
for (c in coins) {
var coin = coins[c]
var template = document.createElement('div');
//template support for same symbol
template.id = 'template-' + sym.replace(/[\W_]/g, '-').toLowerCase() + (c > 0 ? c : '');
template.style.display = 'none';
template.innerHTML = priceString
document.body.appendChild(template);
}
} else {
//console.log("Already made a cryptip for this: " + sym)
}
} catch (error) {
console.error("Cryptip Error: " + error)
}
}
function addTooltip() {
try {
var logging = global.settings.logging
var regularExpressionCoins = createRegularExpression()
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: regularExpressionCoins,
replace: function (portion, match) {
//portion is the full text in the node
//match is the specific regex match
if (logging) {
console.info('Adding cryptip to:' + portion.text)
}
let priceString = createPriceString(match[0]);
if (global.settings.style == 'minimal') {
createTip(match[0], priceString)
} else if (global.settings.style == 'widget') {
createWidget(match[0], priceString)
} else {
console.error("Cryptip Error: Reset your Cryptip style.")
}
let cryptipWrapper = document.createElement('cryptip')
cryptipWrapper.setAttribute("data-tippy-interactive", "true")
cryptipWrapper.setAttribute("class", "cryptip")
cryptipWrapper.setAttribute("data-coin", match[0])
cryptipWrapper.innerText = portion.text;
return cryptipWrapper;
}
});
//checkPageElementsForCoins(elements, regularExpressionCoins, addCryptipToText)
} catch (error) {
console.error("Cryptip Error: " + error)
}
}
function checkSettings() {
let result = global.settings
result.enabled = global.enabled
return result
}
async function addTooltipAdvance(element) {
let symbol = element.innerText;
symbol = symbol.toUpperCase();
let data = await browser.storage.local.get();
let coins = JSON.parse(data.coinmarketcap);
var price = 0;
for (coin in coins) {
let sym = coins[coin]['symbol'].toUpperCase();
let name = coins[coin]['name'].toUpperCase();
if (symbol == sym || symbol == name) {
price = coins[coin]['price_usd'];
break;
}
}
var tip = document.createElement('div');
tip.innerText = "Symbol: " + symbol + "<br>Price: " + price
return tip;
}
async function addToBlacklist() {
if (!global.blacklist) {
global.blacklist = []
}
var site = window.location.hostname
if (!(global.blacklist.includes(site))) {
global.blacklist.push(site)
disableTippy();
global.enabled = false;
return await browser.storage.local.set({
'blacklist': JSON.stringify(global.blacklist),
});
}
}
async function removeFromBlacklist() {
if (global.blacklist) {
var site = window.location.hostname
if (global.blacklist.includes(site)) {
var index = global.blacklist.indexOf(site);
global.blacklist.splice(index, 1);
var result = await browser.storage.local.set({
'blacklist': JSON.stringify(global.blacklist),
});
global.enabled = true;
await cryptip();
return result
}
}
}
async function cryptip() {
try {
//Retrieves and sets settings, then checks for stale coin data and queries coinmarket cap API
await checkStorage();
//Check cryptip is enabled
if (global.enabled) {
//Check we have coin data
if (global.coinDictionary) {
addTooltip();
// for each element with cryptip
const tip = tippy('.cryptip', {
theme: global.settings.theme,
html: function (element) {
//find what coin it represents
var sym = element.dataset.coin;
//get the cryptip for that coin
var template = '#template-' + sym.replace(/[\W_]/g, '-').toLowerCase();
return template
}
});
} else {
console.error("Cryptip Error: Something went wrong getting the coin information. Try refreshing.")
}
} else {
console.log("Cryptip is disabled for this site.")
}
} catch (error) {
console.error("Cryptip Error: " + error)
}
}
async function cryptipEmbedded() {
var coinMarketCapData = await getPrice();
global.coinDictionary = createCoinDictionary(coinMarketCapData);
addTooltip();
// for each element with cryptip
const tip = tippy('.cryptip', {
theme: global.settings.theme,
html: function (element) {
//find what coin it represents
var sym = element.dataset.coin;
//get the cryptip for that coin
var template = '#template-' + sym.replace(/[\W_]/g, '-').toLowerCase();
return template
}
});
}
function disableTippy() {
var tips = document.querySelectorAll('.cryptip');
for (t in tips) {
var tip = tips[t];
if (tip._tippy) {
tip._tippy.destroy();
}
}
}
async function setStyle(style) {
global.settings.style = style;
var result = await browser.storage.local.set({
'settings': JSON.stringify(global.settings)
});
}
async function setTheme(theme = 'dark') {
global.settings.theme = theme;
var result = await browser.storage.local.set({
'settings': JSON.stringify(global.settings)
});
}
if (this.browser) {
cryptip();
browser.runtime.onMessage.addListener(request => {
if (request.message == 'addToBlacklist') {
addToBlacklist();
return Promise.resolve({ response: "Site Added to Blacklist" })
}
if (request.message == 'removeFromBlacklist') {
removeFromBlacklist();
return Promise.resolve({ response: "Site Added to Whitelist" })
}
if (request.message == 'checkSettings') {
var result = checkSettings();
return Promise.resolve({ response: JSON.stringify(result) })
}
if (request.message == 'setWidget') {
var result = setStyle('widget');
return Promise.resolve({ response: "Style set to Widget. Refresh the page." })
}
if (request.message == 'setMinimal') {
var result = setStyle('minimal');
return Promise.resolve({ response: "Style set to Minimal. Refresh the page." })
}
if (request.message == 'setDark') {
var result = setTheme('dark');
return Promise.resolve({ response: "Theme set to Dark. Refresh the page." })
}
if (request.message == 'setLight') {
var result = setTheme('light');
return Promise.resolve({ response: "Theme set to Light. Refresh the page." })
}
return Promise.resolve({ response: "Didn't perform any action" });
});
} else {
console.log('Cryptip: Detected embedded plugin.')
cryptipEmbedded();
}