<commit_before>'use strict';

var hat = require('hat'),
    moment = require('moment'),
    log = require('./logger'),
    io;

var channels = {};
var clients = {};
var sockets = {};
var messages = {};

function formatMessage(username, text) {
    return {
        text: moment().format('HH:mm:ss') +
        ' <strong>'+username+'</strong>: ' + text
    };
}

function formatChannelMessage(text) {
    return {
        text: moment().format('HH:mm:ss') + ' ' + text
    };
}

function addMessage(channel, text) {
    log.info('addMessage()', {channel: channel, text: text});
    if (!messages[channel]) {
        messages[channel] = [];
    }
    messages[channel].push(text);
    if (messages[channel].length > 100) {
        messages[channel].splice(0, 1);
    }
    //log.info('messages for ' + channel, messages[channel]);
}

function getMessages(channel) {
    log.info('getMessages('+channel+')');
    var result = [];
    if (messages[channel]) {
        result = messages[channel];
    }
    //log.info('result', result);
    return result;
}

function addUser (user) {
    clients[user.uuid] = user;
    sockets[user.socketId] = clients[user.uuid];
}

function removeUser (user) {
    if (!user || !user.uuid) {
        return false;
    }
    delete clients[user.uuid];
    delete sockets[user.socketId];
}

function addUserToChannel (uuid, channelName) {
    log.info('channels', channels);
    channels[channelName].users.push(uuid);
    clients[uuid].channels.push(channelName);
}

function removeUserFromChannel (uuid, channelName) {
    var index = channels[channelName].users.indexOf(uuid);
    channels[channelName].users.splice(index, 1);
    var user = clients[uuid];
    index = user.channels.indexOf(channelName);
    user.channels.splice(index, 1);
}

function destroyUser (socketId) {
    if (!socketId) {
        return false;
    }
    var user = findUserBySocketId(socketId);
    if (!user || !user.uuid) {
        return false;
    }
    var channels = getUserChannels(user.uuid);

    channels.forEach(function (channelName) {
        removeUserFromChannel(user.uuid, channelName);
        sendMessageToChannel(channelName, user.username + ' left');
        //send the new users list to all users in the channel
        var users = getChannelUsers(channelName);
        io.to(channelName).emit('channel users list', users);
    });

    removeUser(user);
}

function findUserBySocketId (socketId) {
    return sockets[socketId];
}

function addChannel (channel) {
    channel.users = [];
    channels[channel.name] = channel;
}

function getUserChannels (uuid) {
    return clients[uuid].channels;
}

function sendMessageToChannel (channelName, text) {
    var message = formatChannelMessage(text);
    log.info('sending message', {message: message, channelName: channelName});
    io.to(channelName).emit(
        'new channel message',
        message
    );
    addMessage(channelName, message.text);
}

function channelExists (channelName) {
    return channels[channelName];
}

function socketError (socket, error) {
    //TODO: check for valid type and text values
    socket.emit('chat error', error);
    log.error('chat error', error);
}

function removeUserFromAllChannels (user) {
    var channels = getUserChannels(user.uuid);
    channels.forEach(function (channel) {
        removeUserFromChannel(user.uuid, channel);
        sendMessageToChannel(channel, user.username + ' left');
    });
}

function getChannelUsers (channelName) {
    var users = [];
    channels[channelName].users.forEach(function (uuid) {
        users.push(clients[uuid].username);
    });
    return users;
}

function handleChannelCreate (socket, channel) {
    if (!channel) {
        socketError(socket, {
            type: 'create channel err',
            text: 'Channel not set!'
        });
        return false;
    }
    if (channelExists(channel.name)) {
        socketError(socket, {
            type: 'channel exists',
            text: 'Channel ' + channel.name + ' already exists!'
        });
        return false;
    }
    var user = findUserBySocketId(socket.id);
    if (!user) {
        socketError(socket, {
            type: 'create channel err',
            text: 'Could not find user by this socket\'s id!'
        });
        return false;
    }
    //TODO: remove this for multichannel support
    removeUserFromAllChannels(user);
    joinChannel(socket, user, channel);
}

function handleChannelJoin (socket, user, channel) {
    if (!user || !channel) {
        socketError(socket, {
            type: 'join channel err',
            text: 'User or channel not set!'
        });
        return false;
    }
    if (!channelExists(channel.name)) {
        socketError(socket, {
            type: 'channel does not exist',
            text: 'Channel ' + channel.name + ' does not exist!'
        });
        return false;
    }
    //TODO: remove this for multichannel support
    removeUserFromAllChannels(user);
    if (channels[channel.name] && channels[channel.name].password !== <PASSWORD>) {
        socketError(socket, {
            type: 'join channel err',
            text: 'Could not join channel ' + channel.name + '! Wrong password!'
        });
        return false;
    }
    joinChannel(socket, user, channel);
}

