<commit_before>"use strict";

module.exports = function(imports) {

    let express = imports.modules.express;
    let ObjectId = imports.modules.mongoose.Types.ObjectId;
    let Promise = imports.modules.Promise;
    let util = imports.util;

    let handler = util.handler;
    let requireLogin = util.requireLogin;
    let requireAdmin = util.requireAdmin;
    let audienceQuery = util.hiddenGroups.audienceQuery;

    let Chat = imports.models.Chat;
    let User = imports.models.User;
    let Group = imports.models.Group;

    let router = express.Router();

    // TODO: separate this into separate requests for group and private chats
    router.post("/chats", requireLogin, handler(function*(req, res) {

        if (req.body.type == "private") {
            // private chat

            let otherUser = yield User.findOne({
                _id: req.body.otherUser,
            });
            if (!otherUser) {
                return res.status(400).end("That user does not exist");
            }

            let users = [
                req.user._id,
                otherUser._id,
            ];

            // check to see if already exists
            if ((yield Chat.count({
                    isTwoPeople: true,
                    "audience.users": users,
                })) > 0) {
                return res.status(400).end("This chat already exists");
            }


            let chat = yield Chat.create({
                audience: {
                    groups: [],
                    users: users,
                },
                isTwoPeople: true
            });

            // TODO: rename this stuff for the new client
            res.json(chat);

        } else {
            // group chat

            if (req.body.name.length >= 20) { // name character limit
                return res.status(400).end("The chat name has to be 19 characters or fewer");
                // TODO: get rid of this...
            }

            let chat = yield Chat.create({
                name: util.normalizeDisplayedText(req.body.name),
                audience: req.body.audience,
                isTwoPeople: false,
            });

            res.json(chat);
        }

    }));

    router.get("/chats", requireLogin, handler(function*(req, res) {

        // find a chat that has said user as a member
        let chats = yield Chat.find(audienceQuery(req.user), {
                _id: 1,
                name: 1,
                audience: 1,
                isTwoPeople: 1,
                updated_at: 1
            })
            .slice("messages", [0, 1])
            .sort("-updated_at")
            .populate("audience.users audience.groups")
            .exec();
        // ^ the code above gets the latest message from the chat (for previews in iOS and Android) and orders the list by most recent.

        res.json(chats);

    }));

    router.get("/chats/id/:chatId/messages", requireLogin, handler(function*(req, res) {
        // TODO: maybe in the future combine this with getUsersInChat to improve performance
<commit_msg>Populate chat members on creation<commit_after>"use strict";

module.exports = function(imports) {

    let express = imports.modules.express;
    let ObjectId = imports.modules.mongoose.Types.ObjectId;
    let Promise = imports.modules.Promise;
    let util = imports.util;

    let handler = util.handler;
    let requireLogin = util.requireLogin;
    let requireAdmin = util.requireAdmin;
    let audienceQuery = util.hiddenGroups.audienceQuery;

    let Chat = imports.models.Chat;
    let User = imports.models.User;
    let Group = imports.models.Group;

    let router = express.Router();

    // TODO: separate this into separate requests for group and private chats
    router.post("/chats", requireLogin, handler(function*(req, res) {

        if (req.body.type == "private") {
            // private chat

            let otherUser = yield User.findOne({
                _id: req.body.otherUser,
            });
            if (!otherUser) {
                return res.status(400).end("That user does not exist");
            }

            let users = [
                req.user._id,
                otherUser._id,
            ];

            // check to see if already exists
            if ((yield Chat.count({
                    isTwoPeople: true,
                    "audience.users": users,
                })) > 0) {
                return res.status(400).end("This chat already exists");
            }


            let chat = yield Chat.create({
                audience: {
                    groups: [],
                    users: users,
                },
                isTwoPeople: true
            });

            chat.audience.users = Promise.all(chat.audience.users.map(userId => (
                User.findOne({
                    _id: userId,
                })
            )));

            res.json(chat);

        } else {
            // group chat

            if (req.body.name.length >= 20) { // name character limit
                return res.status(400).end("The chat name has to be 19 characters or fewer");
                // TODO: get rid of this...
            }

            let chat = yield Chat.create({
                name: util.normalizeDisplayedText(req.body.name),
                audience: req.body.audience,
                isTwoPeople: false,
            });

            chat.audience.users = yield Promise.all(chat.audience.users.map(userId => (
                User.findOne({
                    _id: userId,
                })
            )));

            chat.audience.groups = yield Promise.all(chat.audience.groups.map(groupId => (
                Group.findOne({
                    _id: groupId,
                })
            )));

            res.json(chat);
        }

    }));

    router.get("/chats", requireLogin, handler(function*(req, res) {

        // find a chat that has said user as a member
        let chats = yield Chat.find(audienceQuery(req.user), {
                _id: 1,
                name: 1,
                audience: 1,
                isTwoPeople: 1,
                updated_at: 1
            })
            .slice("messages", [0, 1])
            .sort("-updated_at")
            .populate("audience.users audience.groups")
            .exec();
        // ^ the code above gets the latest message from the chat (for previews in iOS and Android) and orders the list by most recent.

        res.json(chats);

    }));

    router.get("/chats/id/:chatId/messages", requireLogin, handler(function*(req, res) {
        // TODO: maybe in the future combine this with getUsersInChat to improve performance

{'fraction_non_alphanumeric': 0.10807565295706995, 'fraction_numerical': 0.006304413089162414, 'mean_word_length': 1.458671586715867, 'pattern_counts': {'":': 2, '<': 3, '<?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': '863073', 'n_tokens_mistral': 1806, 'n_tokens_neox': 1683, 'n_words': 467}