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 f4e6596 commit 6547eb2
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 119 deletions.
4 changes: 2 additions & 2 deletions src/config/oAtuh2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const discord = {
disableGuildSelect: boolean = true,
): string {
const baseDiscordUrl = 'https://discord.com/api/oauth2/authorize';
let url = `${baseDiscordUrl}?client_id=${config.discord.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent(scope)}&permissions=${permissions}&state=${state}`;
let url = `${baseDiscordUrl}?client_id=${config.discord.clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&permissions=${permissions}&state=${state}`;
if (guildId) url += `&guild_id=${guildId}`;
if (disableGuildSelect) url += `&disable_guild_select=true`;
return url;
Expand All @@ -70,6 +70,6 @@ export const twitter = {
},
generateTwitterAuthUrl(state: string, codeChallenge: string): string {
const baseTwitterUrl = 'https://twitter.com/i/oauth2/authorize';
return `${baseTwitterUrl}?response_type=code&client_id=${config.twitter.clientId}&redirect_uri=${encodeURIComponent(config.twitter.callbackURI.connect)}&scope=${encodeURIComponent(this.scopes.connectAccount)}&state=${state}&code_challenge=${codeChallenge}&code_challenge_method=S256`;
return `${baseTwitterUrl}?response_type=code&client_id=${config.twitter.clientId}&redirect_uri=${config.twitter.callbackURI.connect}&scope=${this.scopes.connectAccount}&state=${state}&code_challenge=${codeChallenge}&code_challenge_method=S256`;
},
};
138 changes: 42 additions & 96 deletions src/services/discord/core.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,121 +22,62 @@ async function getPropertyHandler(req: IAuthAndPlatform) {



if (req.query.property === 'role') {
const filter = pick(req.query, ['name']);
if (filter.name) {
filter.name = {
$regex: filter.name,
$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') {
const filter = pick(req.query, ['name']);
if (filter.name) {
filter.name = {
$regex: filter.name,
$options: 'i'
};
}
filter.deletedAt = null;
if (req.body.channelIds) {
filter.channelId = { $in: req.body.channelIds };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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]);
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]);
} 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]);
}
channels[i] = {
channelId: channels[i].channelId,
name: channels[i].name,
parentId: channels[i].parentId,
canReadMessageHistoryAndViewChannel,
announcementAccess,
type: channels[i].type
}
}
return await sort.sortChannels(channels);
if (req.query.property === 'role') {
const filter = pick(req.query, ['name']);
if (filter.name) {
filter.name = {
$regex: filter.name,
$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;
if (req.body.channelIds) {
filter.channelId = { $in: req.body.channelIds };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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
}
}
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);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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 @@ -149,14 +90,15 @@ 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 @@ -167,6 +109,8 @@ async function leaveBotFromGuild(guildId: Snowflake) {
}
}



/**
* exchange discord code with access token
* @param {string} code
Expand All @@ -180,17 +124,18 @@ 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 @@ -208,11 +153,12 @@ 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 @@ -230,11 +176,12 @@ 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 @@ -243,6 +190,7 @@ async function getBotFromDiscordAPI(): Promise<IDiscordUser> {
}
}


/**
* get list of permissions that bot has in a specific guild
* @param {Snowflake} guildId
Expand All @@ -255,10 +203,7 @@ 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 @@ -310,7 +255,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 @@ -345,6 +290,7 @@ class DiscordBotManager {
],
});
await DiscordBotManager.client.login(config.discord.botToken);

}
return DiscordBotManager.client;
}
Expand All @@ -360,5 +306,5 @@ export default {
getBotPermissions,
getRequirePermissionsForModule,
getCombinedPermissionsValue,
getPermissionsStatus,
};
getPermissionsStatus
}
42 changes: 21 additions & 21 deletions src/utils/sort.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

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) {
if (channel.parentId === null) {
const subChannels = channels.filter((c: any) => c.parentId === channel.channelId);
if (subChannels.length > 0) {
sortedChannels.push({
channelId: channel.channelId,
title: channel.name,
subChannels,
});
} else {
unCategorized.subChannels.push({
announcementAccess: channel.announcementAccess, canReadMessageHistoryAndViewChannel: channel.canReadMessageHistoryAndViewChannel, channelId: channel.channelId, parentId: channel.channelId, name: channel.name, type: channel.type
});
}
}
for (const channel of channels) {
if (channel.parentId === null) {
const subChannels = channels.filter((c: any) => c.parentId === channel.channelId);
if (subChannels.length > 0) {
sortedChannels.push({
channelId: channel.channelId,
title: channel.name,
subChannels,
});
} else {
unCategorized.subChannels.push({
announcementAccess: channel.announcementAccess, canReadMessageHistoryAndViewChannel: channel.canReadMessageHistoryAndViewChannel, channelId: channel.channelId, parentId: channel.channelId, name: channel.name, type: channel.type
});
}
}
}

Expand All @@ -43,7 +40,10 @@ function sortByHandler(sortBy: string): Record<string, 1 | -1> {
return sortParams;
}




export default {
sortChannels,
sortByHandler,
};
}

0 comments on commit 6547eb2

Please sign in to comment.