function joinChannel (socket, user, channel) {
    socket.join(channel.name, function (err) {
        if (err) {
            socketError(socket, {
                type: 'join channel err',
                text: 'Could not join channel ' + channel.name + '! Error: ' + err
            });
            return false;
        }
        if (!channelExists(channel.name)) {
            addChannel(channel);
        }
        addUserToChannel(user.uuid, channel.name);
        sendMessageToChannel(channel.name, user.username + ' joined');<commit_msg>removed channel exists check on join, will recreate the channel after a server restart<commit_after>'use strict';

var hat = require('hat'),
    moment = require('moment'),
    log = require('./logger'),
    io;

var channels = {};
var clients = {};
var sockets = {};
var messages = {};

function formatMessage(username, text) {
    return {
        text: moment().format('HH:mm:ss') +
        ' <strong>'+username+'</strong>: ' + text
    };
}

function formatChannelMessage(text) {
    return {
        text: moment().format('HH:mm:ss') + ' ' + text
    };
}

function addMessage(channel, text) {
    log.info('addMessage()', {channel: channel, text: text});
    if (!messages[channel]) {
        messages[channel] = [];
    }
    messages[channel].push(text);
    if (messages[channel].length > 100) {
        messages[channel].splice(0, 1);
    }
    //log.info('messages for ' + channel, messages[channel]);
}

function getMessages(channel) {
    log.info('getMessages('+channel+')');
    var result = [];
    if (messages[channel]) {
        result = messages[channel];
    }
    //log.info('result', result);
    return result;
}

function addUser (user) {
    clients[user.uuid] = user;
    sockets[user.socketId] = clients[user.uuid];
}

function removeUser (user) {
    if (!user || !user.uuid) {
        return false;
    }
    delete clients[user.uuid];
    delete sockets[user.socketId];
}

function addUserToChannel (uuid, channelName) {
    log.info('channels', channels);
    channels[channelName].users.push(uuid);
    clients[uuid].channels.push(channelName);
}

function removeUserFromChannel (uuid, channelName) {
    var index = channels[channelName].users.indexOf(uuid);
    channels[channelName].users.splice(index, 1);
    var user = clients[uuid];
    index = user.channels.indexOf(channelName);
    user.channels.splice(index, 1);
}

function destroyUser (socketId) {
    if (!socketId) {
        return false;
    }
    var user = findUserBySocketId(socketId);
    if (!user || !user.uuid) {
        return false;
    }
    var channels = getUserChannels(user.uuid);

    channels.forEach(function (channelName) {
        removeUserFromChannel(user.uuid, channelName);
        sendMessageToChannel(channelName, user.username + ' left');
        //send the new users list to all users in the channel
        var users = getChannelUsers(channelName);
        io.to(channelName).emit('channel users list', users);
    });

    removeUser(user);
}

function findUserBySocketId (socketId) {
    return sockets[socketId];
}

function addChannel (channel) {
    channel.users = [];
    channels[channel.name] = channel;
}

function getUserChannels (uuid) {
    return clients[uuid].channels;
}

function sendMessageToChannel (channelName, text) {
    var message = formatChannelMessage(text);
    log.info('sending message', {message: message, channelName: channelName});
    io.to(channelName).emit(
        'new channel message',
        message
    );
    addMessage(channelName, message.text);
}

function channelExists (channelName) {
    return channels[channelName];
}

function socketError (socket, error) {
    //TODO: check for valid type and text values
    socket.emit('chat error', error);
    log.error('chat error', error);
}

function removeUserFromAllChannels (user) {
    var channels = getUserChannels(user.uuid);
    channels.forEach(function (channel) {
        removeUserFromChannel(user.uuid, channel);
        sendMessageToChannel(channel, user.username + ' left');
    });
}

function getChannelUsers (channelName) {
    var users = [];
    channels[channelName].users.forEach(function (uuid) {
        users.push(clients[uuid].username);
    });
    return users;
}

function handleChannelCreate (socket, channel) {
    if (!channel) {
        socketError(socket, {
            type: 'create channel err',
            text: 'Channel not set!'
        });
        return false;
    }
    if (channelExists(channel.name)) {
        socketError(socket, {
            type: 'channel exists',
            text: 'Channel ' + channel.name + ' already exists!'
        });
        return false;
    }
    var user = findUserBySocketId(socket.id);
    if (!user) {
        socketError(socket, {
            type: 'create channel err',
            text: 'Could not find user by this socket\'s id!'
        });
        return false;
    }
    //TODO: remove this for multichannel support
    removeUserFromAllChannels(user);
    joinChannel(socket, user, channel);
}

function handleChannelJoin (socket, user, channel) {
    if (!user || !channel) {
        socketError(socket, {
            type: 'join channel err',
            text: 'User or channel not set!'
        });
        return false;
    }
    /*//will not recreate the channel after server restart:
    if (!channelExists(channel.name)) {
        socketError(socket, {
            type: 'channel does not exist',
            text: 'Channel ' + channel.name + ' does not exist!'
        });
        return false;
    }*/
    //TODO: remove this for multichannel support
    removeUserFromAllChannels(user);
    if (channels[channel.name] && channels[channel.name].password !== channel.password) {
        socketError(socket, {
            type: 'join channel err',
            text: 'Could not join channel ' + channel.name + '! Wrong password!'
        });
        return false;
    }
    joinChannel(socket, user, channel);
}

function joinChannel (socket, user, channel) {
    socket.join(channel.name, function (err) {
        if (err) {
            socketError(socket, {
                type: 'join channel err',
                text: 'Could not join channel ' + channel.name + '! Error: ' + err
            });
            return false;
        }
        if (!channelExists(channel.name)) {
            addChannel(channel);
        }
        addUserToChannel(user.uuid, channel.name);
        sendMessageToChannel(channel.name, user.username + ' joined');
{'fraction_non_alphanumeric': 0.13373524666723274, 'fraction_numerical': 0.00118875774815318, 'mean_word_length': 2.7189769497947585, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '559138', 'n_tokens_mistral': 3375, 'n_tokens_neox': 3351, 'n_words': 810}