Skip to content

Commit

Permalink
Fix getMembers API
Browse files Browse the repository at this point in the history
  • Loading branch information
csuvajit committed Mar 12, 2024
1 parent 50ea61d commit 025142a
Show file tree
Hide file tree
Showing 11 changed files with 115 additions and 35 deletions.
10 changes: 9 additions & 1 deletion apps/service-auth/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CurrentUserExpanded, JwtAuthGuard, JwtUser } from '@app/auth';
import { CurrentUserExpanded, JwtAuthGuard, JwtUser, Role, Roles, RolesGuard } from '@app/auth';
import { getAppHealth } from '@app/helper';
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
Expand Down Expand Up @@ -33,4 +33,12 @@ export class AuthController {
getStatus(@CurrentUserExpanded() user: JwtUser) {
return user;
}

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN)
@ApiExcludeEndpoint()
@Get('/applications')
getCustomBots() {
return this.authService.getCustomBots();
}
}
24 changes: 21 additions & 3 deletions apps/service-auth/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { JwtUser } from '@app/auth';
import { Collections } from '@app/constants';
import { PortalUsersEntity } from '@app/entities';
import { CustomBotsEntity, PortalUsersEntity } from '@app/entities';
import { encrypt } from '@app/helper';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import moment from 'moment';
Expand All @@ -14,6 +15,7 @@ export class AuthService {
constructor(
private readonly jwtService: JwtService,
@Inject(Collections.PORTAL_USERS) private portalUsersCollection: Collection<PortalUsersEntity>,
@Inject(Collections.CUSTOM_BOTS) private customBotsCollection: Collection<CustomBotsEntity>,
) {}

async login(passKey: string) {
Expand All @@ -30,13 +32,29 @@ export class AuthService {
return {
userId: user.userId,
roles: user.roles,
expiresIn: moment().add(30, 'days').toDate().getTime(),
accessToken: this.jwtService.sign(payload, { expiresIn: '30d' }),
expiresIn: moment().add(2, 'hours').toDate().getTime(),
accessToken: this.jwtService.sign(payload, { expiresIn: '2h' }),
};
}

async validateJwt(jwtUser: JwtUser) {
if (jwtUser.version !== jwtVersion) throw new UnauthorizedException();
return jwtUser;
}

async getCustomBots() {
const bots = await this.customBotsCollection
.find()
.project({
name: 0,
serviceId: 0,
patronId: 0,
userId: 0,
updatedAt: 0,
createdAt: 0,
})
.toArray();

return { payload: await encrypt(JSON.stringify(bots)) };
}
}
6 changes: 4 additions & 2 deletions apps/service-auth/src/clans/clans.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CurrentUser, JwtAuthGuard, RolesGuard } from '@app/auth';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ClansService } from './clans.service';
import { CWLStatsOutput } from './dto/cwl-stats.dto';

@ApiTags('CLANS')
@ApiBearerAuth()
Expand All @@ -15,7 +16,7 @@ export class ClansController {
return this.clansService.getCapitalContributions(clanTag);
}

@Get('/:clanTag/linked-members')
@Get('/:clanTag/links')
getLinkedMembers(@CurrentUser() userId: string, @Param('clanTag') clanTag: string) {
return this.clansService.getLinkedMembers(userId, clanTag);
}
Expand All @@ -26,6 +27,7 @@ export class ClansController {
}

@Get('/:clanTag/cwl-stats')
@ApiResponse({ type: CWLStatsOutput, status: 200 })
getCwlStats(@Param('clanTag') clanTag: string) {
return this.clansService.getCWLStats(clanTag);
}
Expand Down
30 changes: 8 additions & 22 deletions apps/service-auth/src/clans/clans.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { APIClanWarAttack, APIWarClan } from 'clashofclans.js';
import { Collection } from 'mongodb';
import { CWLMemberStatsOutput, CWLStatsOutput } from './dto/cwl-stats.dto';

@Injectable()
export class ClansService {
Expand Down Expand Up @@ -211,33 +212,14 @@ export class ClansService {
};
}

public async getCWLStats(clanTag: string) {
public async getCWLStats(clanTag: string): Promise<CWLStatsOutput> {
const body = await this.cwlGroupsCollection.findOne(
{ 'clans.tag': clanTag },
{ sort: { _id: -1 } },
);
if (!body) throw new NotFoundException('Clan war league group not found');

const members: Record<
string,
{
name: string;
tag: string;
participated: number;
attacks: number;
stars: number;
destruction: number;
trueStars: number;
threeStars: number;
twoStars: number;
oneStar: number;
zeroStars: number;
missedAttacks: number;
defenseStars: number;
defenseDestruction: number;
defenseCount: number;
}
> = {};
const members: Record<string, CWLMemberStatsOutput> = {};

const wars = await this.clanWarsCollection
.find({ warTag: { $in: body.warTags[clanTag] } })
Expand Down Expand Up @@ -299,7 +281,11 @@ export class ClansService {
}
}

return Object.values(members);
return {
season: body.season,
clans: body.clans,
members: Object.values(members),
};
}

