forked from Nuklon/Steam-Economy-Enhancer
-
Notifications
You must be signed in to change notification settings - Fork 16
/
code.user.js
3978 lines (3342 loc) · 162 KB
/
code.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 Steam Economy Enhancer
// @icon data:image/svg+xml,%0A%3Csvg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" clip-rule="evenodd" viewBox="0 0 267 267"%3E%3Ccircle cx="133.3" cy="133.3" r="133.3" fill="%2326566c"/%3E%3Cpath fill="%23ebebeb" fill-rule="nonzero" d="m50 133 83-83 84 83-84 84-83-84Zm83 62 62-61-62-62v123Z"/%3E%3C/svg%3E
// @namespace https://github.com/Nuklon
// @author Nuklon
// @license MIT
// @version 7.1.1
// @description 增强 Steam 库存和 Steam 市场功能
// @match *://steamcommunity.com/id/*/inventory*
// @match *://steamcommunity.com/profiles/*/inventory*
// @match *://steamcommunity.com/market*
// @match *://steamcommunity.com/tradeoffer*
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.3/jquery-ui.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/async/2.6.0/async.js
// @require https://cdnjs.cloudflare.com/ajax/libs/localforage/1.7.1/localforage.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/luxon/3.4.4/luxon.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.js
// @require https://raw.githubusercontent.com/kapetan/jquery-observe/ca67b735bb3ae8d678d1843384ebbe7c02466c61/jquery-observe.js
// @require https://raw.githubusercontent.com/rmariuzzo/checkboxes.js/91bec667e9172ceb063df1ecb7505e8ed0bae9ba/src/jquery.checkboxes.js
// @grant unsafeWindow
// @grant GM_addStyle
// @homepageURL https://keylol.com/t311996-1-1
// @homepage https://keylol.com/t311996-1-1
// @supportURL https://keylol.com/t311996-1-1
// @downloadURL https://raw.githubusercontent.com/Sneer-Cat/Steam-Economy-Enhancer/master/code.user.js
// @updateURL https://raw.githubusercontent.com/Sneer-Cat/Steam-Economy-Enhancer/master/code.user.js
// ==/UserScript==
/* disable some eslint rules until the code is cleaned up */
/* global unsafeWindow, luxon, jQuery, async, List, localforage */
/* eslint no-undef: off */
// jQuery is already added by Steam, force no conflict mode.
(function($, async) {
$.noConflict(true);
const PAGE_MARKET = 0;
const PAGE_MARKET_LISTING = 1;
const PAGE_TRADEOFFER = 2;
const PAGE_INVENTORY = 3;
const COLOR_ERROR = '#8A4243';
const COLOR_SUCCESS = '#407736';
const COLOR_PENDING = '#908F44';
const COLOR_PRICE_FAIR = '#496424';
const COLOR_PRICE_CHEAP = '#837433';
const COLOR_PRICE_EXPENSIVE = '#813030';
const COLOR_PRICE_NOT_CHECKED = '#26566c';
const ERROR_SUCCESS = null;
const ERROR_FAILED = 1;
const ERROR_DATA = 2;
const marketLists = [];
let totalNumberOfProcessedQueueItems = 0;
let totalNumberOfQueuedItems = 0;
let totalPriceWithFeesOnMarket = 0;
let totalPriceWithoutFeesOnMarket = 0;
let totalScrap = 0;
const spinnerBlock =
'<div class="spinner"><div class="rect1"></div> <div class="rect2"></div> <div class="rect3"></div> <div class="rect4"></div> <div class="rect5"></div> </div>';
let numberOfFailedRequests = 0;
const enableConsoleLog = false;
const country = typeof unsafeWindow.g_strCountryCode !== 'undefined' ? unsafeWindow.g_strCountryCode : undefined;
const isLoggedIn = typeof unsafeWindow.g_rgWalletInfo !== 'undefined' && unsafeWindow.g_rgWalletInfo != null || typeof unsafeWindow.g_bLoggedIn !== 'undefined' && unsafeWindow.g_bLoggedIn;
const currentPage = window.location.href.includes('.com/market')
? window.location.href.includes('market/listings')
? PAGE_MARKET_LISTING
: PAGE_MARKET
: window.location.href.includes('.com/tradeoffer')
? PAGE_TRADEOFFER
: PAGE_INVENTORY;
const market = new SteamMarket(
unsafeWindow.g_rgAppContextData,
getInventoryUrl(),
isLoggedIn ? unsafeWindow.g_rgWalletInfo : undefined
);
const currencyId =
isLoggedIn &&
market != null &&
market.walletInfo != null &&
market.walletInfo.wallet_currency != null
? market.walletInfo.wallet_currency
: 3;
const currencyCountry =
isLoggedIn &&
market != null &&
market.walletInfo != null &&
market.walletInfo.wallet_country != null
? market.walletInfo.wallet_country
: 'US';
const currencyCode = unsafeWindow.GetCurrencyCode(currencyId);
function SteamMarket(appContext, inventoryUrl, walletInfo) {
this.appContext = appContext;
this.inventoryUrl = inventoryUrl;
this.walletInfo = walletInfo;
this.inventoryUrlBase = inventoryUrl.replace('/inventory/json', '');
if (!this.inventoryUrlBase.endsWith('/')) {
this.inventoryUrlBase += '/';
}
}
function request(url, options, callback) {
let delayBetweenRequests = 300;
let requestStorageHash = 'see:request:last';
if (url.startsWith('https://steamcommunity.com/market/')) {
requestStorageHash = `${requestStorageHash}:steamcommunity.com/market`;
delayBetweenRequests = 1000;
}
const lastRequest = JSON.parse(getLocalStorageItem(requestStorageHash) || JSON.stringify({ time: new Date(0), limited: false }));
const timeSinceLastRequest = Date.now() - new Date(lastRequest.time).getTime();
delayBetweenRequests = lastRequest.limited ? 2.5 * 60 * 1000 : delayBetweenRequests;
if (timeSinceLastRequest < delayBetweenRequests) {
setTimeout(() => request(...arguments), delayBetweenRequests - timeSinceLastRequest);
return;
}
lastRequest.time = new Date();
lastRequest.limited = false;
setLocalStorageItem(requestStorageHash, JSON.stringify(lastRequest));
$.ajax({
url: url,
type: options.method,
data: options.data,
success: function(data, statusMessage, xhr) {
if (xhr.status === 429) {
lastRequest.limited = true;
setLocalStorageItem(requestStorageHash, JSON.stringify(lastRequest));
}
if (xhr.status >= 400) {
const error = new Error('HTTP 错误');
error.statusCode = xhr.status;
callback(error, data);
} else {
callback(null, data)
}
},
error: (xhr) => {
if (xhr.status === 429) {
lastRequest.limited = true;
setLocalStorageItem(requestStorageHash, JSON.stringify(lastRequest));
}
const error = new Error('请求失败');
error.statusCode = xhr.status;
callback(error);
},
dataType: options.responseType
});
};
function getInventoryUrl() {
if (unsafeWindow.g_strInventoryLoadURL) {
return unsafeWindow.g_strInventoryLoadURL;
}
let profileUrl = `${window.location.origin}/my/`;
if (unsafeWindow.g_strProfileURL) {
profileUrl = unsafeWindow.g_strProfileURL;
} else {
const avatar = document.querySelector('#global_actions a.user_avatar');
if (avatar) {
profileUrl = avatar.href;
}
}
return `${profileUrl.replace(/\/$/, '')}/inventory/json/`;
}
//#region Settings
const SETTING_MIN_NORMAL_PRICE = 'SETTING_MIN_NORMAL_PRICE';
const SETTING_MAX_NORMAL_PRICE = 'SETTING_MAX_NORMAL_PRICE';
const SETTING_MIN_FOIL_PRICE = 'SETTING_MIN_FOIL_PRICE';
const SETTING_MAX_FOIL_PRICE = 'SETTING_MAX_FOIL_PRICE';
const SETTING_MIN_MISC_PRICE = 'SETTING_MIN_MISC_PRICE';
const SETTING_MAX_MISC_PRICE = 'SETTING_MAX_MISC_PRICE';
const SETTING_PRICE_OFFSET = 'SETTING_PRICE_OFFSET';
const SETTING_PRICE_MIN_CHECK_PRICE = 'SETTING_PRICE_MIN_CHECK_PRICE';
const SETTING_PRICE_ALGORITHM = 'SETTING_PRICE_ALGORITHM';
const SETTING_PRICE_IGNORE_LOWEST_Q = 'SETTING_PRICE_IGNORE_LOWEST_Q';
const SETTING_PRICE_HISTORY_HOURS = 'SETTING_PRICE_HISTORY_HOURS';
const SETTING_INVENTORY_PRICE_LABELS = 'SETTING_INVENTORY_PRICE_LABELS';
const SETTING_TRADEOFFER_PRICE_LABELS = 'SETTING_TRADEOFFER_PRICE_LABELS';
const SETTING_QUICK_SELL_BUTTONS = 'SETTING_QUICK_SELL_BUTTONS';
const SETTING_LAST_CACHE = 'SETTING_LAST_CACHE';
const SETTING_RELIST_AUTOMATICALLY = 'SETTING_RELIST_AUTOMATICALLY';
const SETTING_MARKET_PAGE_COUNT = 'SETTING_MARKET_PAGE_COUNT';
const settingDefaults = {
SETTING_MIN_NORMAL_PRICE: 0.05,
SETTING_MAX_NORMAL_PRICE: 2.50,
SETTING_MIN_FOIL_PRICE: 0.15,
SETTING_MAX_FOIL_PRICE: 10,
SETTING_MIN_MISC_PRICE: 0.05,
SETTING_MAX_MISC_PRICE: 10,
SETTING_PRICE_OFFSET: 0.00,
SETTING_PRICE_MIN_CHECK_PRICE: 0.00,
SETTING_PRICE_ALGORITHM: 1,
SETTING_PRICE_IGNORE_LOWEST_Q: 1,
SETTING_PRICE_HISTORY_HOURS: 12,
SETTING_INVENTORY_PRICE_LABELS: 1,
SETTING_TRADEOFFER_PRICE_LABELS: 1,
SETTING_QUICK_SELL_BUTTONS: 1,
SETTING_LAST_CACHE: 0,
SETTING_RELIST_AUTOMATICALLY: 0,
SETTING_MARKET_PAGE_COUNT: 100
};
function getSettingWithDefault(name) {
return getLocalStorageItem(name) || (name in settingDefaults ? settingDefaults[name] : null);
}
function setSetting(name, value) {
setLocalStorageItem(name, value);
}
//#endregion
//#region Storage
const storagePersistent = localforage.createInstance({
name: 'see_persistent'
});
let storageSession;
const currentUrl = new URL(window.location.href);
const noCache = currentUrl.searchParams.get('no-cache') != null;
// This does not work the same as the 'normal' session storage because opening a new browser session/tab will clear the cache.
// For this reason, a rolling cache is used.
if (getSessionStorageItem('SESSION') == null || noCache) {
let lastCache = getSettingWithDefault(SETTING_LAST_CACHE);
if (lastCache > 5) {
lastCache = 0;
}
setSetting(SETTING_LAST_CACHE, lastCache + 1);
storageSession = localforage.createInstance({
name: `see_session_${lastCache}`
});
storageSession.clear(); // Clear any previous data.
setSessionStorageItem('SESSION', lastCache);
} else {
storageSession = localforage.createInstance({
name: `see_session_${getSessionStorageItem('SESSION')}`
});
}
function getLocalStorageItem(name) {
try {
return localStorage.getItem(name);
} catch (e) {
logConsole(`无法获取 localStorage 内容,名称:${name},原因:${e}。`);
return null;
}
}
function setLocalStorageItem(name, value) {
try {
localStorage.setItem(name, value);
return true;
} catch (e) {
logConsole(`无法设置 localStorage 内容,名称:${name},原因:${e}。`)
return false;
}
}
function getSessionStorageItem(name) {
try {
return sessionStorage.getItem(name);
} catch (e) {
logConsole(`无法获取 sessionStorage 内容,名称:${name},原因:${e}。`);
return null;
}
}
function setSessionStorageItem(name, value) {
try {
sessionStorage.setItem(name, value);
return true;
} catch (e) {
logConsole(`无法设置 sessionStorage 内容,名称:${name},原因:${e}。`)
return false;
}
}
//#endregion
//#region Price helpers
function formatPrice(valueInCents) {
return unsafeWindow.v_currencyformat(valueInCents, currencyCode, currencyCountry);
}
function getPriceInformationFromItem(item) {
const isTradingCard = getIsTradingCard(item);
const isFoilTradingCard = getIsFoilTradingCard(item);
return getPriceInformation(isTradingCard, isFoilTradingCard);
}
function getPriceInformation(isTradingCard, isFoilTradingCard) {
let maxPrice = 0;
let minPrice = 0;
if (!isTradingCard) {
maxPrice = getSettingWithDefault(SETTING_MAX_MISC_PRICE);
minPrice = getSettingWithDefault(SETTING_MIN_MISC_PRICE);
} else {
maxPrice = isFoilTradingCard
? getSettingWithDefault(SETTING_MAX_FOIL_PRICE)
: getSettingWithDefault(SETTING_MAX_NORMAL_PRICE);
minPrice = isFoilTradingCard
? getSettingWithDefault(SETTING_MIN_FOIL_PRICE)
: getSettingWithDefault(SETTING_MIN_NORMAL_PRICE);
}
maxPrice = maxPrice * 100.0;
minPrice = minPrice * 100.0;
const maxPriceBeforeFees = market.getPriceBeforeFees(maxPrice);
const minPriceBeforeFees = market.getPriceBeforeFees(minPrice);
return {
maxPrice,
minPrice,
maxPriceBeforeFees,
minPriceBeforeFees
};
}
// Calculates the average history price, before the fee.
function calculateAverageHistoryPriceBeforeFees(history) {
let highest = 0;
let total = 0;
if (history != null) {
// Highest average price in the last xx hours.
const timeAgo = Date.now() - getSettingWithDefault(SETTING_PRICE_HISTORY_HOURS) * 60 * 60 * 1000;
history.forEach((historyItem) => {
const d = new Date(historyItem[0]);
if (d.getTime() > timeAgo) {
highest += historyItem[1] * historyItem[2];
total += historyItem[2];
}
});
}
if (total == 0) {
return 0;
}
highest = Math.floor(highest / total);
return market.getPriceBeforeFees(highest);
}
// Calculates the listing price, before the fee.
function calculateListingPriceBeforeFees(histogram) {
if (typeof histogram === 'undefined' ||
histogram == null ||
histogram.lowest_sell_order == null ||
histogram.sell_order_graph == null) {
return 0;
}
let listingPrice = market.getPriceBeforeFees(histogram.lowest_sell_order);
const shouldIgnoreLowestListingOnLowQuantity = getSettingWithDefault(SETTING_PRICE_IGNORE_LOWEST_Q) == 1;
if (shouldIgnoreLowestListingOnLowQuantity && histogram.sell_order_graph.length >= 2) {
const listingPrice2ndLowest = market.getPriceBeforeFees(histogram.sell_order_graph[1][0] * 100);
if (listingPrice2ndLowest > listingPrice) {
const numberOfListingsLowest = histogram.sell_order_graph[0][1];
const numberOfListings2ndLowest = histogram.sell_order_graph[1][1];
const percentageLower = 100 * (numberOfListingsLowest / numberOfListings2ndLowest);
// The percentage should change based on the quantity (for example, 1200 listings vs 5, or 1 vs 25).
if (numberOfListings2ndLowest >= 1000 && percentageLower <= 5) {
listingPrice = listingPrice2ndLowest;
} else if (numberOfListings2ndLowest < 1000 && percentageLower <= 10) {
listingPrice = listingPrice2ndLowest;
} else if (numberOfListings2ndLowest < 100 && percentageLower <= 15) {
listingPrice = listingPrice2ndLowest;
} else if (numberOfListings2ndLowest < 50 && percentageLower <= 20) {
listingPrice = listingPrice2ndLowest;
} else if (numberOfListings2ndLowest < 25 && percentageLower <= 25) {
listingPrice = listingPrice2ndLowest;
} else if (numberOfListings2ndLowest < 10 && percentageLower <= 30) {
listingPrice = listingPrice2ndLowest;
}
}
}
return listingPrice;
}
function calculateBuyOrderPriceBeforeFees(histogram) {
if (typeof histogram === 'undefined') {
return 0;
}
return market.getPriceBeforeFees(histogram.highest_buy_order);
}
// Calculate the sell price based on the history and listings.
// applyOffset specifies whether the price offset should be applied when the listings are used to determine the price.
function calculateSellPriceBeforeFees(history, histogram, applyOffset, minPriceBeforeFees, maxPriceBeforeFees) {
const historyPrice = calculateAverageHistoryPriceBeforeFees(history);
const listingPrice = calculateListingPriceBeforeFees(histogram);
const buyPrice = calculateBuyOrderPriceBeforeFees(histogram);
const shouldUseAverage = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 1;
const shouldUseBuyOrder = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 3;
// If the highest average price is lower than the first listing, return the offset + that listing.
// Otherwise, use the highest average price instead.
let calculatedPrice = 0;
if (shouldUseBuyOrder && buyPrice !== -2) {
calculatedPrice = buyPrice;
} else if (historyPrice < listingPrice || !shouldUseAverage) {
calculatedPrice = listingPrice;
} else {
calculatedPrice = historyPrice;
}
let changedToMax = false;
// List for the maximum price if there are no listings yet.
if (calculatedPrice == 0) {
calculatedPrice = maxPriceBeforeFees;
changedToMax = true;
}
// Apply the offset to the calculated price, but only if the price wasn't changed to the max (as otherwise it's impossible to list for this price).
if (!changedToMax && applyOffset) {
calculatedPrice = calculatedPrice + getSettingWithDefault(SETTING_PRICE_OFFSET) * 100;
}
// Keep our minimum and maximum in mind.
calculatedPrice = clamp(calculatedPrice, minPriceBeforeFees, maxPriceBeforeFees);
// In case there's a buy order higher than the calculated price.
if (typeof histogram !== 'undefined' && histogram != null && histogram.highest_buy_order != null) {
const buyOrderPrice = market.getPriceBeforeFees(histogram.highest_buy_order);
if (buyOrderPrice > calculatedPrice) {
calculatedPrice = buyOrderPrice;
}
}
return calculatedPrice;
}
//#endregion
//#region Integer helpers
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getNumberOfDigits(x) {
return (Math.log10((x ^ x >> 31) - (x >> 31)) | 0) + 1;
}
function padLeftZero(str, max) {
str = str.toString();
return str.length < max ? padLeftZero(`0${str}`, max) : str;
}
function replaceNonNumbers(str) {
return str.replace(/\D/g, '');
}
//#endregion
//#region Steam Market
// Sell an item with a price in cents.
// Price is before fees.
SteamMarket.prototype.sellItem = function(item, price, callback /*err, data*/) {
const url = `${window.location.origin}/market/sellitem/`;
const options = {
method: 'POST',
data: {
sessionid: readCookie('sessionid'),
appid: item.appid,
contextid: item.contextid,
assetid: item.assetid || item.id,
amount: 1,
price: price
},
responseType: 'json'
};
request(url, options, callback);
};
// Removes an item.
// Item is the unique item id.
SteamMarket.prototype.removeListing = function(item, isBuyOrder, callback /*err, data*/) {
const url = isBuyOrder
? `${window.location.origin}/market/cancelbuyorder/`
: `${window.location.origin}/market/removelisting/${item}`;
const options = {
method: 'POST',
data: {
sessionid: readCookie('sessionid'),
...(isBuyOrder ? { buy_orderid: item } : {})
},
responseType: 'json'
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED);
return;
}
callback(ERROR_SUCCESS, data);
}
);
};
// Get the price history for an item.
//
// PriceHistory is an array of prices in the form [data, price, number sold].
// Example: [["Fri, 19 Jul 2013 01:00:00 +0000",7.30050206184,362]]
// Prices are ordered by oldest to most recent.
// Price is inclusive of fees.
SteamMarket.prototype.getPriceHistory = function(item, cache, callback) {
const shouldUseAverage = getSettingWithDefault(SETTING_PRICE_ALGORITHM) == 1;
if (!shouldUseAverage) {
// The price history is only used by the "average price" calculation
return callback(ERROR_SUCCESS, null, true);
}
try {
const market_name = getMarketHashName(item);
if (market_name == null) {
callback(ERROR_FAILED);
return;
}
const appid = item.appid;
if (cache) {
const storage_hash = `pricehistory_${appid}+${market_name}`;
storageSession.getItem(storage_hash).
then((value) => {
if (value != null) {
callback(ERROR_SUCCESS, value, true);
} else {
market.getCurrentPriceHistory(appid, market_name, callback);
}
}).
catch(() => {
market.getCurrentPriceHistory(appid, market_name, callback);
});
} else {
market.getCurrentPriceHistory(appid, market_name, callback);
}
} catch {
return callback(ERROR_FAILED);
}
};
SteamMarket.prototype.getGooValue = function(item, callback) {
try {
let appid = item.market_fee_app;
for (const action of item.owner_actions) {
if (!action.link || !action.link.startsWith('javascript:GetGooValue')) {
continue
}
let item_data = action.link.split(',');
let appid = item_data[2].trim();
let item_type = item_data[3].trim();
let border_color = item_data[4].split(' ')[0].trim();
const url = `${window.location.origin}/auction/ajaxgetgoovalueforitemtype`;
const options = {
method: 'GET',
data: {
appid: appid,
item_type: item_type,
border_color: border_color
},
responseType: 'json'
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED, data);
return;
}
callback(ERROR_SUCCESS, data);
}
);
}
} catch (e) {
return callback(ERROR_FAILED);
}
//http://steamcommunity.com/auction/ajaxgetgoovalueforitemtype/?appid=582980&item_type=18&border_color=0
// OR
//http://steamcommunity.com/my/ajaxgetgoovalue/?sessionid=xyz&appid=535690&assetid=4830605461&contextid=6
//sessionid=xyz
//appid = 535690
//assetid = 4830605461
//contextid = 6
};
// Grinds the item into gems.
SteamMarket.prototype.grindIntoGoo = function(item, callback) {
try {
const url = `${this.inventoryUrlBase}ajaxgrindintogoo/`;
const options = {
method: 'POST',
data: {
sessionid: readCookie('sessionid'),
appid: item.market_fee_app,
assetid: item.assetid,
contextid: item.contextid,
goo_value_expected: item.goo_value_expected
},
responseType: 'json'
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED, data);
return;
}
callback(ERROR_SUCCESS, data);
}
);
} catch {
return callback(ERROR_FAILED);
}
//sessionid = xyz
//appid = 535690
//assetid = 4830605461
//contextid = 6
//goo_value_expected = 10
//http://steamcommunity.com/my/ajaxgrindintogoo/
};
// Unpacks the booster pack.
SteamMarket.prototype.unpackBoosterPack = function(item, callback) {
try {
const url = `${this.inventoryUrlBase}ajaxunpackbooster/`;
const options = {
method: 'POST',
data: {
sessionid: readCookie('sessionid'),
appid: item.market_fee_app,
communityitemid: item.assetid
},
responseType: 'json'
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED, data);
return;
}
callback(ERROR_SUCCESS, data);
}
);
} catch {
return callback(ERROR_FAILED);
}
//sessionid = xyz
//appid = 535690
//communityitemid = 4830605461
//http://steamcommunity.com/my/ajaxunpackbooster/
};
// Get the current price history for an item.
SteamMarket.prototype.getCurrentPriceHistory = function(appid, market_name, callback) {
const url = `${window.location.origin}/market/pricehistory/`;
const options = {
method: 'GET',
data: {
appid: appid,
market_hash_name: market_name
},
responseType: 'json'
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED);
return;
}
if (data && (!data.success || !data.prices)) {
callback(ERROR_DATA);
return;
}
// Multiply prices so they're in pennies.
for (let i = 0; i < data.prices.length; i++) {
data.prices[i][1] *= 100;
data.prices[i][2] = parseInt(data.prices[i][2]);
}
// Store the price history in the session storage.
const storage_hash = `pricehistory_${appid}+${market_name}`;
storageSession.setItem(storage_hash, data.prices);
callback(ERROR_SUCCESS, data.prices, false);
}
);
};
// Get the item name id from a market item.
//
// This id never changes so we can store this in the persistent storage.
SteamMarket.prototype.getMarketItemNameId = function(item, callback) {
try {
const market_name = getMarketHashName(item);
if (market_name == null) {
callback(ERROR_FAILED);
return;
}
const appid = item.appid;
const storage_hash = `itemnameid_${appid}+${market_name}`;
storagePersistent.getItem(storage_hash).
then((value) => {
if (value != null) {
callback(ERROR_SUCCESS, value);
} else {
return market.getCurrentMarketItemNameId(appid, market_name, callback);
}
}).
catch(() => {
return market.getCurrentMarketItemNameId(appid, market_name, callback);
});
} catch {
return callback(ERROR_FAILED);
}
};
// Get the item name id from a market item.
SteamMarket.prototype.getCurrentMarketItemNameId = function(appid, market_name, callback) {
const url = `${window.location.origin}/market/listings/${appid}/${escapeURI(market_name)}`;
const options = { method: 'GET' };
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED);
return;
}
const matches = (/Market_LoadOrderSpread\( (\d+) \);/).exec(data || '');
if (matches == null) {
callback(ERROR_DATA);
return;
}
const item_nameid = matches[1];
// Store the item name id in the persistent storage.
const storage_hash = `itemnameid_${appid}+${market_name}`;
storagePersistent.setItem(storage_hash, item_nameid);
callback(ERROR_SUCCESS, item_nameid);
}
);
};
// Get the sales listings for this item in the market, with more information.
//
//{
//"success" : 1,
//"sell_order_table" : "<table class=\"market_commodity_orders_table\"><tr><th align=\"right\">Price<\/th><th align=\"right\">Quantity<\/th><\/tr><tr><td align=\"right\" class=\"\">0,04\u20ac<\/td><td align=\"right\">311<\/td><\/tr><tr><td align=\"right\" class=\"\">0,05\u20ac<\/td><td align=\"right\">895<\/td><\/tr><tr><td align=\"right\" class=\"\">0,06\u20ac<\/td><td align=\"right\">495<\/td><\/tr><tr><td align=\"right\" class=\"\">0,07\u20ac<\/td><td align=\"right\">174<\/td><\/tr><tr><td align=\"right\" class=\"\">0,08\u20ac<\/td><td align=\"right\">49<\/td><\/tr><tr><td align=\"right\" class=\"\">0,09\u20ac or more<\/td><td align=\"right\">41<\/td><\/tr><\/table>",
//"sell_order_summary" : "<span class=\"market_commodity_orders_header_promote\">1965<\/span> for sale starting at <span class=\"market_commodity_orders_header_promote\">0,04\u20ac<\/span>",
//"buy_order_table" : "<table class=\"market_commodity_orders_table\"><tr><th align=\"right\">Price<\/th><th align=\"right\">Quantity<\/th><\/tr><tr><td align=\"right\" class=\"\">0,03\u20ac<\/td><td align=\"right\">93<\/td><\/tr><\/table>",
//"buy_order_summary" : "<span class=\"market_commodity_orders_header_promote\">93<\/span> requests to buy at <span class=\"market_commodity_orders_header_promote\">0,03\u20ac<\/span> or lower",
//"highest_buy_order" : "3",
//"lowest_sell_order" : "4",
//"buy_order_graph" : [[0.03, 93, "93 buy orders at 0,03\u20ac or higher"]],
//"sell_order_graph" : [[0.04, 311, "311 sell orders at 0,04\u20ac or lower"], [0.05, 1206, "1,206 sell orders at 0,05\u20ac or lower"], [0.06, 1701, "1,701 sell orders at 0,06\u20ac or lower"], [0.07, 1875, "1,875 sell orders at 0,07\u20ac or lower"], [0.08, 1924, "1,924 sell orders at 0,08\u20ac or lower"], [0.09, 1934, "1,934 sell orders at 0,09\u20ac or lower"], [0.1, 1936, "1,936 sell orders at 0,10\u20ac or lower"], [0.11, 1937, "1,937 sell orders at 0,11\u20ac or lower"], [0.12, 1944, "1,944 sell orders at 0,12\u20ac or lower"], [0.14, 1945, "1,945 sell orders at 0,14\u20ac or lower"]],
//"graph_max_y" : 3000,
//"graph_min_x" : 0.03,
//"graph_max_x" : 0.14,
//"price_prefix" : "",
//"price_suffix" : "\u20ac"
//}
SteamMarket.prototype.getItemOrdersHistogram = function(item, cache, callback) {
try {
const market_name = getMarketHashName(item);
if (market_name == null) {
callback(ERROR_FAILED);
return;
}
const appid = item.appid;
if (cache) {
const storage_hash = `itemordershistogram_${appid}+${market_name}`;
storageSession.getItem(storage_hash).
then((value) => {
if (value != null) {
callback(ERROR_SUCCESS, value, true);
} else {
market.getCurrentItemOrdersHistogram(item, market_name, callback);
}
}).
catch(() => {
market.getCurrentItemOrdersHistogram(item, market_name, callback);
});
} else {
market.getCurrentItemOrdersHistogram(item, market_name, callback);
}
} catch {
return callback(ERROR_FAILED);
}
};
// Get the sales listings for this item in the market, with more information.
SteamMarket.prototype.getCurrentItemOrdersHistogram = function(item, market_name, callback) {
market.getMarketItemNameId(
item,
(error, item_nameid) => {
if (error) {
callback(ERROR_FAILED);
return;
}
const url = `${window.location.origin}/market/itemordershistogram`;
const options = {
method: 'GET',
data: {
country: country,
language: 'schinese',
currency: currencyId,
item_nameid: item_nameid,
two_factor: 0
}
};
request(
url,
options,
(error, data) => {
if (error) {
callback(ERROR_FAILED, null);
return;
}
// Store the histogram in the session storage.
const storage_hash = `itemordershistogram_${item.appid}+${market_name}`;
storageSession.setItem(storage_hash, data);
callback(ERROR_SUCCESS, data, false);
}
)
}
);
};
// Calculate the price before fees (seller price) from the buyer price
SteamMarket.prototype.getPriceBeforeFees = function(price, item) {
let publisherFee = -1;
if (item != null) {
if (item.market_fee != null) {
publisherFee = item.market_fee;
} else if (item.description != null && item.description.market_fee != null) {
publisherFee = item.description.market_fee;
}
}
if (publisherFee == -1) {
if (this.walletInfo != null) {
publisherFee = this.walletInfo['wallet_publisher_fee_percent_default'];
} else {
publisherFee = 0.10;
}
}
price = Math.round(price);
const feeInfo = CalculateFeeAmount(price, publisherFee, this.walletInfo);
return price - feeInfo.fees;
};
// Calculate the buyer price from the seller price
SteamMarket.prototype.getPriceIncludingFees = function(price, item) {
let publisherFee = -1;
if (item != null) {
if (item.market_fee != null) {
publisherFee = item.market_fee;
} else if (item.description != null && item.description.market_fee != null) {
publisherFee = item.description.market_fee;
}
}
if (publisherFee == -1) {
if (this.walletInfo != null) {
publisherFee = this.walletInfo['wallet_publisher_fee_percent_default'];
} else {
publisherFee = 0.10;
}
}
price = Math.round(price);
const feeInfo = CalculateAmountToSendForDesiredReceivedAmount(price, publisherFee, this.walletInfo);
return feeInfo.amount;
};
//#endregion
// Cannot use encodeURI / encodeURIComponent, Steam only escapes certain characters.
function escapeURI(name) {
let previousName = '';
while (previousName != name) {
previousName = name;
name = name.replace('?', '%3F').
replace('#', '%23').
replace(' ', '%09');
}
return name;
}
//#region Steam Market / Inventory helpers
function getMarketHashName(item) {
if (item == null) {
return null;
}
if (item.description != null && item.description.market_hash_name != null) {
return item.description.market_hash_name;
}
if (item.description != null && item.description.name != null) {
return item.description.name;
}
if (item.market_hash_name != null) {
return item.market_hash_name;
}