Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
5.7 kB
0
Indexable
Never
import {
    client
} from '../index.js'

import {
    PermissionsBitField
} from 'discord.js'

export async function dashboardserverlist(req: any, res: any) {

    res.setHeader(

        "Cache-Control",

        "no-store, no-cache, must-revalidate, proxy-revalidate"

    );

    res.setHeader("Pragma", "no-cache");

    res.setHeader("Expires", "0");

    res.setHeader("Surrogate-Control", "no-store");



    if (

        req.cookies?.access_token?.toLowerCase() === "undefined" ||

        req.cookies?.access_token?.toLowerCase() === "null"

    ) {

        res.clearCookie("access_token");

        console.log("empty cookie deleting");

    }

    const accessToken = req.cookies?.access_token;

    if (accessToken) {

        const expirationTime = new Date(accessToken.expires); // Retrieve the expiration time from the cookie

        const currentTime = new Date(); // Get the current time

        if (currentTime > expirationTime) {

            // Cookie has expired

            // Perform necessary actions (e.g., clear the expired cookie)

            res.clearCookie(accessToken);

            console.log("cookie expired deleting");

        }

    }



    if (!accessToken) {

        return res.redirect(`/api/discord/login/`);

    } else {




        let guilds: any = undefined;

        let error: any = undefined;

        try {

            const response = await fetch(

                "https://discord.com/api/v9/users/@me/guilds",

                {

                    headers: {

                        Authorization: `Bearer ${accessToken}`,

                    },

                }

            );

            if (response.ok) {

                guilds = await response.json();

            } else {

                const erroror: any = await response.json();

                error = erroror.message;

            }

        } catch (errorrr) {

            error = errorrr;

        }

        let guildsthere: boolean = false;

        let filteredguilds: any = [];

        let sessionguild = []

        if (guilds) {

            guildsthere = true;

            const fetchGuildsPromises = guilds.map(async (guild) => {

                try {

                    const bitPermissions = new PermissionsBitField(guild.permissions);

                    console.log(bitPermissions);

                    let adminperms =

                        bitPermissions.has(PermissionsBitField.Flags.ManageGuild) ||

                        bitPermissions.has(PermissionsBitField.Flags.Administrator);

                    if (guild.owner) {

                        adminperms = true;

                    }



                    let fetchedguild = false



                    try {

                        fetchedguild = (await client.guilds.get(guild.id)) ? true : false; // client.guilds.cache.get(guild.id) || await client.guilds.fetch(guild.id);

                    } catch (e: any) {

                        if (e.code === 10004) {

                            // Ignore "Unknown Guild" error

                            console.log("bot not in this server ", guild.id);

                            // Error occurred while processing guild

                        } else {

                            console.log(e)

                        }

                    }

                    if (adminperms) {

                        console.log(guild.name);

                        function generateServerIconAbbreviation(serverName) {

                            // Split the server name into words

                            const words = serverName.split(" ");

                            // Extract the first letter from each word

                            const abbreviation = words

                                .map(word => word.charAt(0))

                                .join("")

                                .toUpperCase();

                            return abbreviation;

                        }



                        const guildWithIcon = {



                            id: guild.id,

                            name: guild.name,

                            icon: guild.icon

                                ?
                                `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png`

                                :
                                false,

                            present: false,

                            shortname: generateServerIconAbbreviation(guild.name),

                        };

                        if (fetchedguild) {

                            guildWithIcon.present = true

                        }

                        // output: true

                        sessionguild.push(guild)

                        filteredguilds.push(guildWithIcon);

                    }

                } catch (err: any) {



                    console.error(err.stack);



                }

            }); //

            await Promise.all(fetchGuildsPromises);

        }

        req.session.guilds = sessionguild

        if (!guilds || guilds.length === 0) {

            guildsthere = false;

        }

        console.log("guildsthere", guildsthere);

        console.log(filteredguilds);



        if (error) console.error(error);

        try {



            return res.render("./dashboard/dashboard.ejs", {

                error: error,

                guildsthere: guildsthere,

                servers: filteredguilds,



            });

        } catch (e: any) {

            console.log(e);

            console.log(JSON.stringify(e));

            res.send(

                `Error 

            )}`

            );

        }



    }



}