# JSDoc: Source: app/channel/channelManager.js

# Source: app/channel/channelManager.js

    /*Canopy - The next generation of stoner streaming software
    Copyright (C) 2024-2025 Rainbownapkin and the TTN Community

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.*/

    //Config
    const config = require('../../../config.json');

    //Local Imports
    const channelModel = require('../../schemas/channel/channelSchema');
    const emoteModel = require('../../schemas/emoteSchema');
    const {userModel} = require('../../schemas/user/userSchema');
    const userBanModel = require('../../schemas/user/userBanSchema');
    const loggerUtils = require('../../utils/loggerUtils');
    const csrfUtils = require('../../utils/csrfUtils');
    const activeChannel = require('./activeChannel');
    const chatHandler = require('./chatHandler');

    /**
     * Class containing global server-side channel connection management logic
     */
    module.exports = class{
        /**
         * Instantiates object containing global server-side channel conection management logic
         * @param {Server} io - Socket.io server instanced passed down from server.js
         */
        constructor(io){
            //Set the socket.io server
            this.io = io;

            //Load
            this.activeChannels = new Map;

            //Load server components
            this.chatHandler = new chatHandler(this);
            //this.mediaYanker = new mediaYanker(this);

            //Handle connections from socket.io
            io.on("connection", this.handleConnection.bind(this) );
        }

        /**
         * Handles global server-side initialization for new connections to any channel
         * @param {Socket} socket - Requesting Socket
         */
        async handleConnection(socket){
            try{
                //ensure unbanned ip and valid CSRF token
                if(!(await this.validateSocket(socket))){
                    socket.disconnect();
                    return;
                }

                //Prevent logged out connections and authenticate socket
                if(socket.request.session.user != null){
                    //Authenticate socket
                    const userDB = await this.authSocket(socket);

                    //Get the active channel based on the socket
                    var {activeChan, chanDB} = await this.getActiveChan(socket);

                    //Check for chan ban
                    const ban = await chanDB.checkBanByUserDoc(userDB);
                    if(ban != null){
                        //Toss out banned user's
                        if(ban.expirationDays < 0){
                            socket.emit("kick", {type: "kicked", reason: "You have been permanently banned from this channel!"});
                        }else{
                            socket.emit("kick", {type: "kicked", reason: `You have been temporarily banned from this channel, and will be unbanned in ${ban.getDaysUntilExpiration()} day(s)!`});
                        }
                        socket.disconnect();
                        return;
                    }

                    //Define listeners for inter-channel classes
                    this.defineListeners(socket);
                    this.chatHandler.defineListeners(socket);

                    //Hand off the connection to it's given active channel object
                    //Lil' hacky to pass chanDB like that, but why double up on DB calls?
                    activeChan.handleConnection(userDB, chanDB, socket);
                }else{
                    //Toss out anon's
                    socket.emit("kick", {type: "disconnected", reason: "You must log-in to join this channel!"});
                    socket.disconnect();
                    return;
                }
            }catch(err){
                //Flip a table if something fucks up
                return loggerUtils.socketCriticalExceptionHandler(socket, err);
            }
        }

        /**
         * Global server-side validation logic for new connections to any channel
         * @param {Socket} socket - Requesting Socket
         * @returns {Boolean} true on success
         */
        async validateSocket(socket){
            //If we're proxied use passthrough IP
            const ip = config.proxied ? socket.handshake.headers['x-forwarded-for'] : socket.handshake.address;

            //Look for ban by IP
            const ipBanDB = await userBanModel.checkBanByIP(ip);

            //If this ip is randy bobandy
            if(ipBanDB != null){
                //Make the number a little prettier despite the lack of precision since we're not doing calculations here :P
                const expiration = ipBanDB.getDaysUntilExpiration() < 1 ? 0 : ipBanDB.getDaysUntilExpiration();

                //If the ban is permanent
                if(ipBanDB.permanent){
                    //tell it to fuck off
                    socket.emit("kick", {type: "kicked", reason: `The IP address you are trying to connect from has been permanently banned. Your cleartext IP has been saved to the database. Any associated accounts will be nuked in ${expiration} day(s).`});
                //Otherwise
                }else{
                    //tell it to fuck off
                    socket.emit("kick", {type: "kicked", reason: `The IP address you are trying to connect from has been temporarily banned. Your cleartext IP has been saved to the database until the ban expires in ${expiration} day(s).`});
                }

                return false;
            }

            //Check for Cross-Site Request Forgery
            if(!csrfUtils.isRequestValid(socket.request)){
                socket.emit("kick", {type: "disconnected", reason: "Invalid CSRF Token!"});
                return false;
            }

            return true;
        }

        /**
         * Global server-side authorization logic for new connections to any channel
         * @param {Socket} socket - Requesting Socket
         * @returns {Mongoose.Document} - Authorized User Document upon success
         */
        async authSocket(socket){
            //Find the user in the Database since the session won't store enough data to fulfill our needs :P
            const userDB = await userModel.findOne({user: socket.request.session.user.user});

            if(userDB == null){
                throw loggerUtils.exceptionSmith("User not found!", "unauthorized");
            }

            //Set socket user and channel values
            socket.user = {
                id: userDB.id,
                user: userDB.user,
            };

            return userDB;
        }

        /**
         * Gets active channel from a given socket
         * @param {Socket} socket - Socket to check
         * @returns {Object} Object containing users active channel name and channel document object
         */
        async getActiveChan(socket){
            socket.chan = socket.handshake.headers.referer.split('/c/')[1].split('/')[0];
            const chanDB = (await channelModel.findOne({name: socket.chan}));

            //Check if channel exists
            if(chanDB == null){
                throw loggerUtils.exceptionSmith("Channel not found", "validation");
            }

            //Check if current channel is active
            var activeChan = this.activeChannels.get(socket.chan);

            if(!activeChan){
                //If not, make it so
                activeChan = new activeChannel(this, chanDB);
                this.activeChannels.set(socket.chan, activeChan);
            }

            //Return whatever the active channel is (new or old)
            return {activeChan, chanDB};
        }

        /**
         * Define Global Server-Side socket event listeners
         * @param {Socket} socket - Socket to check
         */
        defineListeners(socket){
            //Socket Listeners
            socket.conn.on("close", (reason) => {this.handleDisconnect(socket, reason)});
        }

        /**
         * Global server-side logic for handling disconncted sockets
         * @param {Socket} socket - Socket to check
         * @param {String} reason - Reason for disconnection
         */
        handleDisconnect(socket, reason){
            var activeChan = this.activeChannels.get(socket.chan);
            activeChan.handleDisconnect(socket, reason);
        }

        /**
         * Pulls user information by socket
         * @param {Socket} socket - Socket to check
         * @return returns related user info
         */
        getSocketInfo(socket){
            const channel = this.activeChannels.get(socket.chan);
            return channel.userList.get(socket.user.user);
        }

        /**
         * Pulls user information by socket
         * @param {Socket} socket - Socket to check
         * @return returns related user info
         */
        getConnectedChannels(socket){
            //Create a list to hold connected channels
            var chanList = [];

            //For each channel
            this.activeChannels.forEach((channel) => {
                //Check and see if the user is connected
                const foundUser = channel.userList.get(socket.user.user);

                //If we found a user and this channel hasn't been added to the list
                if(foundUser){
                    chanList.push(channel);
                }
            });

            //return the channels this user is connected to
            return chanList;
        }

        /**
         * Iterates through connections by a given username, and runs them through a given callback function/method
         * @param {String} user - Username to crawl connections against
         * @param {Function} cb - Callback function to run active connections of a given user against
         */
        crawlConnections(user, cb){
            //For each channel
            this.activeChannels.forEach((channel) => {
                //Check and see if the user is connected
                const foundUser = channel.userList.get(user);

                //If we found a user and this channel hasn't been added to the list
                if(foundUser){
                    cb(foundUser);
                }
            });
        }

        /**
         * Iterates through connections by a given username, and runs them through a given callback function/method
         * @param {String} user - Username to crawl connections against
         * @param {Function} cb - Callback function to run active connections of a given user against
         */
        getConnections(user){
            //Create a list to store our connections
            var connections = [];

            //crawl through connections
            //this.crawlConnections(user,(foundUser)=>{connections.push(foundUser)});
            this.crawlConnections(user,(foundUser)=>{connections.push(foundUser)});

            //return connects
            return connections;
        }

        /**
         * Kicks a user from all channels by username
         * @param {String} user - Username to kick from the server
         * @param {String} reason - Reason for kick
         */
        kickConnections(user, reason){
            //crawl through connections and kick user
            this.crawlConnections(user,(foundUser)=>{foundUser.disconnect(reason)});
        }

        /**
         * Broadcast global emote list
         */
        async broadcastSiteEmotes(){
            //Get emote list from DB
            const emoteList = await emoteModel.getEmotes();

            //Broadcast that sumbitch
            this.io.sockets.emit('siteEmotes', emoteList);
        }
    }