-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprofile.worker.ts
More file actions
319 lines (260 loc) · 10.6 KB
/
profile.worker.ts
File metadata and controls
319 lines (260 loc) · 10.6 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
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
import { Injectable, Logger } from '@nestjs/common';
import { Browser, BrowserContext, chromium, devices } from 'playwright';
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { InjectRepository } from '@nestjs/typeorm';
import { CharactersProfileEntity, RealmsEntity } from '@app/pg';
import { Repository } from 'typeorm';
import { HttpService } from '@nestjs/axios';
import cheerio from 'cheerio';
import {
formatWorkerLog,
formatWorkerLogWithDetails,
formatWorkerErrorLog,
formatProgressReport,
formatFinalSummary,
WorkerLogStatus,
WorkerStats,
} from '@app/logger';
import {
CHARACTER_RAID_DIFFICULTY,
OSINT_SOURCE_RAIDER_IO,
OSINT_SOURCE_WOW_PROGRESS,
OSINT_SOURCE_WCL,
CHARACTER_PROFILE_MAPPING,
WowProgressProfile,
WarcraftLogsProfile,
ICharacterRaiderIo,
isRaiderIoProfile,
CHARACTER_PROFILE_RIO_MAPPING,
RaiderIoCharacterMappingKey,
capitalize,
profileQueue,
} from '@app/resources';
import { findRealm } from '@app/resources/dao/realms.dao';
@Injectable()
@Processor(profileQueue.name, profileQueue.workerOptions)
export class ProfileWorker extends WorkerHost {
private readonly logger = new Logger(ProfileWorker.name, {
timestamp: true,
});
private stats: WorkerStats = {
total: 0,
success: 0,
errors: 0,
startTime: Date.now(),
};
private rioUpdated = 0;
private wclUpdated = 0;
private wpUpdated = 0;
browser: Browser;
browserContext: BrowserContext;
constructor(
private httpService: HttpService,
@InjectRepository(RealmsEntity)
private readonly realmsRepository: Repository<RealmsEntity>,
@InjectRepository(CharactersProfileEntity)
private readonly charactersProfileRepository: Repository<CharactersProfileEntity>,
) {
super();
}
private async browserControl() {
const isBrowserSession = Boolean(this.browser && this.browserContext);
if (!isBrowserSession) return;
await this.browserContext.close();
await this.browser.close();
}
async process(job: any): Promise<void> {
const message = job.data;
const startTime = Date.now();
this.stats.total++;
try {
const { data: args } = message;
let profileEntity = await this.charactersProfileRepository.findOneBy({
guid: args.guid,
});
if (!profileEntity) {
profileEntity = this.charactersProfileRepository.create({
guid: args.guid,
});
}
if (args.lookingForGuild) profileEntity.lfgStatus = args.lookingForGuild;
if (args.updateRIO) {
const raiderIo = await this.getRaiderIoProfile(args.name, args.realm);
Object.assign(profileEntity, raiderIo);
this.rioUpdated++;
}
if (args.updateWCL) {
const warcraftLogs = await this.getWarcraftLogsProfile(args.name, args.realm);
Object.assign(profileEntity, warcraftLogs);
this.wclUpdated++;
}
if (args.updateWP) {
const wowProgress = await this.getWowProgressProfile(args.name, args.realm);
Object.assign(profileEntity, wowProgress);
this.wpUpdated++;
}
await this.charactersProfileRepository.save(profileEntity);
this.stats.success++;
const duration = Date.now() - startTime;
const context =
`${args.updateRIO ? 'RIO' : ''}${args.updateWCL ? ' WCL' : ''}${args.updateWP ? ' WP' : ''}`.trim();
this.logger.log(
formatWorkerLog(WorkerLogStatus.SUCCESS, this.stats.total, args.guid, duration, context || undefined),
);
if (this.stats.total % 25 === 0) {
this.logProgress();
}
} catch (errorOrException) {
this.stats.errors++;
const duration = Date.now() - startTime;
this.logger.error(formatWorkerErrorLog(this.stats.total, message.data?.guid, duration, errorOrException.message));
throw errorOrException;
}
}
private logProgress(): void {
this.logger.log(formatProgressReport('ProfileWorker', this.stats, 'profiles'));
}
public logFinalSummary(): void {
this.logger.log(formatFinalSummary('ProfileWorker', this.stats, 'profiles'));
}
private async getWarcraftLogsProfile(
name: string,
realmSlug: string,
raidDifficulty: 'heroic' | 'mythic' = 'mythic',
): Promise<WarcraftLogsProfile> {
const warcraftLogsProfile = this.charactersProfileRepository.create();
const guid = `${name}@${realmSlug}`;
try {
const isBrowserLaunched = Boolean(this.browser && this.browserContext);
if (!isBrowserLaunched) {
this.browser = await chromium.launch();
this.browserContext = await this.browser.newContext(devices['iPhone 15 Pro Max landscape']);
}
const difficulty = CHARACTER_RAID_DIFFICULTY.has(raidDifficulty)
? CHARACTER_RAID_DIFFICULTY.get(raidDifficulty)
: CHARACTER_RAID_DIFFICULTY.get('mythic');
const page = await this.browserContext.newPage();
const url = encodeURI(`${OSINT_SOURCE_WCL}/${realmSlug}/${name}#difficulty=${difficulty.wclId}`);
await page.goto(url);
const getBestPerfAvg = await page.getByText('Best Perf. Avg').allInnerTexts();
const [getBestPerfAvgValue] = getBestPerfAvg;
const [_text, value] = getBestPerfAvgValue.trim().split('\n');
const isLogsNumberValid = !isNaN(Number(value.trim()));
if (isLogsNumberValid) {
warcraftLogsProfile[difficulty.fieldName] = parseFloat(value);
this.logger.log(
formatWorkerLogWithDetails(WorkerLogStatus.SUCCESS, this.stats.total, guid, 0, {
source: 'WCL',
value: difficulty.fieldName,
}),
);
} else {
this.logger.warn(
formatWorkerLog(WorkerLogStatus.WARNING, this.stats.total, guid, 0, 'WCL - No valid logs data found'),
);
}
warcraftLogsProfile.updatedByWarcraftLogs = new Date();
return warcraftLogsProfile;
} catch (errorOrException) {
this.logger.error(formatWorkerErrorLog(this.stats.total, guid, 0, errorOrException.message, 'WCL'));
return warcraftLogsProfile;
} finally {
await this.browserControl();
}
}
private async getWowProgressProfile(name: string, realmSlug: string): Promise<WowProgressProfile> {
const wowProgressProfile = this.charactersProfileRepository.create();
const guid = `${name}@${realmSlug}`;
try {
const { data } = await this.httpService.axiosRef.get<string>(
encodeURI(`${OSINT_SOURCE_WOW_PROGRESS}/${realmSlug}/${name}`),
);
if (!data) {
this.logger.warn(formatWorkerLog(WorkerLogStatus.WARNING, this.stats.total, guid, 0, 'WP - No data received'));
return wowProgressProfile;
}
const wowProgressProfilePage = cheerio.load(data);
const wpHTML = wowProgressProfilePage.html('.language');
await Promise.allSettled(
wowProgressProfilePage(wpHTML).map((_index, node) => {
const characterText = wowProgressProfilePage(node).text();
const [key, stringValue] = characterText.split(':');
const isKeyExists = CHARACTER_PROFILE_MAPPING.has(key);
if (!isKeyExists) return;
const value = stringValue.trim();
const fieldValueName = CHARACTER_PROFILE_MAPPING.get(key);
if (fieldValueName === 'readyToTransfer')
wowProgressProfile.readyToTransfer = value.includes('ready to transfer');
if (fieldValueName === 'raidDays' && value) {
const [from, to] = value.split(' - ');
const daysFrom = parseInt(from);
const daysTo = parseInt(to);
const isNumber = typeof daysFrom === 'number' && typeof daysTo === 'number';
if (isNumber) wowProgressProfile.raidDays = [daysFrom, daysTo];
}
if (fieldValueName === 'languages') {
wowProgressProfile.languages = value.split(',').map((s) => s.toLowerCase().trim());
}
if (fieldValueName === 'battleTag' || fieldValueName === 'playRole') {
wowProgressProfile[fieldValueName] = value;
}
}),
);
wowProgressProfile.updatedByWowProgress = new Date();
const hasData =
wowProgressProfile.battleTag || wowProgressProfile.playRole || wowProgressProfile.languages?.length > 0;
if (hasData) {
this.logger.log(formatWorkerLog(WorkerLogStatus.SUCCESS, this.stats.total, guid, 0, 'WP - Profile updated'));
} else {
this.logger.warn(
formatWorkerLog(WorkerLogStatus.WARNING, this.stats.total, guid, 0, 'WP - No profile data found'),
);
}
return wowProgressProfile;
} catch (errorOrException) {
this.logger.error(formatWorkerErrorLog(this.stats.total, guid, 0, errorOrException.message, 'WP'));
return wowProgressProfile;
}
}
private async getRaiderIoProfile(name: string, realmSlug: string) {
const rioProfileCharacter = this.charactersProfileRepository.create();
const guid = `${name}@${realmSlug}`;
try {
const { data: raiderIoProfile } = await this.httpService.axiosRef.get<ICharacterRaiderIo>(
encodeURI(
`${OSINT_SOURCE_RAIDER_IO}?region=eu&realm=${realmSlug}&name=${name}` +
`&fields=mythic_plus_scores_by_season:current,raid_progression`,
),
);
const isRaiderIoProfileValid = isRaiderIoProfile(raiderIoProfile);
if (!isRaiderIoProfileValid) {
this.logger.warn(
formatWorkerLog(WorkerLogStatus.WARNING, this.stats.total, guid, 0, 'RIO - Invalid profile data'),
);
return rioProfileCharacter;
}
Object.entries(raiderIoProfile).forEach(([key, value]) => {
const isKeyInProfile = CHARACTER_PROFILE_RIO_MAPPING.has(<RaiderIoCharacterMappingKey>key);
if (!isKeyInProfile) return;
const fieldProfile = CHARACTER_PROFILE_RIO_MAPPING.get(<RaiderIoCharacterMappingKey>key);
rioProfileCharacter[fieldProfile] = fieldProfile === 'gender' ? capitalize(value) : value;
});
const realmEntity = await findRealm(this.realmsRepository, raiderIoProfile.realm);
if (realmEntity) rioProfileCharacter.realmId = realmEntity.id;
rioProfileCharacter.raidProgress = raiderIoProfile.raid_progression;
const [season] = raiderIoProfile.mythic_plus_scores_by_season;
rioProfileCharacter.raiderIoScore = season.scores.all;
rioProfileCharacter.updatedByRaiderIo = new Date();
this.logger.log(
formatWorkerLogWithDetails(WorkerLogStatus.SUCCESS, this.stats.total, guid, 0, {
source: 'RIO',
score: season.scores.all,
}),
);
return rioProfileCharacter;
} catch (errorOrException) {
this.logger.error(formatWorkerErrorLog(this.stats.total, guid, 0, errorOrException.message, 'RIO'));
return rioProfileCharacter;
}
}
}