private getWarResult(clan: APIWarClan, opponent: APIWarClan) {
Expand Down
35 changes: 35 additions & 0 deletions apps/service-auth/src/clans/dto/cwl-stats.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ApiProperty } from '@nestjs/swagger';

export class CWLMemberStatsOutput {
name: string;
tag: string;
participated: number;
attacks: number;
stars: number;
destruction: number;
trueStars: number;
threeStars: number;
twoStars: number;
oneStar: number;
zeroStars: number;
missedAttacks: number;
defenseStars: number;
defenseDestruction: number;
defenseCount: number;
}

export class CWLClansOutput {
name: string;
tag: string;
leagueId: number;
}

export class CWLStatsOutput {
season: string;

@ApiProperty({ isArray: true, type: CWLClansOutput })
clans: CWLClansOutput[];

@ApiProperty({ isArray: true, type: CWLMemberStatsOutput })
members: CWLMemberStatsOutput[];
}
8 changes: 6 additions & 2 deletions apps/service-auth/src/guilds/guilds.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
BotGuildsEntity,
ClanCategoriesEntity,
ClanStoresEntity,
CustomBotsEntity,
SettingsEntity,
} from '@app/entities';
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
Expand All @@ -21,10 +22,13 @@ export class GuildsService {
private botGuildsCollection: Collection<BotGuildsEntity>,
@Inject(Collections.SETTINGS)
private settingsCollection: Collection<SettingsEntity>,
@Inject(Collections.CUSTOM_BOTS)
private customBotsCollection: Collection<CustomBotsEntity>,
) {}

getMembers(guildId: string, q: string) {
return this.discordClientService.listMembers(guildId, q);
async getMembers(guildId: string, query: string) {
const bot = await this.customBotsCollection.findOne({ guildIds: guildId });
return this.discordClientService.listMembers({ query, guildId, token: bot?.token ?? null });
}

async getGuild(guildId: string): Promise<GuildOutput> {
Expand Down
4 changes: 2 additions & 2 deletions apps/service-auth/src/players/players.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ import { PlayersService } from './players.service';
export class PlayersController {
constructor(private playersService: PlayersService) {}

@Get('/:playerTag/clan-wars')
@Get('/:playerTag/wars')
getWarHistory(
@Param('playerTag') playerTag: string,
@Query() query: AttackHistoryQueryInput,
): Promise<AttackHistoryOutput[]> {
return this.playersService.getClanWarHistory(playerTag, query.months);
}

@Get('/:playerTag/clan-war-league-stats')
@Get('/:playerTag/cwl-stats')
getClanWarLeagueStats(
@Param('playerTag') playerTag: string,
@Query() query: AttackHistoryQueryInput,
Expand Down
17 changes: 15 additions & 2 deletions libs/discord-client/src/discord-client.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const rest = new REST({ version: '10' });

@Injectable()
export class DiscordClientService {
constructor(configService: ConfigService) {
constructor(private configService: ConfigService) {
rest.setToken(configService.getOrThrow('DISCORD_TOKEN'));
}

Expand All @@ -18,9 +18,22 @@ export class DiscordClientService {
return payload as APIUser;
}

async listMembers(guildId: string, query: string): Promise<APIGuildMember[]> {
async listMembers({
guildId,
query,
token,
}: {
guildId: string;
query: string;
token: string | null;
}): Promise<APIGuildMember[]> {
token ??= this.configService.getOrThrow('DISCORD_TOKEN');

const payload = await rest.get(Routes.guildMembersSearch(guildId), {
query: new URLSearchParams({ query, limit: '50' }),
headers: {
Authorization: `Bot ${token}`,
},
});
return payload as APIGuildMember[];
}
Expand Down
12 changes: 12 additions & 0 deletions libs/entities/src/custom-bots.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export class CustomBotsEntity {
applicationId: string;
name: string;
userId: string;
token: string;
patronId: string;
serviceId: string;
isLive: boolean;
guildIds: string[];
updatedAt: Date;
createdAt: Date;
}
3 changes: 2 additions & 1 deletion libs/entities/src/cwl-groups.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ export class CWLGroupsEntity {
clans: {
name: string;
tag: string;
};
leagueId: number;
}[];
rounds: { warTags: string[] }[];
warTags: Record<string, string[]>;
}
1 change: 1 addition & 0 deletions libs/entities/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export * from './capital-contributions.entity';
export * from './capital-raid-seasons.entity';
export * from './clan-categories.entity';
export * from './clan-stores.entity';
export * from './custom-bots.entity';
export * from './cwl-groups.entity';
export * from './player-links.entity';
export * from './players.entity';
Expand Down

0 comments on commit 025142a

Please sign in to comment.