-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfollower-count.js
More file actions
1919 lines (1621 loc) · 59.9 KB
/
follower-count.js
File metadata and controls
1919 lines (1621 loc) · 59.9 KB
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: blue; icon-glyph: sort-numeric-up;
// Social Media Followers Count Widget for Scriptable by Jannis Hutt (https://hutt.io)
// GitHub Repository: https://github.com/hutt/scriptable-follower-count-widget
// ### INFO: WIDGET PARAMETERS ###
// parameters are seperated by a semicolon (";" or "; ").
// example widget parameter strings: "display:twitter", "display:twitter,instagram; instagram:aluhutt.jpg", "display:twitter; hidefollowers:true"
//
//
// OPTIONS:
// - choose social network(s) to display (optional; default: all)
// prefix: "display"
// possible values: "twitter", "mastodon", instagram", "facebook", "youtube", "all", or a combination, e.g. "twitter,instagram".
// examples: "display:twitter", "display:twitter,instagram", "display:all"
//
// - overwrite username(s) (optional; overwrites default usernames in the config section below)
// prefixes: network names ("twitter", "mastodon", "instagram", "facebook", "youtube")
// value: your username (without a leading "@")
// examples: "display:twitter; twitter:aluhutt", "mastodon:jannis@hutt.social", "display:all; mastodon:jannis@hutt.social; twitter:aluhutt"
//
// - hide "Followers" / "Subscribers" label (optional; default: set below)
// prefix: "hidelabel"
// possible values: "true", "false"
// examples: "hidelabel:true", "hidelabel" (interpreted like hidelabel:true), "hidelabel:false"
//
//
// ####### SETUP #######
// Store Cache File locally or in iCloud Drive?
const STORE_CACHE = "icloud"; // options: icloud, local
// Default usernames
// (can be overwritten by widget parameters (see above))
var twitter = "linksfraktion";
var mastodon = "linksfraktion@social.linksfraktion.de";
var instagram = "linksfraktion";
var facebook = "linksfraktion";
var youtube = "linksfraktion";
// Append "Followers" or "Subscribers" behind the number?
const HIDE_FOLLOWERS_LABEL = true;
// Hide username in the widgets?
const HIDE_USERNAME = false;
// Open social media profile when clicking widget?
const OPEN_PROFILE = true;
// Get last follower count from graph cache when there's an API error?
const ON_API_ERROR_GET_FROM_GRAPH_CACHE = true;
// In which interval do you want to query your follower count?
const CACHE_TTL = 1800; // in seconds. 3600s = 1h
// Only applys to the large widget: In what period of time should the follower growth be measured?
const FOLLOWER_GRAPH_SCALE = 12; // in hours.
// How long do you want to store data for the follower graphs
// the long the number, the bigger gets graph-cache.json
const GRAPH_CACHE_MAX = 30; // in days.
// How often do you want to check if the script needs to clean the old graph cache?
const GRAPH_CACHE_CLEANUP = 6; // in hours.
// Styling
const BACKGROUND_COLOR = Color.dynamic(
new Color("#ffffff"), // Background color for the light theme
new Color("#161618") // Background color for the dark theme
);
const TEXT_COLOR = Color.dynamic(
new Color("#333333"), // Text color for the light theme
new Color("#ffffff") // Text color for the dark theme
);
// Refresh interval for the widgets
const REFRESH_INTERVAL = 5; // in minutes
// Override locale? (affects the decimal seperator of your follower count ("," or "."))
const OVERRIDE_LOCALE = "de"; // "en" = english, "de" = german, etc. leave empty if you're fine with your thousands seperator (99% of cases).
// ####### END SETUP #######
// don't touch anything under here, unless you know what you're doing
// Constant to check available platforms
const AVAILABLE_PLATFORMS = ["twitter", "mastodon", "instagram", "facebook", "youtube"];
// Social Icons constants
const SOCIAL_ICONS_FOLDER_URL = "https://raw.githubusercontent.com/hutt/scriptable-follower-count-widget/main/icons/";
const SOCIAL_ICONS_FILENAMES = ["facebook", "facebook_white", "instagram", "instagram_white", "mastodon", "mastodon_white", "twitter", "twitter_white", "youtube", "youtube_white"];
const REQUEST_TIMEOUT = 15; // how many seconds until timeout?
// Variable to detect first run and refresh immidiately afterwards
var first_run = false;
// Set locale
var locale = Device.locale();
// only use first two characters of the locale string
locale = locale.slice(0,2);
if(OVERRIDE_LOCALE != "") {
locale = OVERRIDE_LOCALE;
}
// Create Error Object
var error = new Object();
error.status = false;
error.message = new String();
// Create hidefollowers variable out of constant
var hidefollowers_label = HIDE_FOLLOWERS_LABEL;
// PARAMETERS
// Get parameters; if none, set "display:all"
let parameters = await args.widgetParameter;
if (!parameters){
parameters = "display:all";
}
if (parameters.includes("hidelabel")) {
let regex = /hidelabel\:([\w\d]+)[\;\s]*|/gi;
let value = regex.exec(parameters);
if (value[1] == "true" || value[1] == "1" || value[2] == "hidelabel") {
hidefollowers_label = true;
}
if (value[1] == "false" || value[1] == "0") {
hidefollowers_label = false;
}
}
// HELPER FUNCTIONS
// Substract one day of a date
function subtractDays(date, days) {
date.setDate(date.getDate() - days);
return date;
}
function platformValuesAllowed(values) {
let whitelist = new Array();
for (platform of AVAILABLE_PLATFORMS) {
whitelist.push(platform);
}
let all_good = true;
for (value of values) {
if (!whitelist.includes(value)){
all_good = false;
}
}
return all_good;
}
// Get display parameter
function getDisplayParameters(parameters) {
let display_platforms = new Array();
if (parameters.includes("display:")) {
// display parameters are valid
// extract values after "display:"
let regex = /display:([\w,]+)[;\s]*/gi;
let parameter_value_string = regex.exec(parameters)[1];
display_platforms = parameter_value_string.split(",");
// if display_platforms contains "all", replace display_values with array of all available platforms
if(display_platforms.includes("all")) {
display_platforms = AVAILABLE_PLATFORMS;
}
} else {
// parameters are not valid
error.status = true;
error.message = "Widget parameters not valid. Check for keyword \"display\";";
display_platforms.push("error");
}
return display_platforms;
}
// Get username parameters
function getUsernameParameters(platform, parameters) {
let regex = new RegExp(`${platform}:([\\w\\d_.@]+)[;\\s]*`, "gi");
let parameter_string = regex.exec(parameters)[1];
return parameter_string;
}
// Download icons
async function downloadSocialIcons() {
for (img of SOCIAL_ICONS_FILENAMES) {
let img_path = fm.joinPath(icons_dir, img + ".png");
if (!fm.fileExists(img_path)) {
console.log("loading social icon: " + img + ".png");
let request = new Request(SOCIAL_ICONS_FOLDER_URL + img + ".png");
request.timeoutInterval = REQUEST_TIMEOUT;
console.log(request);
image = await request.loadImage();
fm.writeImage(img_path, image);
}
}
}
async function getImageFor(platform, version = "standard") {
let filename = platform;
if (version != "standard") {
filename = filename + "_" + version;
}
let img_path = fm.joinPath(icons_dir, filename + ".png");
await fm.downloadFileFromiCloud(img_path);
img = await fm.readImage(img_path);
return img;
}
async function writeDataToCache(data) {
data.savedDate = Date.now();
fm.writeString(path, JSON.stringify(data));
console.log("saved new data to file");
}
async function getLastGraphCacheCleanUpFromCache() {
let from_cache = await getDataFromCache();
return from_cache.lastGraphCacheCleanUp;
}
async function updateLastGraphCacheCleanUpInCache() {
let from_cache = await getDataFromCache();
from_cache.lastGraphCacheCleanUp = Date.now();
fm.writeString(path, JSON.stringify(from_cache));
console.log("updated lastGraphCacheCleanUp: " + Date.now());
}
async function writeDataToGraphCache(data) {
fm.writeString(graph_cache_path, JSON.stringify(data));
console.log("saved new data to graph cache file");
}
async function getDataFromCache() {
await fm.downloadFileFromiCloud(path);
data = await JSON.parse(fm.readString(path));
// console.log("fetching data from cache file was successful");
return data;
}
async function getDataFromGraphCache() {
await fm.downloadFileFromiCloud(graph_cache_path);
data = await JSON.parse(fm.readString(graph_cache_path));
// console.log("fetching data from cache file was successful");
return data;
}
async function addToGraphCache(platform, username, followers) {
let graph_cache = await getDataFromGraphCache();
// is the platform created as an object yet?
if (typeof graph_cache[platform] == "undefined"){
// not an object. create one.
graph_cache[platform] = new Object();
}
// does the user inside the platform object exist yet?
if (typeof graph_cache[platform][username] == "undefined"){
// not an array. create one.
graph_cache[platform][username] = new Array();
}
// create new entry object
let graph_entry = new Object();
graph_entry.timestamp = Date.now();
graph_entry.followers = followers;
// check former record
if (graph_cache[platform][username].length > 0) {
// there is another entry
let former_record_position = graph_cache[platform][username].length-1;
let former_record = graph_cache[platform][username]
former_record = former_record_position[former_record_position];
// if the former record != the new record, write new entry to cache.
if (former_record != followers) {
// new value. write to cache.
graph_cache[platform][username].push(graph_entry);
}
} else {
// this is the first entry for the selected account on the selected platform. write to cache.
graph_cache[platform][username].push(graph_entry);
}
writeDataToGraphCache(graph_cache);
// log to console
let datetime = new Date(graph_entry.timestamp);
datetime_string = datetime.getHours() + ":" + datetime.getMinutes() + ":" + datetime.getSeconds();
console.log("added new entry for " + platform + " (@" + username + ") at " + datetime_string + " to graph cache");
}
async function getGraphDataFromGraphCache(platform, username) {
let data = new Array();
let graph_cache = new Object();
try {
graph_cache = await getDataFromGraphCache();
let oldest_record_timestamp = Date.now() - (FOLLOWER_GRAPH_SCALE * 60 * 60 * 1000);
// iterate through all values under platform, username
for (record of graph_cache[platform][username]) {
if (record.timestamp > oldest_record_timestamp){
// only include data in graph that's within FOLLOWER_GRAPH_SCALE
data.push(record.followers);
}
}
} catch (err) {
data.push(-1);
}
return data;
}
async function calculateFollowerGain(platform, username) {
let follower_gain = new Object();
let graph_cache = new Object();
try {
graph_cache = await getDataFromGraphCache();
// iterate through all values under platform, username and get all objects needed
let data = new Array();
for (record of graph_cache[platform][username]) {
data.push(record);
}
// check if we got enough data.
if(data.length >= 3) {
//enough data collected
// calculate timestamp of the oldest record to search for
let substract_hours = FOLLOWER_GRAPH_SCALE * 60 * 60 * 1000; // convert hours in milliseconds
let now = Date.now();
let oldest_timestamp_to_search_for = now - substract_hours;
// search for the record with the closest timestamp
let closest_record_timestamp = data.map(o => o.timestamp).reduce(function(prev, curr) {
return (Math.abs(curr - oldest_timestamp_to_search_for) < Math.abs(prev - oldest_timestamp_to_search_for) ? curr : prev);
});
// get the requested record
let record = data.find(item => item.timestamp === closest_record_timestamp);
// if more than 30min difference to FOLLOWER_GRAPH_SCALE, calculate actual period of time elapsed
let oldest = oldest_timestamp_to_search_for - (30 * 60 * 1000);
let newest = oldest_timestamp_to_search_for + (30 * 60 * 1000);
// show actual graph scale, if record's timestamp is too far from the requested one
if (record.timestamp < oldest || record.timestamp > newest) {
// more than 30min difference between record's timestamp and actual timestamp we searched for
let actual_difference = ((now - record.timestamp) / (1000 * 60 * 60)).toFixed(1);
follower_gain.elapsedTime = actual_difference + " hours";
} else {
// actual record's timestamp within 30min window
follower_gain.elapsedTime = FOLLOWER_GRAPH_SCALE + " hours";
}
// calculate follower difference
let newest_record = data[(data.length - 1)];
let followers_difference = newest_record.followers - record.followers;
follower_gain.followers = followers_difference.toString();
// Format String
if (followers_difference >= 0) {
follower_gain.followers = "Gained " + followers_difference;
}
if (followers_difference < 0) {
follower_gain.followers = "Lost " + followers_difference;
}
} else {
// not enough data. show info text in widget by returning null.
console.error("calculateFollowerGain(): not enough data; " + err);
follower_gain.followers = null;
}
} catch (err) {
// could not find .platform.username object array yet. show info text in widget by returning null.
console.error("calculateFollowerGain(): could not find .platform.username object array; " + err);
follower_gain.followers = null;
}
// test values
//follower_gain.followers = "+25";
//follower_gain.elapsedTime = "6 hours";
return follower_gain;
}
async function getFollowersFromGraphCache(platform, username) {
let followers = -1;
if (ON_API_ERROR_GET_FROM_GRAPH_CACHE & !first_run) {
let data = await getDataFromGraphCache();
// check if platform object exists
if (typeof data[platform] != "undefined"){
// check if data is available
if (typeof data[platform][username] != "undefined"){
// data found in graph cache.
let last_value = data[platform][username].pop();
followers = last_value.followers;
}
}
}
return followers;
}
async function cleanUpGraphCache() {
let graph_cache = await getDataFromGraphCache();
let num_checked_records = 0;
let num_cleaned_up_elements = 0;
let now = new Date();
let last_acceptable_timestamp = subtractDays(now, GRAPH_CACHE_MAX);
let yesterday_timestamp = subtractDays(now, 1);
// iterate through platforms
for (let i = 0; i < graph_cache.length-1; i++) {
// iterate through accounts
for (let j = 0; j < graph_cache[i].length-1; j++) {
// iterate through data
for (let k = 0; k < graph_cache[i][j].length-1; k++) {
let data = graph_cache[i][j][k];
let search_for_other_records = true;
// delete records older than last_acceptable_timestamp
if (data.timestamp < last_acceptable_timestamp) {
// delete this record
graph_cache[i][j].splice(i,1);
// increase counter of deleted records
num_cleaned_up_elements++;
// disable search for other records on the same day since this record has to be deleted anyways since it's too old.
search_for_other_records = false;
}
// keep only one record if it's older than 24h
if (data.timestamp < yesterday_timestamp && search_for_other_records) {
// look if there is another record from that day
// define range to search for
let start_of_day = new Date(data.timestamp);
start_of_day.setUTCHours(0,0,0,0);
let end_of_day = new Date();
end_of_day.setUTCHours(23,59,59,999);
// iterate through all records of that account and search for another one
let another_record_found = false;
for (record of graph_cache[i][j]) {
if (record.timestamp > start_of_day && record.timestamp < end_of_day) {
another_record_found = true;
}
}
if (another_record_found) {
// another record on that day has been found. delete this one.
graph_cache[i][j].splice(i,1);
// incerease counter of deleted records
num_cleaned_up_elements++;
}
}
// increase the counter of checked elements
num_checked_records++;
}
}
}
// write cleaned up cache file to cache
writeDataToGraphCache(graph_cache);
// log
console.log("cleanUpGraphCache(): " + num_checked_records + " Records have been checked. " + num_cleaned_up_elements + " have been deleted.");
}
function configFileFirstInit() {
// define timestamp that forces script to reload data in the next step
let outdated_timestamp = Date.now() - ((CACHE_TTL-1) * 1000);
// define object variable to be written later on
let data = new Object();
data.cached = [];
data.lastGraphCacheCleanUp = Date.now();
// write twitter username to cache (if set)
if (twitter) {
data.cached.push ({
timestamp: outdated_timestamp,
platform: "twitter",
username: twitter,
followers: -2
});
}
// write mastodon username to cache (if set)
if (mastodon) {
data.cached.push({
timestamp: outdated_timestamp,
platform: "mastodon",
username: mastodon,
followers: -2
});
}
// write instagram username to cache (if set)
if (instagram) {
data.cached.push({
timestamp: outdated_timestamp,
platform: "instagram",
username: instagram,
followers: -2
});
}
// write facebook username to cache (if set)
if (facebook) {
data.cached.push({
timestamp: outdated_timestamp,
platform: "facebook",
username: facebook,
followers: -2
});
}
// write youtube username to cache (if set)
if (youtube) {
data.cached.push({
timestamp: outdated_timestamp,
platform: "youtube",
username: youtube,
followers: -2
});
}
first_run = true;
// write first data to cache (followers = -1)
writeDataToCache(data);
//build graph cache file
let graph_entry = new Object();
writeDataToGraphCache(graph_entry);
}
// get username
function getUsername(platform) {
let username = "";
switch (platform){
case "twitter":
username = twitter;
break;
case "mastodon":
username = mastodon;
break;
case "instagram":
username = instagram;
break;
case "facebook":
username = facebook;
break;
case "youtube":
username = youtube;
break;
}
return username;
}
// overwrite username parameter
function setUsername(platform, name) {
switch (platform) {
case "twitter":
twitter = name;
break;
case "mastodon":
mastodon = name;
break;
case "instagram":
instagram = name;
break;
case "facebook":
facebook = name;
break;
case "youtube":
youtube = name;
break;
}
}
function getMastodonUsernameWithoutInstanceUrl(username){
let regex = /^([\w]+)\@([\w\.]+)$/gi;
username = regex.exec(username)[1];
return username;
}
function getMastodonInstanceUrl(username){
let regex = /^([\w]+)\@([\w\.]+)$/gi;
let instance_url = regex.exec(username)[2];
return instance_url;
}
// get profile url
function getProfileUrl(platform) {
let url = "https://";
let username = getUsername(platform);
switch (platform){
case "twitter":
url += "twitter.com";
break;
case "mastodon":
url += getMastodonInstanceUrl(username);
username = "@" + getMastodonUsernameWithoutInstanceUrl(username);
break;
case "instagram":
url += "instagram.com";
break;
case "facebook":
url += "facebook.com";
break;
case "youtube":
url += "youtube.com";
username = "@" + username;
break;
}
url += "/" + username;
return url;
}
// social media username parameters
let platforms = AVAILABLE_PLATFORMS;
for (let i = platforms.length - 1; i >= 0; i--) {
// if social network name is found in parameter string, overwrite username variable with matched username string
if (parameters.includes(platforms[i] + ":")) {
let newusername = getUsernameParameters(platforms[i], parameters);
setUsername(platforms[i], newusername);
console.log(platforms[i] + " username overwritten: " + newusername);
}
}
// helper function to create background gradient
function createLinearGradient(colors) {
let gradient = new LinearGradient();
let num_locations = colors.length;
let locations_array = [];
let colors_array = [];
for (let i = 0; i < num_locations - 1; i++) {
let color_location = i * (1 / (num_locations - 1));
color_location = color_location.toFixed(6);
locations_array.push(parseFloat(color_location));
let color = new Color(colors[i]);
colors_array.push(color);
}
gradient.locations = locations_array;
gradient.colors = colors_array;
return gradient;
}
function getFollowersName(platform) {
let followers_name = "followers";
switch (platform) {
case "twitter":
followers_name = "followers";
break;
case "mastodon":
followers_name = "followers";
break;
case "instagram":
followers_name = "followers";
break;
case "facebook":
followers_name = "page likes";
break;
case "youtube":
followers_name = "subscribers";
break;
}
return followers_name;
}
// helper function to display long usernames correctly
function dynamicUsernameDisplay(text) {
// if it's a mastodon username, split at @
if (text.includes("@") && text.length > 20) {
let textArray = text.split("@");
text = textArray[0] + "\n@" + textArray[1];
} else {
//it's not a mastodon username.
}
return text;
}
// LOAD functions
// Load Twitter Followers
async function loadTwitterFollowers(user) {
// get random nitter instance
// for this, we'll be using https://twiiit.com. They're monitoring all the instances listed in the wiki and redirect to a working one.
// requesting data
let url = "https://twiiit.com/";
url += user;
let request = new Request(url);
request.headers = {
"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1",
};
request.timeoutInterval = REQUEST_TIMEOUT;
let wv = new WebView();
await wv.loadRequest(request);
let html = await wv.getHTML();
let regex = /\<span\sclass\=\"profile\-stat\-num\"\>([\d\.\,]+)\<\/span\>/gi;
let followers = 0;
// check data that'll be returned by regex
if (!regex.test(html)) {
// followers count couldn't be extracted
followers = -1;
console.error("Nitter API: " + request.response.url + ") threw an API Error (status code " + request.response.statusCode + ").");
} else {
// get fourth regex match (Followers)
for (let i = 0; i < 2; i++) {
followers = regex.exec(html)[1];
}
followers = followers.replace(/\,|\./g, "");
followers = parseInt(followers);
}
return followers;
}
// Load Mastodon Followers
async function loadMastodonFollowers(user) {
// requesting data
// building request url
let url = "https://";
url += getMastodonInstanceUrl(user);
url += "/api/v1/accounts/lookup?acct=";
url += getMastodonUsernameWithoutInstanceUrl(user);
let followers = -1;
let request = new Request(url);
request.timeoutInterval = REQUEST_TIMEOUT;
try {
let data = await request.loadJSON();
followers = data.followers_count;
} catch (err) {
followers = -1;
console.error("Mastodon API Error (" + getMastodonInstanceUrl(user) + "): " + err);
}
return followers;
}
// Load Instagram Followers
async function loadInstagramFollowers(user) {
// requesting data
// building request url
let url = "https://www.instagram.com/";
url += encodeURI(user);
url += "/?__a=1&__d=dis";
let request = new Request(url);
request.headers = {
"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1",
};
request.timeoutInterval = REQUEST_TIMEOUT;
let data = await request.loadJSON();
let followers = -1;
if (data.status == "fail") {
console.error("Instagram API: " + data.message);
} else {
followers = data.graphql.user.edge_followed_by.count;
}
return followers;
}
// Load Facebook Likes
async function loadFacebookLikes(user) {
// requesting data
let url = "https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2F";
url += encodeURI(user);
//url += "&tabs=info&width=340&height=130&small_header=false&adapt_container_width=false&hide_cover=true&show_facepile=false&appId";
url += "&amp;tabs=info&amp;width=340&amp;height=130&amp;small_header=false&amp;adapt_container_width=false&amp;hide_cover=true&amp;show_facepile=false&amp;appId&amp;_fb_noscript=1";
let request = new Request(url);
request.headers = {
"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1",
};
request.timeoutInterval = REQUEST_TIMEOUT;
let wv = new WebView();
await wv.loadRequest(request);
let html = await wv.getHTML();
let regex = /\<div\sclass\=\"_1drq\"[\s\w\=\"\-\:\;]*\>([\d\,\.]+)/gi;
let likes = -1;
likes = regex.exec(html)[1];
likes = likes.replace(/\,|\./g, "");
likes = parseInt(likes);
return likes;
}
// Load YouTube Subscribers
async function loadYouTubeSubscribers(user) {
// 1. get list of running invidious instances
let instance_api_url = "https://api.invidious.io/instances.json?pretty=1&sort_by=health,api,users";
let request = new Request(instance_api_url);
request.timeoutInterval = REQUEST_TIMEOUT;
let data = await request.loadJSON();
// 2. select random, sufficiently healthy instance
let random_int = Math.floor(Math.random()*7); // random integer between 0-7
let selected_instance_domain = data[random_int][0];
let api_url = "https://" + selected_instance_domain;
// 3. search for channels with that username
let request_cid_url = api_url + "/api/v1/search?type=channel&q=" + encodeURI(user) + "&fields=authorId";
let subscribers = -1;
request = new Request(request_cid_url);
request.timeoutInterval = REQUEST_TIMEOUT;
data = await request.loadJSON();
let move_on = true;
// check if api is working
if (typeof data[0] != "object") {
move_on = false;
}
if (move_on) {
let cid = data[0].authorId;
// 4. get subscription count from instance api
let request_subscribers_url = api_url + "/api/v1/channels/" + cid + "?fields=subCount";
request = new Request(request_subscribers_url);
request.timeoutInterval = REQUEST_TIMEOUT;
data = await request.loadJSON();
if (typeof data != "undefined"){
subscribers = data.subCount;
}
}
return subscribers;
}
// Get requested data for a specific platform.
async function getData(platform) {
let data = 0;
var username = null;
// Followers name and username?
let followers_name = "Followers";
switch (platform) {
case "twitter":
username = twitter;
followers_name = getFollowersName(platform);
break;
case "mastodon":
username = mastodon;
followers_name = getFollowersName(platform);
break;
case "instagram":
username = instagram;
followers_name = getFollowersName(platform);
break;
case "facebook":
username = facebook;
followers_name = getFollowersName(platform);
break;
case "youtube":
username = youtube;
followers_name = getFollowersName(platform);
break;
}
let from_cache = await getDataFromCache();
// try to get object for platform
let found_object_index = -1;
try {
found_object_index = await from_cache.cached.findIndex(item => item.platform === platform && item.username === username);
} catch(err) {
error.status = true;
error.message = err;
}
// Check if data is cached
if (found_object_index != -1){
// data is cached.
// console.log("getData(): requested " + platform + " data (@" + username + ") is cached.");
// now get timestamp
let found_object = from_cache.cached[found_object_index];
let timestamp = found_object.timestamp;
// if time stamp is too old, load data:
if (Math.floor((Date.now() - timestamp) / 1000) >= CACHE_TTL) {
// data is cached but too old. loading new data.
console.log("getData(): cached " + platform + " (@" + username + ") data too old. loading new data.");
// call right function to load followers
switch (platform) {
case "twitter":
data = await loadTwitterFollowers(twitter);
break;
case "mastodon":
data = await loadMastodonFollowers(mastodon);
break;
case "instagram":
data = await loadInstagramFollowers(instagram);
break;
case "facebook":
data = await loadFacebookLikes(facebook);
break;
case "youtube":
data = await loadYouTubeSubscribers(youtube);
break;
}
// now replace data in cache file
found_object.timestamp = Date.now();
found_object.followers = await data;
from_cache.cached[found_object_index] = found_object;
writeDataToCache(from_cache);
// add data to graph cache file, if there is no api error
if (found_object.followers >= 0) {
addToGraphCache(platform, username, found_object.followers);
}
console.log("wrote new " + platform + " followers count for @" + username + " to cache: " + data);
} else {
// time stamp was not too old.
//check if last value was an error code (< 0)
if (found_object.followers < 0) {
// last cached value contained an error. try to load again.
console.log("getData(): cached " + platform + " (@" + username + ") data could not be loaded the last time. loading new data.");
// call right function to load followers
switch (platform) {
case "twitter":
data = await loadTwitterFollowers(twitter);
break;
case "mastodon":
data = await loadMastodonFollowers(mastodon);
break;
case "instagram":
data = await loadInstagramFollowers(instagram);
break;
case "facebook":
data = await loadFacebookLikes(facebook);
break;
case "youtube":
data = await loadYouTubeSubscribers(youtube);
break;
}
// now replace data in cache file
found_object.timestamp = Date.now();
found_object.followers = await data;
from_cache.cached[found_object_index] = found_object;
writeDataToCache(from_cache);
// add data to graph cache file, if there is no api error
if (found_object.followers >= 0) {
addToGraphCache(platform, username, found_object.followers);
} else {
// api error. try to get old data from graph cache
data = await getFollowersFromGraphCache(platform, username);
console.log(platform + " api error. loaded old data from graph cache instead: " + data);
}
} else {
// everything fine with the last cached value. load from cache.
console.log("cached " + platform + " data still valid.")
data = found_object.followers;
}
}
} else {
// requested data not found in cache. loading...
console.log("getData(): requested " + platform + " (" + username + ") data is not cached.");
// call right function to load followers
switch (platform) {
case "twitter":
data = await loadTwitterFollowers(twitter);
break;
case "mastodon":
data = await loadMastodonFollowers(mastodon);