-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathchallenges.js
732 lines (675 loc) · 22.7 KB
/
challenges.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
/**
* @module "services.challenges"
* @desc This module provides a service for convenient manipulation with
* Topcoder challenges via TC API.
*/
import _ from 'lodash';
import moment from 'moment';
import qs from 'qs';
import { decodeToken } from 'tc-accounts';
import logger from '../utils/logger';
import { setErrorIcon, ERROR_ICON_TYPES } from '../utils/errors';
import { COMPETITION_TRACKS, getApiResponsePayload } from '../utils/tc';
import { getApi } from './api';
import { getService as getMembersService } from './members';
import { getService as getSubmissionsService } from './submissions';
export const ORDER_BY = {
SUBMISSION_END_DATE: 'submissionEndDate',
};
/**
* Normalizes a regular challenge object received from the backend.
* NOTE: This function is copied from the existing code in the challenge listing
* component. It is possible, that this normalization is not necessary after we
* have moved to Topcoder API, but it is kept for now to minimize a risk of
* breaking anything.
* @todo Should be used only internally!
* @param {Object} challenge Challenge object received from the backend.
* @param {String} username Optional.
*/
export function normalizeChallenge(challenge, username) {
const phases = challenge.allPhases || challenge.phases || [];
const registration = phases.filter(d => d.name === 'Registration')[0];
let registrationOpen = 'No';
let registrationStartDate;
let registrationEndDate;
if (registration) {
registrationStartDate = registration.actualStartDate || registration.scheduledStartDate;
if (registration.isOpen) {
registrationOpen = 'Yes';
}
registrationEndDate = registration.actualEndDate || registration.scheduledEndDate;
}
const groups = {};
if (challenge.groups) {
challenge.groups.forEach((id) => {
groups[id] = true;
});
}
/* eslint-disable no-param-reassign */
if (!challenge.prizeSets) challenge.prizeSets = [];
if (!challenge.tags) challenge.tags = [];
if (!challenge.platforms) challenge.platforms = [];
let submissionEndTimestamp = phases.filter(d => d.name === 'Submission')[0];
if (submissionEndTimestamp) {
submissionEndTimestamp = submissionEndTimestamp.scheduledEndDate;
}
const prizes = (challenge.prizeSets[0] && challenge.prizeSets[0].prizes) || [];
_.defaults(challenge, {
communities: new Set([COMPETITION_TRACKS[challenge.track]]),
groups,
registrationOpen,
submissionEndTimestamp,
registrationStartDate,
registrationEndDate,
totalPrize: prizes.reduce((acc, prize) => acc + prize.value, 0),
submissionEndDate: submissionEndTimestamp,
users: username ? { [username]: true } : {},
});
}
/**
* Helper method that checks for HTTP error response and throws Error in this case.
* @param {Object} res HTTP response object
* @return {Object} API JSON response object
* @private
*/
async function checkError(res) {
if (!res.ok) {
if (res.status >= 500) {
setErrorIcon(ERROR_ICON_TYPES.API, '/challenges', res.statusText);
}
throw new Error(res.statusText);
}
const jsonRes = (await res.json()).result;
if (jsonRes.status !== 200) throw new Error(jsonRes.content);
return jsonRes;
}
/**
* Helper method that checks for HTTP error response v5 and throws Error in this case.
* @param {Object} res HTTP response object
* @return {Object} API JSON response object
* @private
*/
async function checkErrorV5(res) {
if (!res.ok) {
if (res.status >= 500) {
setErrorIcon(ERROR_ICON_TYPES.API, '/challenges', res.statusText);
}
throw new Error(res.statusText);
}
const jsonRes = (await res.json());
if (jsonRes.message) {
throw new Error(res.message);
}
return {
result: jsonRes,
headers: res.headers,
};
}
/**
* Challenge service.
*/
class ChallengesService {
/**
* Creates a new ChallengeService instance.
* @param {String} tokenV3 Optional. Auth token for Topcoder API v3.
* @param {String} tokenV2 Optional. Auth token for Topcoder API v2.
*/
constructor(tokenV3, tokenV2) {
/**
* Private function being re-used in all methods related to getting
* challenges. It handles query-related arguments in the uniform way:
* @param {String} endpoint API endpoint, where the request will be send.
* @param {Object} filters Optional. A map of filters to pass as `filter`
* query parameter (this function takes care to stringify it properly).
* @param {Object} params Optional. A map of any other parameters beside
* `filter`.
*/
const getChallenges = async (
endpoint,
filters = {},
params = {},
) => {
const query = {
...filters,
...params,
};
const url = `${endpoint}?${qs.stringify(query)}`;
const res = await this.private.apiV5.get(url).then(checkErrorV5);
return {
challenges: res.result || [],
totalCount: res.headers.get('x-total'),
meta: {
allChallengesCount: res.headers.get('x-total'),
myChallengesCount: 0,
ongoingChallengesCount: 0,
openChallengesCount: 0,
totalCount: res.headers.get('x-total'),
},
};
};
/**
* Private function being re-used in all methods related to getting
* challenges. It handles query-related arguments in the uniform way:
* @param {String} endpoint API endpoint, where the request will be send.
* @param {Object} filters Optional. A map of filters to pass as `filter`
* query parameter (this function takes care to stringify it properly).
* @param {Object} params Optional. A map of any other parameters beside
* `filter`.
*/
const getMemberChallenges = async (
endpoint,
filters = {},
params = {},
) => {
const memberId = decodeToken(this.private.tokenV3).userId;
const query = {
...params,
...filters,
memberId,
};
const url = `${endpoint}?${qs.stringify(_.omit(query, ['limit', 'offset', 'technologies']))}`;
const res = await this.private.apiV5.get(url).then(checkError);
const totalCount = res.length;
return {
challenges: res || [],
totalCount,
};
};
this.private = {
api: getApi('V4', tokenV3),
apiV5: getApi('V5', tokenV3),
apiV2: getApi('V2', tokenV2),
apiV3: getApi('V3', tokenV3),
getChallenges,
getMemberChallenges,
tokenV2,
tokenV3,
memberService: getMembersService(),
submissionsService: getSubmissionsService(tokenV3),
};
}
/**
* Activates the specified challenge.
* @param {Number} challengeId
* @return {Promise} Resolves to null value in case of success; otherwise it
* is rejected.
*/
async activate(challengeId) {
const params = {
status: 'Active',
};
let res = await this.private.apiV5.patch(`/challenge/${challengeId}`, params);
if (!res.ok) throw new Error(res.statusText);
res = (await res.json()).result;
if (res.status !== 200) throw new Error(res.content);
return res.content;
}
/**
* Closes the specified challenge.
* @param {Number} challengeId
* @return {Promise} Resolves to null value in case of success; otherwise it
* is rejected.
*/
async close(challengeId) {
const params = {
status: 'Completed',
};
let res = await this.private.apiV5.patch(`/challenges/${challengeId}`, params);
if (!res.ok) throw new Error(res.statusText);
res = (await res.json()).result;
if (res.status !== 200) throw new Error(res.content);
return res.content;
}
/**
* Creates a new payment task.
* @param {Number} projectId
* @param {Number} accountId Billing account ID.
* @param {String} title
* @param {String} description
* @param {String} assignee
* @param {Number} payment
* @param {String} submissionGuidelines
* @param {Number} copilotId
* @param {Number} copilotFee
* @param {?} tags
* @return {Promise} Resolves to the created challenge object (payment task).
*/
async createTask(
projectId,
accountId,
title,
description,
assignee,
payment,
submissionGuidelines,
copilotId,
copilotFee,
tags,
) {
const registrationPhase = await this.private.apiV5.get('/challenge-phases?name=Registration');
const payload = {
param: {
name: title,
typeId: 'e885273d-aeda-42c0-917d-bfbf979afbba',
description,
legacy: {
track: 'FIRST_2_FINISH',
reviewType: 'INTERNAL',
confidentialityType: 'public',
billingAccountId: accountId,
},
phases: [
{
phaseId: registrationPhase.id,
scheduledEndDate: moment().toISOString(),
},
],
prizeSets: [
{
type: 'Challenge Prizes',
description: 'Challenge Prize',
prizes: [
{
value: payment,
type: 'First Placement',
},
],
},
],
tags,
projectId,
},
};
if (copilotId) {
_.assign(payload.param, {
copilotId,
copilotFee,
});
}
let res = await this.private.apiV5.postJson('/challenges', payload);
if (!res.ok) throw new Error(res.statusText);
res = (await res.json()).result;
if (res.status !== 200) throw new Error(res.content);
return res.content;
}
/**
* Gets challenge details from Topcoder API.
* NOTE: This function also uses API v2 and other endpoints for now, due
* to some information is missing or
* incorrect in the main endpoint. This may change in the future.
* @param {Number|String} challengeId
* @return {Promise} Resolves to the challenge object.
*/
async getChallengeDetails(challengeId) {
const memberId = this.private.tokenV3 ? decodeToken(this.private.tokenV3).userId : null;
let challenge = {};
let registrants = [];
let submissions = [];
let isLegacyChallenge = false;
let isRegistered = false;
const userDetails = { roles: [] };
// condition based on ROUTE used for Review Opportunities, change if needed
if (/^[\d]{5,8}$/.test(challengeId)) {
isLegacyChallenge = true;
challenge = await this.private.getChallenges('/challenges/', { legacyId: challengeId })
.then(res => res.challenges[0] || {});
} else {
challenge = await this.private.getChallenges(`/challenges/${challengeId}`)
.then(res => res.challenges);
}
if (challenge) {
registrants = await this.getChallengeRegistrants(challenge.id);
// This TEMP fix to colorStyle, this will be fixed with issue #4530
registrants = _.map(registrants, r => ({
...r, colorStyle: 'color: #151516',
}));
/* Prepare data to logged user */
if (memberId) {
isRegistered = _.some(registrants, r => `${r.memberId}` === `${memberId}`);
const subParams = {
challengeId,
perPage: 100,
};
submissions = await this.private.submissionsService.getSubmissions(subParams);
if (submissions) {
// Remove AV Scan, SonarQube Review and Virus Scan review types
const reviewScans = await this.private.submissionsService.getScanReviewIds();
submissions.forEach((s, i) => {
submissions[i].review = _.reject(s.review, r => r && _.includes(reviewScans, r.typeId));
});
// Add submission date to registrants
registrants.forEach((r, i) => {
const submission = submissions.find(s => `${s.memberId}` === `${r.memberId}`);
if (submission) {
registrants[i].submissionDate = submission.created;
}
});
}
userDetails.roles = await this.getUserRolesInChallenge(challengeId);
}
challenge = {
...challenge,
isLegacyChallenge,
isRegistered,
registrants,
submissions,
userDetails,
events: _.map(challenge.events, e => ({
eventName: e.key,
eventId: e.id,
description: e.name,
})),
fetchedWithAuth: Boolean(this.private.apiV5.private.token),
};
}
return challenge;
}
/**
* Gets challenge registrants from Topcoder API.
* @param {Number|String} challengeId
* @return {Promise} Resolves to the challenge registrants array.
*/
async getChallengeRegistrants(challengeId) {
/* If no token provided, resource will return Submitter role only */
const roleId = this.private.tokenV3 ? await this.getRoleId('Submitter') : '';
const params = {
challengeId,
roleId,
};
let registrants = await this.private.apiV5.get(`/resources?${qs.stringify(params)}`)
.then(checkErrorV5).then(res => res.result);
/* API will return all roles to currentUser, so need to filter in FE */
if (roleId) {
registrants = _.filter(registrants, r => r.roleId === roleId);
}
return registrants || [];
}
/**
* Gets possible challenge types.
* @return {Promise} Resolves to the array of subtrack names.
*/
getChallengeTypes() {
return this.private.apiV5.get('/challenge-types')
.then(res => (res.ok ? res.json() : new Error(res.statusText)))
.then(res => (
res.message
? new Error(res.message)
: res
));
}
/**
* Get the ID from a challenge type by abbreviation
* @param {String} abbreviation
* @return {Promise} ID from first abbreviation match
*/
async getChallengeTypeId(abbreviation) {
const ret = await this.private.apiV5.get(`/challenge-types?abbreviation=${abbreviation}`)
.then(checkErrorV5).then(res => res);
if (_.isEmpty(ret.result)) {
throw new Error('Challenge typeId not found!');
}
return ret.result[0].id;
}
/**
* Gets possible challenge tags (technologies).
* @return {Promise} Resolves to the array of tag strings.
*/
getChallengeTags() {
return this.private.api.get('/technologies')
.then(res => (res.ok ? res.json() : new Error(res.statusText)))
.then(res => (
res.result.status === 200
? res.result.content
: new Error(res.result.content)
));
}
/**
* Gets challenges.
* @param {Object} filters Optional.
* @param {Object} params Optional.
* @return {Promise} Resolves to the api response.
*/
async getChallenges(filters, params) {
return this.private.getChallenges('/challenges/', filters, params)
.then((res) => {
res.challenges.forEach(item => normalizeChallenge(item));
return res;
});
}
/**
* Gets SRM matches.
* @param {Object} params
* @return {Promise}
*/
async getSrms(params) {
const res = await this.private.api.get(`/srms/?${qs.stringify(params)}`);
return getApiResponsePayload(res);
}
static updateFiltersParamsForGettingMemberChallenges(filters, params) {
if (params && params.perPage) {
// eslint-disable-next-line no-param-reassign
params.offset = (params.page - 1) * params.perPage;
// eslint-disable-next-line no-param-reassign
params.limit = params.perPage;
}
}
/**
* Gets challenges of the specified user.
* @param {String} userId User id whose challenges we want to fetch.
* @return {Promise} Resolves to the api response.
*/
async getUserChallenges(userId, filters, params) {
const userFilters = _.cloneDeep(filters);
ChallengesService.updateFiltersParamsForGettingMemberChallenges(userFilters, params);
const query = {
...params,
...userFilters,
memberId: userId,
};
const url = `/challenges?${qs.stringify(_.omit(query, ['limit', 'offset', 'technologies']))}`;
const userChallenges = await this.private.apiV5.get(url)
.then(checkErrorV5)
.then((res) => {
res.result.forEach(item => normalizeChallenge(item, userId));
return res.result;
});
return {
challenges: userChallenges,
totalCount: userChallenges.length,
};
}
/**
* Gets user resources.
* @param {String} userId User id whose challenges we want to fetch.
* @param {Number} page Current page for paginated API response (default 1)
* @param {Number} perPage Page size for paginated API response (default 1000)
* @return {Promise} Resolves to the api response.
*/
async getUserResources(userId, page = 1, perPage = 1000) {
const res = await this.private.apiV5.get(`/resources/${userId}/challenges?page=${page}&perPage=${perPage}`);
return res.json();
}
/**
* Gets marathon matches of the specified user.
* @param {String} memberId User whose challenges we want to fetch.
* @param {Object} filter
* @param {Object} params
* @return {Promise} Resolves to the api response.
*/
async getUserMarathonMatches(memberId, filter, params) {
const newParams = {
...filter,
...params,
tag: 'Marathon Match',
memberId,
};
const res = await this.private.apiV5.get(`/challenges?${qs.stringify(newParams)}`);
return res.json();
}
/**
* Gets SRM matches related to the user.
* @param {String} handle
* @param {Object} params
* @return {Promise}
*/
async getUserSrms(handle, params) {
const url = `/members/${handle}/srms/?${qs.stringify(params)}`;
const res = await this.private.api.get(url);
return getApiResponsePayload(res);
}
/**
* Get the Resource Role ID from provided Role Name
* @param {String} roleName
* @return {Promise}
*/
async getRoleId(roleName) {
const params = {
name: roleName,
isActive: true,
};
const roles = await this.private.apiV5.get(`/resource-roles?${qs.stringify(params)}`)
.then(checkErrorV5).then(res => res.result);
if (_.isEmpty(roles)) {
throw new Error('Resource Role not found!');
}
return roles[0].id;
}
/**
* Registers user to the specified challenge.
* @param {String} challengeId
* @return {Promise}
*/
async register(challengeId) {
const user = decodeToken(this.private.tokenV3);
const roleId = await this.getRoleId('Submitter');
const params = {
challengeId,
memberHandle: encodeURIComponent(user.handle),
roleId,
};
const res = await this.private.apiV5.postJson('/resources', params);
if (!res.ok) throw new Error(res.statusText);
return res.json();
}
/**
* Unregisters user from the specified challenge.
* @param {String} challengeId
* @return {Promise}
*/
async unregister(challengeId) {
const user = decodeToken(this.private.tokenV3);
const roleId = await this.getRoleId('Submitter');
const params = {
challengeId,
memberHandle: encodeURIComponent(user.handle),
roleId,
};
const res = await this.private.apiV5.delete('/resources', JSON.stringify(params));
if (!res.ok) throw new Error(res.statusText);
return res.json();
}
/**
* Gets count of user's active challenges.
* @param {String} handle Topcoder user handle.
* @return {Action} Resolves to the api response.
*/
getActiveChallengesCount(handle) {
const filter = { status: 'Active' };
const params = { limit: 1, offset: 0 };
return this.getUserChallenges(handle, filter, params).then(res => res.totalCount);
}
/**
* Submits a challenge submission. Uses APIV2 for Development submission
* and APIV3 for Design submisisons.
* @param {Object} body
* @param {String} challengeId
* @param {String} track Either DESIGN or DEVELOP
* @return {Promise}
*/
submit(body, challengeId, track, onProgress) {
let api;
let contentType;
let url;
if (track === COMPETITION_TRACKS.DESIGN) {
({ api } = this.private);
contentType = 'application/json';
url = '/submissions/'; // The submission info is contained entirely in the JSON body
} else {
api = this.private.apiV2;
// contentType = 'multipart/form-data';
contentType = null;
url = `/develop/challenges/${challengeId}/upload`;
}
return api.upload(url, {
body,
headers: { 'Content-Type': contentType },
method: 'POST',
}, onProgress).then((res) => {
const jres = JSON.parse(res);
// Return result for Develop submission
if (track === COMPETITION_TRACKS.DEVELOP) {
return jres;
}
// Design Submission requires an extra "Processing" POST
const procId = jres.result.content.id;
return api.upload(`/submissions/${procId}/process/`, {
body: JSON.stringify({ param: jres.result.content }),
headers: { 'Content-Type': contentType },
method: 'POST',
}, onProgress).then(procres => JSON.parse(procres));
}, (err) => {
logger.error(`Failed to submit to the challenge #${challengeId}`, err);
throw err;
});
}
/**
* Updates the challenge (saves the give challenge to the API).
* @param {Object} challenge
* @param {String} tokenV3
* @return {Promise}
*/
async updateChallenge(challenge) {
const url = `/challenges/${challenge.id}`;
let res = await this.private.apiV5.put(url, challenge);
if (!res.ok) throw new Error(res.statusText);
res = (await res.json()).result;
if (res.status !== 200) throw new Error(res.content);
return res.content;
}
/**
* Gets roles of a user in the specified challenge. The user tested is
* the owner of authentication token used to instantiate the service.
*
* Notice, if you have already loaded the challenge as that user, these roles
* are attached to the challenge object under `userDetails.roles` path during
* challenge normalization. However, if you have not, this method is the most
* efficient way to get them, as it by-passes any unnecessary normalizations
* of the challenge object.
*
* @param {Number} challengeId Challenge ID.
*/
async getUserRolesInChallenge(challengeId) {
const user = decodeToken(this.private.tokenV3);
const url = `/resources?challengeId=${challengeId}&memberHandle=${user.handle}`;
const getResourcesResponse = await this.private.apiV5.get(url);
const resources = await getResourcesResponse.json();
if (resources) return _.map(_.filter(resources, r => r.memberHandle === user.handle), 'roleId');
throw new Error(`Failed to fetch user role from challenge #${challengeId}`);
}
}
let lastInstance = null;
/**
* Returns a new or existing challenges service.
* @param {String} tokenV3 Optional. Auth token for Topcoder API v3.
* @param {String} tokenV2 Optional. Auth token for Topcoder API v2.
* @return {ChallengesService} Challenges service object
*/
export function getService(tokenV3, tokenV2) {
if (!lastInstance || lastInstance.private.tokenV3 !== tokenV3
|| lastInstance.tokenV2 !== tokenV2) {
lastInstance = new ChallengesService(tokenV3, tokenV2);
}
return lastInstance;
}
/* Using default export would be confusing in this case. */
export default undefined;