-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEpicGames.ts
More file actions
265 lines (240 loc) · 6.74 KB
/
EpicGames.ts
File metadata and controls
265 lines (240 loc) · 6.74 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
import { EmbedBuilder, SnowflakeUtil } from 'discord.js';
import got from 'got';
import type { Logger } from 'pino';
import { KeyValue } from '../database/index.js';
import { Cron, findTextChannelByName } from '../framework/index.js';
const dateFmtOptions: Intl.DateTimeFormatOptions = {
timeZone: 'Europe/Paris',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
};
export default new Cron({
enabled: true,
name: 'EpicGames',
description:
'Vérifie toutes les demi heures si Epic Games offre un jeu (promotion gratuite) et alerte dans #jeux',
schedule: '5,35 * * * *',
async handle(context) {
const games = await getOfferedGames(context.date, context.logger);
const rawLastResults = await KeyValue.get<string[]>('Last-Cron-Epic');
const lastGames = new Set<string>(rawLastResults);
const gamesToNotify = games.filter((g) => !lastGames.has(g.id));
await KeyValue.set(
'Last-Cron-Epic',
games.map((g) => g.id),
);
const channel = findTextChannelByName(context.client.channels, 'jeux');
for (const game of gamesToNotify) {
context.logger.info(`Found a new offered game (${game.title})`);
const message = new EmbedBuilder({ title: game.title, url: game.link });
if (game.thumbnail) message.setThumbnail(game.thumbnail);
if (game.banner) message.setImage(game.banner);
await channel.send({
embeds: [
message
.setDescription(game.description)
.addFields(
{
name: 'Début',
value: game.discountStartDate.toLocaleDateString(
'fr-FR',
dateFmtOptions,
),
inline: true,
},
{
name: 'Fin',
value: game.discountEndDate.toLocaleDateString(
'fr-FR',
dateFmtOptions,
),
inline: true,
},
{ name: 'Prix', value: `${game.originalPrice} → **Gratuit**` },
)
.setTimestamp(),
],
enforceNonce: true,
nonce: SnowflakeUtil.generate().toString(),
});
}
},
});
/**
* Subset of the fields returned by the Epic Games GraphQL API.
*/
interface EpicGamesProducts {
data: {
Catalog: {
searchStore: {
elements: Array<{
id: string;
title: string;
description: string;
keyImages: Array<{
type: 'OfferImageWide' | 'OfferImageTall' | 'Thumbnail';
url: string;
}>;
productSlug: string;
catalogNs: {
mappings: Array<{
pageSlug: string;
pageType: 'productHome' | 'offer';
}>;
};
offerMappings: Array<{
pageSlug: string;
pageType: 'productHome' | 'offer';
}>;
urlSlug: string;
price: {
totalPrice: {
fmtPrice: {
originalPrice: string;
};
};
lineOffers: Array<{
appliedRules: Array<{
startDate: string;
endDate: string;
}>;
}>;
};
promotions?: {
promotionalOffers?: Array<{
promotionalOffers: Array<{
startDate: string;
endDate: string;
}>;
}>;
};
}>;
paging: {
total: number;
};
};
};
};
}
/**
* Game information extracted from the Epic Games GraphQL API.
*/
interface Game {
/**
* Game id.
*/
id: string;
/**
* Game title.
*/
title: string;
/**
* Game link.
*/
link: string;
/**
* Game description.
*/
description: string;
/**
* Game thumbnail.
*/
thumbnail?: string;
/**
* Game banner.
*/
banner?: string;
/**
* Game formatted original price.
*/
originalPrice: string;
/**
* Game discount start date.
*/
discountStartDate: Date;
/**
* Game discount end date.
*/
discountEndDate: Date;
}
/**
* Fetches offered games from the Epic Games GraphQL API. If there are any and they
* were offered between the previous and current cron execution, returns them.
* @param now - Current date. Comes from cron schedule.
* @param logger
*/
export async function getOfferedGames(
now: Date,
logger: Logger,
): Promise<Game[]> {
const { body } = await got<EpicGamesProducts>(
'https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions',
{
method: 'GET',
responseType: 'json',
},
);
logger.info({ data: body.data }, 'Offered games GraphQL response');
const catalog = body.data.Catalog.searchStore;
if (catalog.paging.total === 0) {
return [];
}
const nowTime = now.getTime();
// Keep only the games that were offered in the last day.
const games = (catalog.elements ?? []).filter((game) => {
const promotion =
game.promotions?.promotionalOffers?.[0]?.promotionalOffers?.[0];
if (!promotion) return false;
const [startDate, endDate] = [
new Date(promotion.startDate),
new Date(promotion.endDate),
];
return startDate.getTime() < nowTime && nowTime < endDate.getTime();
});
return games.map<Game>((game) => {
const promotion =
game.promotions?.promotionalOffers?.[0]?.promotionalOffers?.[0];
let slug =
game.productSlug ||
game.offerMappings?.find((mapping) => mapping.pageType === 'productHome')
?.pageSlug ||
game.catalogNs.mappings?.find(
(mapping) => mapping.pageType === 'productHome',
)?.pageSlug ||
(!/^[\da-f]+$/.test(game.urlSlug) && game.urlSlug) ||
'';
if (!slug) {
logger.error(game, 'No slug foundable');
}
// Sanitize the slug (e.g. sludge-life/home -> sludge-life).
const slugSlashIndex = slug.indexOf('/');
if (slugSlashIndex !== -1) {
slug = slug.slice(0, slugSlashIndex);
}
const link = slug
? `https://www.epicgames.com/store/fr/p/${slug}`
: 'https://store.epicgames.com/fr/free-games';
let thumbnail = game.keyImages.find(
(image) => image.type === 'Thumbnail',
)?.url;
thumbnail = thumbnail && encodeURI(thumbnail);
let banner = game.keyImages.find(
(image) => image.type === 'OfferImageWide',
)?.url;
banner = banner && encodeURI(banner);
return {
id: game.id,
title: game.title,
description: game.description,
link,
thumbnail,
banner,
originalPrice: game.price.totalPrice.fmtPrice.originalPrice,
discountStartDate: new Date(promotion?.startDate ?? Date.now()),
discountEndDate: new Date(promotion?.endDate ?? Date.now()),
};
});
}