-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathshop.js
297 lines (248 loc) · 10.9 KB
/
shop.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
import fs from "fs";
import { authUser, deleteUserAuth, getUser } from "./auth.js";
import {
discordTag,
fetch,
formatBundle,
formatNightMarket,
getPuuid,
isMaintenance, isSameDay,
userRegion,
riotClientHeaders,
} from "../misc/util.js";
import { addBundleData, getSkin, getSkinFromSkinUuid } from "./cache.js";
import { addStore } from "../misc/stats.js";
import config from "../misc/config.js";
import { deleteUser, saveUser } from "./accountSwitcher.js";
import { mqGetShop, useMultiqueue } from "../misc/multiqueue.js";
export const getShop = async (id, account = null) => {
if (useMultiqueue()) return await mqGetShop(id, account);
const authSuccess = await authUser(id, account);
if (!authSuccess.success) return authSuccess;
const user = getUser(id, account);
console.log(`Fetching shop for ${user.username}...`);
// https://github.com/techchrism/valorant-api-docs/blob/trunk/docs/Store/GET%20Store_GetStorefrontV2.md
const req = await fetch(`https://pd.${userRegion(user)}.a.pvp.net/store/v3/storefront/${user.puuid}`, {
method: "POST",
headers: {
"Authorization": "Bearer " + user.auth.rso,
"X-Riot-Entitlements-JWT": user.auth.ent,
...riotClientHeaders(),
},
body: JSON.stringify({})
});
console.assert(req.statusCode === 200, `Valorant skins offers code is ${req.statusCode}!`, req);
const json = JSON.parse(req.body);
if (json.httpStatus === 400 && json.errorCode === "BAD_CLAIMS") {
deleteUserAuth(user);
return { success: false }
} else if (isMaintenance(json)) return { success: false, maintenance: true };
// shop stats tracking
try {
addStore(user.puuid, json.SkinsPanelLayout.SingleItemOffers);
} catch (e) {
console.error("Error adding shop stats!");
console.error(e);
console.error(json);
}
// add to shop cache
addShopCache(user.puuid, json);
// save bundle data & prices
Promise.all(json.FeaturedBundle.Bundles.map(rawBundle => formatBundle(rawBundle))).then(async bundles => {
for (const bundle of bundles)
await addBundleData(bundle);
});
return { success: true, shop: json };
}
export const getOffers = async (id, account = null) => {
const shopCache = getShopCache(getPuuid(id, account), "offers");
if (shopCache) return { success: true, cached: true, ...shopCache.offers };
const resp = await getShop(id, account);
if (!resp.success) return resp;
return await easterEggOffers(id, account, {
success: true,
offers: resp.shop.SkinsPanelLayout.SingleItemOffers,
expires: Math.floor(Date.now() / 1000) + resp.shop.SkinsPanelLayout.SingleItemOffersRemainingDurationInSeconds,
accessory: {
offers: (resp.shop.AccessoryStore.AccessoryStoreOffers || []).map(rawAccessory => {
return {
cost: rawAccessory.Offer.Cost["85ca954a-41f2-ce94-9b45-8ca3dd39a00d"],
rewards: rawAccessory.Offer.Rewards,
contractID: rawAccessory.ContractID
}
}),
expires: Math.floor(Date.now() / 1000) + resp.shop.AccessoryStore.AccessoryStoreRemainingDurationInSeconds
}
});
}
export const getBundles = async (id, account = null) => {
const shopCache = getShopCache(getPuuid(id, account), "bundles");
if (shopCache) return { success: true, bundles: shopCache.bundles };
const resp = await getShop(id, account);
if (!resp.success) return resp;
const formatted = await Promise.all(resp.shop.FeaturedBundle.Bundles.map(rawBundle => formatBundle(rawBundle)));
return { success: true, bundles: formatted };
}
export const getNightMarket = async (id, account = null) => {
const shopCache = getShopCache(getPuuid(id, account), "night_market");
if (shopCache) return { success: true, ...shopCache.night_market };
const resp = await getShop(id, account);
if (!resp.success) return resp;
if (!resp.shop.BonusStore) return {
success: true,
offers: false
}
return { success: true, ...formatNightMarket(resp.shop.BonusStore) };
}
export const getBalance = async (id, account = null) => {
const authSuccess = await authUser(id, account);
if (!authSuccess.success) return authSuccess;
const user = getUser(id, account);
console.log(`Fetching balance for ${user.username}...`);
// https://github.com/techchrism/valorant-api-docs/blob/trunk/docs/Store/GET%20Store_GetWallet.md
const req = await fetch(`https://pd.${userRegion(user)}.a.pvp.net/store/v1/wallet/${user.puuid}`, {
headers: {
"Authorization": "Bearer " + user.auth.rso,
"X-Riot-Entitlements-JWT": user.auth.ent,
...riotClientHeaders(),
}
});
console.assert(req.statusCode === 200, `Valorant balance code is ${req.statusCode}!`, req);
const json = JSON.parse(req.body);
if (json.httpStatus === 400 && json.errorCode === "BAD_CLAIMS") {
deleteUser(id, account);
return { success: false };
} else if (isMaintenance(json)) return { success: false, maintenance: true };
return {
success: true,
vp: json.Balances["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"],
rad: json.Balances["e59aa87c-4cbf-517a-5983-6e81511be9b7"],
kc: json.Balances["85ca954a-41f2-ce94-9b45-8ca3dd39a00d"]
};
}
let nextNMTimestamp = null, nextNMTimestampUpdated = 0;
export const getNextNightMarketTimestamp = async () => {
// only fetch every 5 minutes
if (nextNMTimestampUpdated > Date.now() - 5 * 60 * 1000) return nextNMTimestamp;
// thx Mistral for maintaining this!
const req = await fetch("https://gist.githubusercontent.com/mistralwz/17bb10db4bb77df5530024bcb0385042/raw/nmdate.txt");
const [timestamp] = req.body.split("\n");
nextNMTimestamp = parseInt(timestamp);
if (isNaN(nextNMTimestamp) || nextNMTimestamp < Date.now() / 1000) nextNMTimestamp = null;
nextNMTimestampUpdated = Date.now();
return nextNMTimestamp;
}
export let NMTimestamp = null;
/** Shop cache format:
* {
* offers: {
* offers: [...],
* expires: timestamp,
* accessory: {
* offers: [{
* "cost": 4000,
* "rewards": [{
* "ItemTypeID": uuid,
* "ItemID": uuid,
* "Quantity": number
* }],
* "contractID": uuid
* },...],
* expires: timestamp
* }
* },
* bundles: [{
* uuid: uuid,
* expires: timestamp
* }, {...}],
* night_market?: {
* offers: [{
* uuid: uuid,
* realPrice: 5000,
* nmPrice: 1000,
* percent: 80
* }, {...}],
* expires: timestamp
* },
* timestamp: timestamp
* }
*/
export const getShopCache = (puuid, target = "offers", print = true) => {
if (!config.useShopCache) return null;
try {
const shopCache = JSON.parse(fs.readFileSync("data/shopCache/" + puuid + ".json", "utf8"));
let expiresTimestamp;
if (target === "offers") expiresTimestamp = shopCache[target].expires;
else if (target === "night_market") expiresTimestamp = shopCache[target] ? shopCache[target].expires : getMidnightTimestamp(shopCache.timestamp);
else if (target === "bundles") expiresTimestamp = Math.min(...shopCache.bundles.map(bundle => bundle.expires), get9PMTimetstamp(Date.now()));
else if (target === "all") expiresTimestamp = Math.min(shopCache.offers.expires, ...shopCache.bundles.map(bundle => bundle.expires), get9PMTimetstamp(Date.now()), shopCache.night_market.expires);
else console.error("Invalid target for shop cache! " + target);
if (Date.now() / 1000 > expiresTimestamp) return null;
if (print) console.log(`Fetched shop cache for user ${discordTag(puuid)}`);
if (!shopCache.offers.accessory) return null;// If there are no accessories in the cache, it returns null so that the user's shop is checked again.
return shopCache;
} catch (e) { }
return null;
}
const addShopCache = (puuid, shopJson) => {
if (!config.useShopCache) return;
const now = Date.now();
const shopCache = {
offers: {
offers: shopJson.SkinsPanelLayout.SingleItemOffers,
expires: Math.floor(now / 1000) + shopJson.SkinsPanelLayout.SingleItemOffersRemainingDurationInSeconds,
accessory: {
offers: (shopJson.AccessoryStore.AccessoryStoreOffers || []).map(rawAccessory => {
return {
cost: rawAccessory.Offer.Cost["85ca954a-41f2-ce94-9b45-8ca3dd39a00d"],
rewards: rawAccessory.Offer.Rewards,
contractID: rawAccessory.ContractID
}
}),
expires: Math.floor(now / 1000) + shopJson.AccessoryStore.AccessoryStoreRemainingDurationInSeconds
}
},
bundles: shopJson.FeaturedBundle.Bundles.map(rawBundle => {
return {
uuid: rawBundle.DataAssetID,
expires: Math.floor(now / 1000) + rawBundle.DurationRemainingInSeconds,
}
}),
night_market: formatNightMarket(shopJson.BonusStore),
timestamp: now
}
if (shopJson.BonusStore) NMTimestamp = now
if (!fs.existsSync("data/shopCache")) fs.mkdirSync("data/shopCache");
fs.writeFileSync("data/shopCache/" + puuid + ".json", JSON.stringify(shopCache, null, 2));
console.log(`Added shop cache for user ${discordTag(puuid)}`);
}
const getMidnightTimestamp = (timestamp) => {
const date = new Date(timestamp);
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 23, 59, 59, 999) / 1000;
}
const get9PMTimetstamp = (timestamp) => { // new bundles appear at 9PM UTC
const date = new Date(timestamp);
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 20, 59, 59, 999) / 1000;
}
const easterEggOffers = async (id, account, offers) => {
// shhh...
try {
const _offers = { ...offers, offers: [...offers.offers] };
const user = getUser(id, account);
const sawEasterEgg = isSameDay(user.lastSawEasterEgg, Date.now());
const isApril1st = new Date().getMonth() === 3 && new Date().getDate() === 1;
if (isApril1st && !sawEasterEgg) {
for (const [i, uuid] of Object.entries(_offers.offers)) {
const skin = await getSkin(uuid);
const defaultSkin = await getSkinFromSkinUuid(skin.defaultSkinUuid);
_offers.offers[i] = defaultSkin.uuid;
}
user.lastSawEasterEgg = Date.now();
saveUser(user);
return _offers
}
} catch (e) {
console.error(e);
}
return offers;
}