Skip to content

Commit

Permalink
format the code
Browse files Browse the repository at this point in the history
  • Loading branch information
Behzad-rabiei committed Mar 5, 2024
1 parent 1a6a804 commit 8a93bc9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 46 deletions.
89 changes: 51 additions & 38 deletions src/services/discord/core.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,24 @@ const logger = parentLogger.child({ module: 'DiscordService' });
async function getPropertyHandler(req: IAuthAndPlatform) {
const connection = await DatabaseManager.getInstance().getTenantDb(req.platform?.metadata?.id);



if (req.query.property === 'role') {
const filter = pick(req.query, ['name']);
if (filter.name) {
filter.name = {
$regex: filter.name,
$options: 'i'
$options: 'i',
};
}
filter.deletedAt = null;
const options = pick(req.query, ['sortBy', 'limit', 'page']);

return await roleService.queryRoles(connection, filter, options)
}
else if (req.query.property === 'channel') {
return await roleService.queryRoles(connection, filter, options);
} else if (req.query.property === 'channel') {
const filter = pick(req.query, ['name']);
if (filter.name) {
filter.name = {
$regex: filter.name,
$options: 'i'
$options: 'i',
};
}
filter.deletedAt = null;
Expand All @@ -49,35 +46,56 @@ async function getPropertyHandler(req: IAuthAndPlatform) {
}
const channels: any = await channelService.getChannels(connection, filter);
for (let i = 0; i < channels.length; i++) {
const canReadMessageHistoryAndViewChannel = await channelService.checkBotPermissions(req.platform?.metadata?.id, channels[i], [discord.permissions.ReadData.ViewChannel, discord.permissions.ReadData.ReadMessageHistory]);
const canReadMessageHistoryAndViewChannel = await channelService.checkBotPermissions(
req.platform?.metadata?.id,
channels[i],
[discord.permissions.ReadData.ViewChannel, discord.permissions.ReadData.ReadMessageHistory],
);
let announcementAccess: boolean;
if (channels[i].type === 0 || channels[i].type === 4) {
announcementAccess = await channelService.checkBotPermissions(req.platform?.metadata?.id, channels[i], [discord.permissions.Announcement.ViewChannel, discord.permissions.Announcement.SendMessages, discord.permissions.Announcement.SendMessagesInThreads, discord.permissions.Announcement.CreatePrivateThreads, discord.permissions.Announcement.CreatePublicThreads, discord.permissions.Announcement.EmbedLinks, discord.permissions.Announcement.AttachFiles, discord.permissions.Announcement.MentionEveryone]);
announcementAccess = await channelService.checkBotPermissions(req.platform?.metadata?.id, channels[i], [
discord.permissions.Announcement.ViewChannel,
discord.permissions.Announcement.SendMessages,
discord.permissions.Announcement.SendMessagesInThreads,
discord.permissions.Announcement.CreatePrivateThreads,
discord.permissions.Announcement.CreatePublicThreads,
discord.permissions.Announcement.EmbedLinks,
discord.permissions.Announcement.AttachFiles,
discord.permissions.Announcement.MentionEveryone,
]);
} else {
announcementAccess = await channelService.checkBotPermissions(req.platform?.metadata?.id, channels[i], [discord.permissions.Announcement.ViewChannel, discord.permissions.Announcement.SendMessages, discord.permissions.Announcement.SendMessagesInThreads, discord.permissions.Announcement.CreatePrivateThreads, discord.permissions.Announcement.CreatePublicThreads, discord.permissions.Announcement.EmbedLinks, discord.permissions.Announcement.AttachFiles, discord.permissions.Announcement.MentionEveryone, discord.permissions.Announcement.Connect]);
announcementAccess = await channelService.checkBotPermissions(req.platform?.metadata?.id, channels[i], [
discord.permissions.Announcement.ViewChannel,
discord.permissions.Announcement.SendMessages,
discord.permissions.Announcement.SendMessagesInThreads,
discord.permissions.Announcement.CreatePrivateThreads,
discord.permissions.Announcement.CreatePublicThreads,
discord.permissions.Announcement.EmbedLinks,
discord.permissions.Announcement.AttachFiles,
discord.permissions.Announcement.MentionEveryone,
discord.permissions.Announcement.Connect,
]);
}
channels[i] = {
channelId: channels[i].channelId,
name: channels[i].name,
parentId: channels[i].parentId,
canReadMessageHistoryAndViewChannel,
announcementAccess,
type: channels[i].type
}
type: channels[i].type,
};
}
return await sort.sortChannels(channels);
}

else if (req.query.property === 'guildMember') {
} else if (req.query.property === 'guildMember') {
const filter = pick(req.query, ['ngu']);
filter.deletedAt = null;
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const guildMembers = await guildMemberService.queryGuildMembers(connection, filter, options)
const guildMembers = await guildMemberService.queryGuildMembers(connection, filter, options);
guildMembers.results.forEach((guildMember: any) => {
guildMember.ngu = guildMemberService.getNgu(guildMember);
guildMember.username = guildMemberService.getUsername(guildMember);
});
return guildMembers
return guildMembers;
}
}

