forked from ge-ku/AutoJoin-for-SteamGifts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackgroundpage.js
310 lines (290 loc) · 11.4 KB
/
backgroundpage.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
/*How about make a human readable script, then pass it to jsmin or closure for release?
https://developers.google.com/closure/compiler/
This script page is the background script. autoentry.js is the autojoin button and other page
modifications*/
function Giveaway(code, level, appid, odds, cost) {
this.code = code, this.level = level, this.steamlink = appid, this.odds = odds, this.cost = cost
}
function compareLevel(a, b) {
return b.level - a.level
}
function compareOdds(a, b) {
return b.odds - a.odds
}
function calculateWinChance(giveaway, timeLoaded) {
var timeLeft = parseInt( $(giveaway).find('.fa.fa-clock-o').next('span').attr('data-timestamp') ) - timeLoaded; // time left in seconds
var timePassed = timeLoaded - parseInt( $(giveaway).find('.giveaway__username').prev('span').attr('data-timestamp') ); //time passed in seconds
var numberOfEntries = parseInt( $(giveaway).find('.fa-tag').next('span').text().replace(',', '') );
var numberOfCopies = 1;
if ($(giveaway).find('.giveaway__heading__thin:first').text().replace(',', '').match(/\(\d+ Copies\)/)) { // if more than one copy there's a text field "(N Copies)"
numberOfCopies = parseInt( $(giveaway).find('.giveaway__heading__thin:first').text().replace(',', '').match(/\d+/)[0] );
}
var predictionOfEntries = (numberOfEntries / timePassed) * timeLeft; // calculate rate of entries and multiply on time left, probably not very accurate as we assume linear rate
var chance = (1 / (numberOfEntries + 1 + predictionOfEntries)) * 100 * numberOfCopies;
return chance;
}
function notify() {
chrome.notifications.clear("won_notification", function() {
var e = {
type: "basic",
title: "AutoJoin",
message: "You won! Click here to open steamgifts.com",
iconUrl: "autologosteam.png"
};
chrome.notifications.create("won_notification", e, function() {
chrome.storage.sync.get({PlayAudio: 'true'}, function (data) {
if (data.PlayAudio == 'true'){
var e = new Audio("audio.mp3");
e.play()
}
});
})
})
}
/*This function scans the pages and calls the function pagesloaded() once it finished
All giveaways that must be entered are pushed in an array called "arr"
Remember once scanpage is over, pagesloaded is called*/
function scanpage(e) {
var timeLoaded = Math.round(Date.now() / 1000);
var postsDiv = $(e).find(':not(.pinned-giveaways__inner-wrap) > .giveaway__row-outer-wrap').parent();
((settings.IgnorePinnedBG == true || (useWishlistPriorityForMainBG && pagestemp == pages)) ? postsDiv : $(e)).find(".giveaway__row-inner-wrap:not(.is-faded) .giveaway__heading__name").each(function() {
var e = $(this).parent().parent().parent(),
t = this.href.match(/giveaway\/(.+)\//);
if (t.length > 0) {
var GAcode = t[1];
if (!(settings.IgnoreGroupsBG && 0 != $(this).find(".giveaway__column--group").length || $(e).find(".giveaway__column--contributor-level--negative").length > 0)) {
if ($(e).find(".giveaway__column--contributor-level--positive").length > 0) var GAlevel = $(e).find(".giveaway__column--contributor-level--positive").html().match(/(\d+)/)[1];
else var GAlevel = 0;
var s = $(e).find(".global__image-outer-wrap--game-medium").find(".global__image-inner-wrap").css("background-image");
if (null == s) var GAsteamAppID = "0";
else {
var i = s.match(/.+apps\/(\d+)\/cap.+/);
if (null == i) var GAsteamAppID = "0";
else var GAsteamAppID = i[1]
}
var cost = $(e).find(".giveaway__heading__thin").last().html().match(/\d+/)[0];
var oddsOfWinning = calculateWinChance(e, timeLoaded);
arr.push(new Giveaway(GAcode, parseInt(GAlevel), GAsteamAppID, oddsOfWinning, parseInt(cost)));
}
}
});
if(pagestemp == pages){
totalWishlistGAcnt = arr.length;
}
pagestemp--;
if(0 == pagestemp || (currPoints < settings.PointsToPreserve && useWishlistPriorityForMainBG && settings.IgnorePreserveWishlistOnMainBG && totalWishlistGAcnt != 0)){
pagestemp = 0;
pagesloaded();
}
}
/*This function is called once all pages have been parsed
this sends the requests to steamgifts*/
function pagesloaded() {
if(useWishlistPriorityForMainBG){
wishlistArr = arr.slice(0, totalWishlistGAcnt);
if (settings.LevelPriorityBG) {
wishlistArr.sort(compareLevel);
} else if (settings.OddsPriorityBG) {
wishlistArr.sort(compareOdds);
}
arr = arr.slice(totalWishlistGAcnt);
}
if (settings.LevelPriorityBG) {
arr.sort(compareLevel);
} else if (settings.OddsPriorityBG) {
arr.sort(compareOdds);
}
if(useWishlistPriorityForMainBG){
arr = wishlistArr.concat(arr);
}
var timeouts = [];
$.each(arr, function(e) {
if (arr[e].level < settings.MinLevelBG) { // this may be unnecessary since level_min search parameter https://www.steamgifts.com/discussion/5WsxS/new-search-parameters
return true;
}
if (arr[e].cost < settings.MinCost){
return true;
}
timeouts.push(setTimeout(function(){
console.log(arr[e]), $.post("https://www.steamgifts.com/ajax.php", {
xsrf_token: token,
"do": "entry_insert",
code: arr[e].code
}, function(response){
var json_response = jQuery.parseJSON(response);
if ((json_response.points < settings.PointsToPreserve &&
((useWishlistPriorityForMainBG && settings.IgnorePreserveWishlistOnMainBG) ?
(totalWishlistGAcnt == 1 ? true : (e > totalWishlistGAcnt - 2)) : true))
|| json_response.msg == "Not Enough Points") {
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
timeouts = [];
}
/* For easier understanding of the above if check.
var clearTimeouts = function(){
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
timeouts = [];
}
if(json_response.points < settings.PointsToPreserve
&& useWishlistPriorityForMainBG && settings.IgnorePreserveWishlistOnMainBG){
if(totalWishlistGAcnt == 1){
clearTimeouts();
}else if (e > totalWishlistGAcnt - 2){
clearTimeouts();
}
} else if (json_response.msg == "Not Enough Points"){
clearTimeouts();
}*/
})
}, e * settings.DelayBG * 1000 + Math.floor(Math.random()*2001)));
});
}
/*This function checks for a won gift, then calls the scanpage function*/
/*e is the whole html page*/
function settingsloaded() {
if (settings.IgnoreGroupsBG && settings.PageForBG == "all") {
settings.IgnoreGroupsBG = true;
}
if (settings.PageForBG == "all" && settings.WishlistPriorityForMainBG){
useWishlistPriorityForMainBG = true;
} else {
useWishlistPriorityForMainBG = false;
}
pages = settings.PagesToLoadBG;
if (pages < 2 && useWishlistPriorityForMainBG) pages = 2;
timetopass = 10 * settings.RepeatHoursBG;
if (justLaunched || settings.RepeatHoursBG == 0) { // settings.RepeatHoursBG == 0 means it should autojoin every time
justLaunched = false;
timepassed = timetopass;
} else {
timepassed += 5;
}
/*If background autojoin is disabled or not enough time passed only check if won*/
if (settings.BackgroundAJ == false || timepassed < timetopass) {
$.get(link + 1, function(data){
if ( $(data).filter(".popup--gift-received").length ) {
notify();
}
//check level and save if changed
mylevel = $(data).find('a[href="/account"]').find("span").next().html().match(/(\d+)/)[1];
if (settings.LastKnownLevel != parseInt(mylevel)) {
chrome.storage.sync.set({LastKnownLevel: parseInt(mylevel, 10)});
}
});
}
/*Else check if won first (since pop-up disappears after first view), then start scanning pages*/
else {
timepassed = 0; //reset timepassed
link = "https://www.steamgifts.com/giveaways/search?type=" + settings.PageForBG + "&level_min=" + settings.MinLevelBG + "&level_max=" + settings.LastKnownLevel + "&page=";
wishLink = "https://www.steamgifts.com/giveaways/search?type=wishlist&level_min=" + settings.MinLevelBG + "&level_max=" + settings.LastKnownLevel + "&page=";
var linkToUse = "";
useWishlistPriorityForMainBG ? linkToUse = wishLink : linkToUse = link;
arr.length = 0;
$.get(linkToUse + 1, function(data) {
if ( $(data).filter(".popup--gift-received").length ) {
notify();
}
if (pages > 5 || pages < 1) { pagestemp = 3 } else { pagestemp = pages } // in case someone has old setting with more than 5 pages to load or somehow set this value to <1 use 3 (default)
token = $(data).find("input[name=xsrf_token]").val();
mylevel = $(data).find('a[href="/account"]').find("span").next().html().match(/(\d+)/)[1];
//save new level if it changed
if (settings.LastKnownLevel != parseInt(mylevel)) {
chrome.storage.sync.set({LastKnownLevel: parseInt(mylevel)});
}
currPoints = parseInt($(data).find('a[href="/account"]').find("span.nav__points").text(), 10);
console.log('Current Points: ' + currPoints);
//var numOfGAsOnPage = parseInt($(data).find('.pagination__results').children().next().text(), 10);
if(currPoints >= settings.PointsToPreserve || (useWishlistPriorityForMainBG && settings.IgnorePreserveWishlistOnMainBG)){
scanpage(data); // scan this page that was already loaded to get info above
var i = 0;
if(useWishlistPriorityForMainBG){
linkToUse = link;
i = 1;
}
if(currPoints >= settings.PointsToPreserve){
for (var n = 2 - i; n <= pages - i; n++) { // scan next pages
if (n > 3 - i) break; // no more than 3 pages at a time since the ban wave
$.get(linkToUse + n, function(newPage) {
scanpage(newPage)
})
}
}
}
});
}
}
/*Load settings, then call settingsloaded()*/
function loadsettings() {
chrome.storage.sync.get({
PageForBG: 'wishlist',
RepeatHoursBG: 2,
DelayBG: 10,
MinLevelBG: 0,
MinCost: 0,
PointsToPreserve: 0,
WishlistPriorityForMainBG: false,
IgnorePreserveWishlistOnMainBG: false,
PagesToLoadBG: 3,
BackgroundAJ: true,
LevelPriorityBG: true,
OddsPriorityBG: false,
IgnoreGroupsBG: false,
IgnorePinnedBG: false,
LastKnownLevel: 10, // set to 10 by default so it loads pages with max_level set to 10 (maximum) before extensions learns actual level
lastLaunchedVersion: thisVersion
}, function(data) {
settings = data;
settingsloaded();
}
);
}
/*Function declarations over*/
/*It all begins with the loadsettings call*/
chrome.alarms.onAlarm.addListener(function(alarm) {
console.log("Alarm fired.")
if (alarm.name == "routine") {
loadsettings();
chrome.alarms.create("routine", {
delayInMinutes: 30
});
}
});
/*Variables declaration*/
var arr = [],
settings,
link = "https://www.steamgifts.com/giveaways/search?page=",
pages = 1,
pagestemp = pages,
token = "",
mylevel = 0,
varcount = 0,
timepassed = 0,
timetopass = 20,
justLaunched = true,
thisVersion = 20170225,
totalWishlistGAcnt = 0,
useWishlistPriorityForMainBG = false,
currPoints = 0;
/*Create first alarm as soon as possible*/
chrome.alarms.create("routine", {
delayInMinutes: .1
});
/*Creating a new tab if notification is clicked*/
chrome.notifications.onClicked.addListener(function() {
chrome.windows.getCurrent(function(currentWindow) {
if (currentWindow != null) {
return chrome.tabs.create({
url: "https://www.steamgifts.com/giveaways/won"
});
} else {
return chrome.windows.create({
url: "https://www.steamgifts.com/giveaways/won",
type: "normal",
focused: true
});
}
})
});