forked from Citrinate/giveawayHelper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
giveawayHelper.user.js
1772 lines (1592 loc) · 51.1 KB
/
giveawayHelper.user.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
// ==UserScript==
// @name Giveaway Helper
// @namespace https://github.com/Citrinate/giveawayHelper
// @description Enhances Steam key-related giveaways
// @author Citrinate
// @version 2.5.0
// @match *://*.chubbykeys.com/giveaway.php*
// @match *://*.dogebundle.com/index.php?page=redeem&id=*
// @match *://*.dupedornot.com/giveaway.php*
// @match *://*.embloo.net/task/*
// @match *://*.getkeys.net/giveaway.php*
// @match *://*.ghame.ru/*
// @match *://*.giftybundle.com/giveaway.php*
// @match *://*.giveawayhopper.com/giveaway.php*
// @match *://*.gleam.io/*
// @match *://*.hrkgame.com/en/giveaway/get-free-game/
// @match *://*.indiegala.com/*
// @match *://*.keychampions.net/view.php?gid=*
// @match *://*.marvelousga.com/giveaway.php*
// @match *://*.marvelousga.com/raffle.php*
// @match *://*.prys.ga/giveaway/?id=*
// @match *://*.simplo.gg/index.php?giveaway=*
// @match *://*.steamfriends.info/free-steam-key/
// @match *://*.treasuregiveaways.com/*.php*
// @match *://*.whosgamingnow.net/giveaway/*
// @connect steamcommunity.com
// @connect twitter.com
// @connect twitch.tv
// @match https://syndication.twitter.com/
// @match https://player.twitch.tv/
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @updateURL https://raw.githubusercontent.com/Citrinate/giveawayHelper/master/giveawayHelper.user.js
// @downloadURL https://raw.githubusercontent.com/Citrinate/giveawayHelper/master/giveawayHelper.user.js
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js
// @run-at document-end
// ==/UserScript==
/* jshint esversion: 6 */
(function() {
/**
*
*/
var setup = (function() {
return {
/**
* Determine what to do for this page based on what's defined in the "config" variable
*
* hostname: A string
* The hostname of the site we're setting the config for. Must be the same as what's defined
* as @match in the metadata block above.
*
* helper: An object
* The class which will determine how the do/undo buttons are added to the page. Usually this will
* be set to basicHelper, which simply searches for links to Steam Groups and adds buttons for
* them at the top of the page.
*
* domMatch: An array of strings
* In some cases, we don't know what page a giveaway will be on. For example, Indiegala embeds
* giveaways on various parts of their site which they want to attract attention to. Instead we
* need to search the page for a DOM element that only appears when there is a giveaway on that
* page. If any of the elements in this array match, then the script will be run on this page.
*
* urlMatch: An array of regular expressions
* Used in conjunction with domMatch. Used for pages on the domain that we do know are relevant
* to giveaways, and we always want to run the script on. For example, the giveaway confirmation
* page on Indiegala. The regular expressions will be tested against the url of the pages, and if
* any of them match, the script will be run on this page.
*
* cache: Boolean
* For use with basicHelper. Some sites will remove links to Steam groups after the entry has
* been completed. Set this to true so that any groups we find will be saved and presented later.
*
* offset: Array of integers
* For use with basicHelper. Used to correct instances where the script's UI blocks parts of a
* site. Offsets the UI by X number of pixels in the order of [top, left, right].
* Directions that shouldn't be offset should be set to 0.
*
* requires: An object: {twitch: Boolean}
* For use with basicHelper. Some sites may have links asking you to follow a twitch channel, but
* don't verify that you've done so. In these cases there's no need to display a "follow/unfollow"
* button. For sites that do verify, set the value to true.
*
*/
run: function() {
var found = false,
config = [
{
hostname: "chubbykeys.com",
helper: basicHelper,
cache: false
},
{
hostname: "dogebundle.com",
helper: basicHelper,
cache: true,
offset: [50, 0, 0]
},
{
hostname: "dupedornot.com",
helper: basicHelper,
cache: false,
requires: {twitch: true}
},
{
hostname: "embloo.net",
helper: basicHelper,
cache: true
},
{
hostname: "getkeys.net",
helper: basicHelper,
cache: false,
requires: {twitch: true},
offset: [60, 0, 0]
},
{
hostname: "ghame.ru",
helper: basicHelper,
cache: false
},
{
hostname: "giftybundle.com",
helper: basicHelper,
cache: false
},
{
hostname: "giveawayhopper.com",
helper: basicHelper,
cache: false
},
{
hostname: "gleam.io",
helper: gleamHelper,
cache: false
},
{
hostname: "hrkgame.com",
helper: basicHelper,
cache: false
},
{
hostname: "indiegala.com",
helper: basicHelper,
domMatch: [".giveaway-header"],
urlMatch: [/givmessage/],
cache: false,
offset: [0, 260, 0]
},
{
hostname: "keychampions.net",
helper: basicHelper,
cache: true,
offset: [0, 120, 0]
},
{
hostname: "marvelousga.com",
helper: basicHelper,
cache: false,
requires: {twitch: true}
},
{
hostname: "prys.ga",
helper: basicHelper,
cache: false,
offset: [50, 0, 0]
},
{
hostname: "simplo.gg",
helper: basicHelper,
cache: true
},
{
hostname: "steamfriends.info",
helper: basicHelper,
cache: false
},
{
hostname: "treasuregiveaways.com",
helper: basicHelper,
cache: true,
offset: [50, 0, 0]
},
{
hostname: "whosgamingnow.net",
helper:
basicHelper,
cache: true
}
];
for(var i = 0; i < config.length; i++) {
var site = config[i];
if(document.location.hostname.split(".").splice(-2).join(".") == site.hostname) {
found = true;
// determine whether to run the script based on the content of the page
if(typeof site.domMatch !== "undefined" ||
typeof site.urlMatch !== "undefined"
) {
var match_found = false;
// check the DOM for matches as defined by domMatch
if(typeof site.domMatch !== "undefined") {
for(var k = 0; k < site.domMatch.length; k++) {
if($(site.domMatch[k]).length !== 0) {
match_found = true;
break;
}
}
}
// check the URL for matches as defined by urlMatch
if(typeof site.urlMatch !== "undefined") {
for(var l = 0; l < site.urlMatch.length; l++) {
var reg = new RegExp(site.urlMatch[l]);
if(reg.test(location.href)) {
match_found = true;
break;
}
}
}
if(!match_found) break;
}
giveawayHelperUI.loadUI();
site.helper.init(site.cache, site.cache_id, site.offset, site.requires);
}
}
if(!found) {
commandHub.init();
}
}
};
})();
/**
*
*/
var gleamHelper = (function() {
var gleam = null,
authentications = { steam: false, twitter: false, twitch: false };
/**
* Check to see what accounts the user has linked to gleam
*/
function checkAuthentications() {
if(gleam.contestantState.contestant.authentications) {
var authentication_data = gleam.contestantState.contestant.authentications;
for(var i = 0; i < authentication_data.length; i++) {
var current_authentication = authentication_data[i];
authentications[current_authentication.provider] = current_authentication;
}
}
}
/**
* Decide what to do for each of the entries
*/
function handleEntries() {
var entries = $(".entry-method");
for(var i = 0; i < entries.length; i++) {
var entry_element = entries[i],
entry = unsafeWindow.angular.element(entry_element).scope();
switch(entry.entry_method.entry_type) {
case "steam_join_group":
createSteamButton(entry, entry_element);
break;
case "twitter_follow":
case "twitter_retweet":
case "twitter_tweet":
case "twitter_hashtags":
createTwitterButton(entry, entry_element);
break;
case "twitchtv_follow":
createTwitchButton(entry, entry_element);
break;
default:
break;
}
}
}
/**
* Places the button onto the page
*/
function addButton(entry_element) {
return function(new_button) {
new_button.addClass("btn btn-embossed btn-info");
$(entry_element).find(">a").first().append(new_button);
};
}
/**
* Returns true when an entry has been completed
*/
function isCompleted(entry) {
return function() {
return gleam.isEntered(entry.entry_method);
};
}
/**
*
*/
function createSteamButton(entry, entry_element) {
SteamHandler.getInstance().handleEntry({
group_name: entry.entry_method.config3.toLowerCase(),
group_id: entry.entry_method.config4
},
addButton(entry_element),
false,
authentications.steam === false ? false : {
user_id: authentications.steam.uid
}
);
}
/**
*
*/
function createTwitterButton(entry, entry_element) {
// Don't do anything for a tweet entry that's already been completed
if(isCompleted(entry)() &&
(entry.entry_method.entry_type == "twitter_tweet" ||
entry.entry_method.entry_type == "twitter_hashtags")) {
return;
}
TwitterHandler.getInstance().handleEntry({
action: entry.entry_method.entry_type,
id: entry.entry_method.config1
},
addButton(entry_element),
isCompleted(entry),
false,
authentications.twitter === false ? false : {
user_id: authentications.twitter.uid,
user_handle: authentications.twitter.reference
}
);
}
/**
*
*/
function createTwitchButton(entry, entry_element) {
TwitchHandler.getInstance().handleEntry(
entry.entry_method.config1,
addButton(entry_element),
isCompleted(entry),
false,
authentications.twitchtv === false ? false : {
user_handle: authentications.twitchtv.reference
}
);
}
return {
/**
*
*/
init: function() {
GM_addStyle(`
.${giveawayHelperUI.gh_button} {
bottom: 0px;
height: 32px;
margin: auto;
padding: 6px;
position: absolute;
right: 64px;
top: 0px;
z-index: 9999999999;
}
`);
// Show exact end date when hovering over any times
$("[data-ends]").each(function() {
$(this).attr("title", new Date(parseInt($(this).attr("data-ends")) * 1000));
});
// wait for gleam to finish loading
var temp_interval = setInterval(function() {
if($(".popup-blocks-container") !== null) {
clearInterval(temp_interval);
gleam = unsafeWindow.angular.element($(".popup-blocks-container").get(0)).scope();
// wait for gleam to fully finish loading
var another_temp_interval = setInterval(function() {
if(typeof gleam.campaign.entry_count !== "undefined") {
clearInterval(another_temp_interval);
checkAuthentications();
if(!gleam.showPromotionEnded()) {
handleEntries();
}
}
}, 100);
}
}, 100);
}
};
})();
/**
*
*/
var basicHelper = (function() {
return {
/**
*
*/
init: function(do_cache, cache_id, offset, requires) {
if(typeof do_cache !== "undefined" && do_cache) {
if(typeof cache_id === "undefined") {
cache_id = document.location.hostname + document.location.pathname + document.location.search;
}
cache_id = `cache_${CryptoJS.MD5(cache_id)}`;
} else {
do_cache = false;
}
giveawayHelperUI.defaultButtonSetup(offset);
// Some sites load the giveaway data dynamically. Check every second for changes
setInterval(function() {
// Add Steam buttons
SteamHandler.getInstance().findGroups(giveawayHelperUI.addButton, true, do_cache, cache_id);
if(typeof requires !== "undefined") {
if(typeof requires.twitch !== "undefined" && requires.twitch === true) {
// Add Twitch buttons
TwitchHandler.getInstance().findChannels(
giveawayHelperUI.addButton,
true,
do_cache,
`twitch_${cache_id}`
);
}
}
}, 1000);
},
};
})();
/**
* Handles Steam group buttons
*/
var SteamHandler = (function() {
function init() {
var re_group_name = /steamcommunity\.com\/groups\/([a-zA-Z0-9\-\_]{2,32})/g,
re_group_id = /steamcommunity.com\/gid\/(([0-9]+)|\[g:[0-9]:([0-9]+)\])/g,
user_id = null,
session_id = null,
process_url = null,
active_groups = [],
button_count = 1,
ready = false;
// Get all the user data we'll need to make join/leave group requests
GM_xmlhttpRequest({
url: "https://steamcommunity.com/my/groups",
method: "GET",
onload: function(response) {
user_id = response.responseText.match(/g_steamID = \"(.+?)\";/);
session_id = response.responseText.match(/g_sessionID = \"(.+?)\";/);
process_url = response.responseText.match(/processURL = '(.+?)';/);
user_id = user_id === null ? null : user_id[1];
session_id = session_id === null ? null : session_id[1];
process_url = process_url === null ? null : process_url[1];
$(response.responseText).find("a[href^='https://steamcommunity.com/groups/']").each(function() {
var group_name = $(this).attr("href").replace("https://steamcommunity.com/groups/", "");
if(group_name.indexOf("/") == -1) {
active_groups.push(group_name.toLowerCase());
}
});
active_groups = giveawayHelperUI.removeDuplicates(active_groups);
ready = true;
}
});
/**
*
*/
function prepCreateButton(group_data, button_callback, show_name, expected_user) {
if(typeof group_data.group_id == "undefined") {
// Group ID is missing
getGroupID(group_data.group_name, function(group_id) {
group_data.group_id = group_id;
createButton(group_data, button_callback, show_name, expected_user);
});
} else if(typeof group_data.group_name == "undefined") {
// Group name is missing
getGroupName(group_data.group_id, function(group_name) {
group_data.group_name = group_name;
// Fetch a separate numeric group id that we'll need
getGroupID(group_data.group_name, function(group_id) {
group_data.group_id = group_id;
createButton(group_data, button_callback, show_name, expected_user);
});
});
} else {
createButton(group_data, button_callback, show_name, expected_user);
}
}
/**
* Create a join/leave toggle button
*/
function createButton(group_data, button_callback, show_name, expected_user) {
if(typeof expected_user !== "undefined" && !expected_user) {
// The user doesn't have a Steam account linked, do nothing
} else if(user_id === null || session_id === null || process_url === null) {
// We're not logged in
giveawayHelperUI.showError(`You must be logged into
<a href="https://steamcommunity.com/login" target="_blank">steamcommunity.com</a>`);
} else if(typeof expected_user !== "undefined" && expected_user.user_id != user_id) {
// We're logged in as the wrong user
giveawayHelperUI.showError(`You must be logged into the linked Steam account:
<a href="https://steamcommunity.com/profiles/${expected_user.user_id}" target="_blank">
https://steamcommunity.com/profiles/${expected_user.user_id}</a>`);
} else if(active_groups === null) {
// Couldn't get user's group data
giveawayHelperUI.showError("Unable to determine what Steam groups you're a member of");
} else {
// Create the button
var group_name = group_data.group_name,
group_id = group_data.group_id,
in_group = active_groups.indexOf(group_name) != -1,
button_id = "steam_button_" + button_count++,
label = in_group ?
`Leave ${show_name ? group_name : "Group"}`
: `Join ${show_name ? group_name : "Group"}`;
button_callback(
giveawayHelperUI.buildButton(button_id, label, in_group, function() {
toggleGroupStatus(button_id, group_name, group_id, show_name);
giveawayHelperUI.showButtonLoading(button_id);
})
);
}
}
/**
* Toggle group status between "joined" and "left"
*/
function toggleGroupStatus(button_id, group_name, group_id, show_name) {
var steam_community_down_error = `
The Steam Community is experiencing issues. Please handle any remaining Steam entries manually.
`;
if(active_groups.indexOf(group_name) == -1) {
joinSteamGroup(group_name, group_id, function(success) {
if(success) {
active_groups.push(group_name);
giveawayHelperUI.toggleButtonClass(button_id);
giveawayHelperUI.setButtonLabel(button_id, `Leave ${show_name ? group_name : "Group"}`);
} else {
giveawayHelperUI.showError(steam_community_down_error);
}
giveawayHelperUI.hideButtonLoading(button_id);
});
} else {
leaveSteamGroup(group_name, group_id, function(success) {
if(success) {
active_groups.splice(active_groups.indexOf(group_name), 1);
giveawayHelperUI.toggleButtonClass(button_id);
giveawayHelperUI.setButtonLabel(button_id, `Join ${show_name ? group_name : "Group"}`);
} else {
giveawayHelperUI.showError(steam_community_down_error);
}
giveawayHelperUI.hideButtonLoading(button_id);
});
}
}
/**
* Join a steam group
*/
function joinSteamGroup(group_name, group_id, callback) {
GM_xmlhttpRequest({
url: "https://steamcommunity.com/groups/" + group_name,
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: $.param({ action: "join", sessionID: session_id }),
onload: function(response) {
GM_xmlhttpRequest({
url: "https://steamcommunity.com/my/groups",
method: "GET",
onload: function(response) {
if(typeof callback == "function") {
if($(response.responseText.toLowerCase()).find(
`a[href='https://steamcommunity.com/groups/${group_name}']`).length === 0) {
// Failed to join the group, Steam Community is probably down
callback(false);
} else {
callback(true);
}
}
}
});
}
});
}
/**
* Leave a steam group
*/
function leaveSteamGroup(group_name, group_id, callback) {
GM_xmlhttpRequest({
url: process_url,
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: $.param({ sessionID: session_id, action: "leaveGroup", groupId: group_id }),
onload: function(response) {
if(typeof callback == "function") {
if($(response.responseText.toLowerCase()).find(
`a[href='https://steamcommunity.com/groups/${group_name}']`).length !== 0) {
// Failed to leave the group, Steam Community is probably down
callback(false);
} else {
callback(true);
}
}
}
});
}
/**
* Get the numeric ID for a Steam group
*/
function getGroupID(group_name, callback) {
GM_xmlhttpRequest({
url: "https://steamcommunity.com/groups/" + group_name,
method: "GET",
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
onload: function(response) {
var group_id = response.responseText.match(/joinchat\/([0-9]+)/);
group_id = group_id === null ? null : group_id[1];
callback(group_id);
}
});
}
/**
* Get the name for a Steam group given the numeric ID
*/
function getGroupName(group_id, callback) {
GM_xmlhttpRequest({
url: "https://steamcommunity.com/gid/" + group_id,
method: "GET",
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
onload: function(response) {
var group_name = response.finalUrl.match(/steamcommunity\.com\/groups\/([a-zA-Z0-9\-\_]{2,32})/);
group_name = group_name === null ? null : group_name[1];
callback(group_name.toLowerCase());
}
});
}
return {
/**
*
*/
handleEntry: function(group_data, button_callback, show_name, expected_user) {
if(ready) {
prepCreateButton(group_data, button_callback, show_name, expected_user);
} else {
// Wait for the command hub to load
var temp_interval = setInterval(function() {
if(ready) {
clearInterval(temp_interval);
prepCreateButton(group_data, button_callback, show_name, expected_user);
}
}, 100);
}
},
handled_group_names: [],
handled_group_ids: [],
/**
*
*/
findGroups: function(button_callback, show_name, do_cache, cache_id) {
var group_names = do_cache ? giveawayHelperUI.restoreCachedLinks(cache_id) : [],
group_ids = do_cache ? giveawayHelperUI.restoreCachedLinks(cache_id + "_ids") : [],
match;
// Look for any links containing steam group names
while((match = re_group_name.exec($("body").html())) !== null) {
group_names.push(match[1].toLowerCase());
}
// Look for any links containing steam group ids
while((match = re_group_id.exec($("body").html())) !== null) {
if(typeof match[2] !== "undefined") {
group_ids.push(match[2].toLowerCase());
} else {
group_ids.push(match[3].toLowerCase());
}
}
group_names = giveawayHelperUI.removeDuplicates(group_names);
group_ids = giveawayHelperUI.removeDuplicates(group_ids);
// Cache the results
if(do_cache) {
giveawayHelperUI.cacheLinks(group_names, cache_id);
giveawayHelperUI.cacheLinks(group_ids, cache_id + "_ids");
}
// Create the buttons
for(var i = 0; i < group_names.length; i++) {
if($.inArray(group_names[i], this.handled_group_names) == -1) {
this.handled_group_names.push(group_names[i]);
this.handleEntry({ group_name: group_names[i] }, button_callback, show_name);
}
}
for(var j = 0; j < group_ids.length; j++) {
if($.inArray(group_ids[i], this.handled_group_ids) == -1) {
this.handled_group_ids.push(group_ids[i]);
this.handleEntry({ group_id: group_ids[j] }, button_callback, show_name);
}
}
}
};
}
var instance;
return {
getInstance: function() {
if(!instance) instance = init();
return instance;
}
};
})();
/**
* Handles Twitter undo buttons
*/
var TwitterHandler = (function() {
function init() {
var command_hub_url = "https://syndication.twitter.com/",
command_hub_host = "syndication.twitter.com",
auth_token = null,
csrf_token = null,
user_handle = null,
user_id = null,
start_time = +new Date(),
deleted_tweets = [], // used to make sure we dont try to delete the same (re)tweet more than once
button_count = 1,
ready_a = false;
ready_b = false;
// Get all the user data we'll need to undo twitter entries
commandHub.load(
command_hub_url,
command_hub_host,
function() {
return {
csrf_token: getCookie("ct0")
};
},
function(data) {
csrf_token = data.csrf_token;
ready_a = true;
}
);
GM_xmlhttpRequest({
url: "https://twitter.com",
method: "GET",
onload: function(response) {
auth_token = $($(response.responseText)
.find("input[id='authenticity_token']").get(0))
.attr("value");
user_handle = $(response.responseText)
.find(".current-user a")
.attr("href");
user_id = $(response.responseText)
.find("#current-user-id")
.attr("value");
auth_token = typeof auth_token == "undefined" ? null : auth_token;
user_handle = typeof user_handle == "undefined" ? null : user_handle.replace("/", "");
user_id = typeof user_id == "undefined" ? null : user_id;
ready_b = true;
}
});
/**
* Get ready to create an item
*/
function prepCreateButton(action_data, button_callback, ready_check, show_name, expected_user) {
// Wait until the entry is completed before showing the button
var temp_interval = setInterval(function() {
if(ready_check()) {
clearInterval(temp_interval);
createButton(action_data, button_callback, show_name, expected_user, +new Date());
}
}, 100);
}
/**
* Create the button
*/
function createButton(action_data, button_callback, show_name, expected_user, end_time) {
if(!expected_user) {
// The user doesn't have a Twitter account linked, do nothing
} else if(auth_token === null || user_handle === null || csrf_token === null) {
// We're not logged in
giveawayHelperUI.showError(`You must be logged into
<a href="https://twitter.com/login" target="_blank">twitter.com</a>`);
} else if(expected_user.user_id != user_id) {
// We're logged in as the wrong user
giveawayHelperUI.showError(`You must be logged into the Twitter account linked to Gleam.io:
<a href="https://twitter.com/${expected_user.user_handle}" target="_blank">
https://twitter.com/${expected_user.user_handle}</a>`);
} else {
// Create the button
var button_id = "twitter_button_" + button_count++;
if(action_data.action == "twitter_follow") {
// Unfollow button
var twitter_handle = action_data.id;
button_callback(
giveawayHelperUI.buildButton(button_id, `Unfollow${show_name ? ` ${twitter_handle}` : ""}`,
false,
function() {
giveawayHelperUI.removeButton(button_id);
// Get user's Twitter ID
getTwitterUserData(twitter_handle, function(twitter_id, is_following) {
deleteTwitterFollow(twitter_handle, twitter_id);
});
})
);
} else if(action_data.action == "twitter_retweet") {
// Delete Retweet button
button_callback(
giveawayHelperUI.buildButton(button_id, "Delete Retweet", false, function() {
giveawayHelperUI.removeButton(button_id);
deleteTwitterRetweet(action_data.id.match(/\/([0-9]+)/)[1]);
})
);
} else if(action_data.action == "twitter_tweet" || action_data.action == "twitter_hashtags") {
// Delete Tweet button
button_callback(
giveawayHelperUI.buildButton(button_id, "Delete Tweet", false, function() {
giveawayHelperUI.removeButton(button_id);
/* We don't have an id for the tweet, so instead delete the first tweet we can find
that was posted after we handled the entry, but before it was marked completed. */
getTwitterTweet(end_time, function(tweet_id) {
if(tweet_id === false) {
giveawayHelperUI.showError(`Failed to find
<a href="https://twitter.com/${user_handle}" target="_blank">Tweet</a>`);
} else {
deleteTwitterTweet(tweet_id);
}
});
})
);
}
}
}
/**
* @return {String} twitter_id - Twitter id for this handle
* @return {Boolean} is_following - True for "following", false for "not following"
*/
function getTwitterUserData(twitter_handle, callback) {
GM_xmlhttpRequest({
url: "https://twitter.com/" + twitter_handle,
method: "GET",
onload: function(response) {
var twitter_id = $($(response.responseText.toLowerCase()).find(
`[data-screen-name='${twitter_handle.toLowerCase()}'][data-user-id]`).get(0)).attr(
"data-user-id"),
is_following = $($(response.responseText.toLowerCase()).find(
`[data-screen-name='${twitter_handle.toLowerCase()}'][data-you-follow]`).get(0)).attr(
"data-you-follow");
if(typeof twitter_id !== "undefined" && typeof is_following !== "undefined") {
callback(twitter_id, is_following !== "false");
} else {
callback(null, null);
}
}
});
}
/**
* We don't have an id for the tweet, so instead delete the first tweet we can find
* that was posted after we handled the entry, but before it was marked completed.
*
* @param {Number} end_time - Unix timestamp in ms
* @return {Array|Boolean} tweet_id - The oldest (re)tweet id between start and end time, false if not found
*/
function getTwitterTweet(end_time, callback) {
/* Tweets are instantly posted to our profile, but there's a delay before they're made
public (a few seconds). Increase the range by a few seconds to compensate. */
end_time += (60 * 1000);
GM_xmlhttpRequest({
url: "https://twitter.com/" + user_handle,
method: "GET",
onload: function(response) {
var found_tweet = false,
now = +new Date();
// reverse the order so that we're looking at oldest to newest
$($(response.responseText.toLowerCase()).find(
`a[href*='${user_handle.toLowerCase()}/status/']`).get().reverse()).each(function() {
var tweet_time = $(this).find("span").attr("data-time-ms"),
tweet_id = $(this).attr("href").match(/\/([0-9]+)/);
if(typeof tweet_time != "undefined" && tweet_id !== null) {
if(deleted_tweets.indexOf(tweet_id[1]) == -1 &&
tweet_time > start_time &&
(tweet_time < end_time || tweet_time > now)) {
// return the first match
found_tweet = true;
deleted_tweets.push(tweet_id[1]);
callback(tweet_id[1]);
return false;
}
}
});
// couldn't find any tweets between the two times
if(!found_tweet) {
callback(false);
}
}
});
}
/**
* Unfollow a twitter user
*/
function deleteTwitterFollow(twitter_handle, twitter_id) {
if(twitter_id === null) {
giveawayHelperUI.showError(`Failed to unfollow Twitter user:
<a href="https://twitter.com/${twitter_handle}" target="_blank">${twitter_handle}</a>`);
} else {
GM_xmlhttpRequest({
url: "https://api.twitter.com/1.1/friendships/destroy.json",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"authorization": "Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw",
"x-csrf-token": csrf_token,
},
data: $.param({ user_id: twitter_id }),
onload: function(response) {
if(response.status != 200) {
giveawayHelperUI.showError(`Failed to unfollow Twitter user:
<a href="https://twitter.com/${twitter_handle}" target="_blank">
${twitter_handle}
</a>`);
}
}
});