Expand All @@ -90,15 +108,14 @@ async function getGuildFromDiscordJS(guildId: Snowflake): Promise<Guild | null>
const client = await DiscordBotManager.getClient();
try {
return await client.guilds.fetch(guildId);

} catch (error) {
logger.error({ error }, 'Failed to get guild from discordJS');
return null;
}
}

/**
* leave bot from guild
* leave bot from guild
* @param {Snowflake} guildId
* @returns {Promise<IDiscordOAuth2EchangeCode>}
*/
Expand All @@ -109,8 +126,6 @@ async function leaveBotFromGuild(guildId: Snowflake) {
}
}



/**
* exchange discord code with access token
* @param {string} code
Expand All @@ -124,18 +139,17 @@ async function exchangeCode(code: string, redirect_uri: string): Promise<IDiscor
client_secret: config.discord.clientSecret,
grant_type: 'authorization_code',
redirect_uri,
code
code,
};

const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(data),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
if (response.ok) {
return await response.json();
}
else {
} else {
throw new Error();
}
} catch (error) {
Expand All @@ -153,12 +167,11 @@ async function getUserFromDiscordAPI(accessToken: string): Promise<IDiscordUser>
try {
const response = await fetch('https://discord.com/api/users/@me', {
method: 'GET',
headers: { 'Authorization': `Bearer ${accessToken}` }
headers: { Authorization: `Bearer ${accessToken}` },
});
if (response.ok) {
return await response.json();
}
else {
} else {
throw new Error(await response.json());
}
} catch (error) {
Expand All @@ -176,12 +189,11 @@ async function getBotFromDiscordAPI(): Promise<IDiscordUser> {
try {
const response = await fetch('https://discord.com/api/users/@me', {
method: 'GET',
headers: { 'Authorization': `Bot ${config.discord.botToken}` }
headers: { Authorization: `Bot ${config.discord.botToken}` },
});
if (response.ok) {
return await response.json();
}
else {
} else {
throw new Error(await response.json());
}
} catch (error) {
Expand All @@ -190,7 +202,6 @@ async function getBotFromDiscordAPI(): Promise<IDiscordUser> {
}
}


/**
* get list of permissions that bot has in a specific guild
* @param {Snowflake} guildId
Expand All @@ -203,7 +214,10 @@ async function getBotPermissions(guildId: Snowflake): Promise<Array<string>> {
const member = await guild.members.fetch(config.discord.clientId);
return member.permissions.toArray();
} catch (error) {
logger.error({ bot_token: config.discord.botToken, error }, 'Failed to get list of permissions that bot has in a specific guild');
logger.error(
{ bot_token: config.discord.botToken, error },
'Failed to get list of permissions that bot has in a specific guild',
);
throw new ApiError(590, 'Failed to get list of permissions that bot has in a specific guild');
}
}
Expand Down Expand Up @@ -255,7 +269,7 @@ function getCombinedPermissionsValue(permissionsArray: Array<string>) {
* The function iterates through each category of permissions (like ReadData, Announcement) in the
* discord object and checks if the given permissions are present in each category.
* If a permission is present, it is marked as true, otherwise false.
*
*
* @param {string[]} permissionsToCheck - An array of permission names to check against the discord permissions.
* @returns {any} An object with each category of permissions containing key-value pairs of permission names and their boolean status (true if present in the array, false otherwise).
*/
Expand Down Expand Up @@ -290,7 +304,6 @@ class DiscordBotManager {
],
});
await DiscordBotManager.client.login(config.discord.botToken);

}
return DiscordBotManager.client;
}
Expand All @@ -306,5 +319,5 @@ export default {
getBotPermissions,
getRequirePermissionsForModule,
getCombinedPermissionsValue,
getPermissionsStatus
}
getPermissionsStatus,
};
18 changes: 10 additions & 8 deletions src/utils/sort.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
function sortChannels(channels: any[]) {
const sortedChannels: any[] = [];
const unCategorized: any = {
channelId: "0",
title: "unCategorized",
subChannels: []
channelId: '0',
title: 'unCategorized',
subChannels: [],
};

for (const channel of channels) {
Expand All @@ -17,7 +17,12 @@ function sortChannels(channels: any[]) {
});
} else {
unCategorized.subChannels.push({
announcementAccess: channel.announcementAccess, canReadMessageHistoryAndViewChannel: channel.canReadMessageHistoryAndViewChannel, channelId: channel.channelId, parentId: channel.channelId, name: channel.name, type: channel.type
announcementAccess: channel.announcementAccess,
canReadMessageHistoryAndViewChannel: channel.canReadMessageHistoryAndViewChannel,
channelId: channel.channelId,
parentId: channel.channelId,
name: channel.name,
type: channel.type,
});
}
}
Expand All @@ -40,10 +45,7 @@ function sortByHandler(sortBy: string): Record<string, 1 | -1> {
return sortParams;
}




export default {
sortChannels,
sortByHandler,
}
};

0 comments on commit 8a93bc9

Please sign in to comment.