<commit_before>/* global module, require, User, UserSettings, UserService, Message, Room, actionUtil */

/**
 * MessageController
 *
 * @description :: Server-side logic for managing messages
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

'use strict';

var moment = require('moment');
var actionUtil = require('../../node_modules/sails/lib/hooks/blueprints/actionUtil');

// POST /message
// Create a new message. We're overriding the blueprint route provided by sails in order to do
// some custom things.
exports.create = function (req, res) {
	var userId = req.session.userId;
	var roomId = req.param('room');

	// TODO if author is not a member of the roomId, cancel
	var text = sanitizeMessage(req.param('text'));
	if (!text || !text.length) {
		return res.badRequest();
	}
	else if (/^\/nick\s+/i.test(text)) { // Change the current user's nick

		var newNick = text.match(/\/nick\s+([\w\s\-\.]{1,20})/i);
		if (newNick) {
			User.findOne(userId).exec(function (error, user) { // find the user in the db (don't want to use session version)
				var currentNick = user.nick;
				user.nick = newNick[1];
				user.save() // save the model with the updated nick
					.then(function () {
						User.publishUpdate(userId, {nick: user.nick});

						RoomMember.find().where({user: userId}).exec(function (err, roomMembers) {
							var rooms = _.pluck(roomMembers, 'room');
							RoomService.messageRooms(rooms, currentNick + ' changed their handle to ' + user.nick);
						});
					})
					.catch(function () {
						// TODO error handling
					});
			});
		}
		res.ok();
	}
	else if (/^\/(up|down)\s+/i.test(text)) { // Karma system, unfinished

		var nickMatches = text.match(/^\/(?:up|down)\s+@?(\w+)/i);
		if (!nickMatches) return;
		var nick = nickMatches[1];
		var rating = text.match(/up/i) ? 1 : -1;

		// TODO would need to limit how many times a user can vote

		RoomMember.find().where({room: roomId}).populate('user').exec(function (error, roomMembers) {
			var matchingMember = _.find(roomMembers, function (roomMember) {
				return roomMember.user.nick == nick;
			});

			if (!matchingMember) return;

			if (typeof matchingMember.rating === 'undefined') {
				matchingMember.rating = 0;
			}

			matchingMember.rating += rating;
			// Not actually going to save right now as this is not completed
			//matchingMember.save();
			res.ok();
		});
	}
	else if (/^\/topic/i.test(text)) { // Change room topic

		RoomMember.findOne({room: roomId, user: userId}).populate('user').exec(function (error, roomMember) {
			if (error) return res.serverError(error);
			if (!roomMember) return res.forbidden();

			if (roomMember.role == 'administrator' || roomMember.role == 'moderator') {

				var topicMatches = text.match(/\/topic\s+(.+)/i);
				var topic = topicMatches ? topicMatches[1].substr(0, 200) : null;

				Room.update(roomId, {topic: topic}).exec(function (error, room) {
					if (error) return res.serverError(error);
					if (!room) return res.notFound();

					var room = room[0];
					var message = roomMember.user.nick + (topic ? ' changed the topic to "' + topic + '"' : ' cleared the topic');

					Room.publishUpdate(room.id, room);
					RoomService.messageRoom(roomId, message);

					res.ok();
				});
			}
			else {
				res.forbidden();
			}

		});
	}
	else if (/^\/roll/i.test(text)) {
		var matches = text.match(/\/roll\s+(.+)/i);
		var roll = matches ? matches[1] : null;

		// Determine outcome
		var rollOutcome;

		if(_.isNumber(+roll) && !_.isNaN(+roll)) {
			var max = +roll;
			rollOutcome = 'rolled ' + Math.ceil(Math.random() * max) + ' out of ' + max;
		}
		// d20 case for D&D nerds
		//else if(/^d\d{1,4}/i.test(roll)) { // a dice roll
		//	rollOutcome = 'rolled a ' + roll + ' for ' + 100;
		//}
		else { // Doesn't fit any of our cases
			return;
		}

		User.findOne(userId).exec(function (error, user) {
			Message.create({
				room: roomId,
				author: null,
				text: user.nick + ' ' + rollOutcome
			}).exec(function (error, message) {
				res.ok(); // send back the message to the original caller
				broadcastMessage(message);
			});
		});
	}
	else { // base case, a regular chat message
		// Create a message model object in the db
		Message.create({ // the model to add into db
			room: roomId,
			author: userId,
			text: text
		}).exec(function (error, message) {
			res.ok(message); // send back the message to the original caller
			broadcastMessage(message);
		});
	}
};

// PUT /message/:id
// Update a message (the edit functionality)
exports.update = function (req, res) {
	var messageEditWindowSeconds = 30;
	var pk = actionUtil.requirePk(req);

	Message.findOne(pk).exec(function (error, message) {
		if (error) return res.serverError(error);<commit_msg>me command<commit_after>/* global module, require, User, UserSettings, UserService, Message, Room, actionUtil */

/**
 * MessageController
 *
 * @description :: Server-side logic for managing messages
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

'use strict';

var moment = require('moment');
var actionUtil = require('../../node_modules/sails/lib/hooks/blueprints/actionUtil');

// POST /message
// Create a new message. We're overriding the blueprint route provided by sails in order to do
// some custom things.
exports.create = function (req, res) {
	var userId = req.session.userId;
	var roomId = req.param('room');

	// TODO if author is not a member of the roomId, cancel
	var text = sanitizeMessage(req.param('text'));
	if (!text || !text.length) {
		return res.badRequest();
	}
	else if (/^\/nick\s+/i.test(text)) { // Change the current user's nick

		var newNick = text.match(/\/nick\s+([\w\s\-\.]{1,20})/i);
		if (newNick) {
			User.findOne(userId).exec(function (error, user) { // find the user in the db (don't want to use session version)
				var currentNick = user.nick;
				user.nick = newNick[1];
				user.save() // save the model with the updated nick
					.then(function () {
						User.publishUpdate(userId, {nick: user.nick});

						RoomMember.find().where({user: userId}).exec(function (err, roomMembers) {
							var rooms = _.pluck(roomMembers, 'room');
							RoomService.messageRooms(rooms, currentNick + ' changed their handle to ' + user.nick);
						});
					})
					.catch(function () {
						// TODO error handling
					});
			});
		}
		res.ok();
	}
	else if (/^\/(up|down)\s+/i.test(text)) { // Karma system, unfinished

		var nickMatches = text.match(/^\/(?:up|down)\s+@?(\w+)/i);
		if (!nickMatches) return;
		var nick = nickMatches[1];
		var rating = text.match(/up/i) ? 1 : -1;

		// TODO would need to limit how many times a user can vote

		RoomMember.find().where({room: roomId}).populate('user').exec(function (error, roomMembers) {
			var matchingMember = _.find(roomMembers, function (roomMember) {
				return roomMember.user.nick == nick;
			});

			if (!matchingMember) return;

			if (typeof matchingMember.rating === 'undefined') {
				matchingMember.rating = 0;
			}

			matchingMember.rating += rating;
			// Not actually going to save right now as this is not completed
			//matchingMember.save();
			res.ok();
		});
	}
	else if (/^\/topic/i.test(text)) { // Change room topic

		RoomMember.findOne({room: roomId, user: userId}).populate('user').exec(function (error, roomMember) {
			if (error) return res.serverError(error);
			if (!roomMember) return res.forbidden();

			if (roomMember.role == 'administrator' || roomMember.role == 'moderator') {

				var topicMatches = text.match(/\/topic\s+(.+)/i);
				var topic = topicMatches ? topicMatches[1].substr(0, 200) : null;

				Room.update(roomId, {topic: topic}).exec(function (error, room) {
					if (error) return res.serverError(error);
					if (!room) return res.notFound();

					var room = room[0];
					var message = roomMember.user.nick + (topic ? ' changed the topic to "' + topic + '"' : ' cleared the topic');

					Room.publishUpdate(room.id, room);
					RoomService.messageRoom(roomId, message);

					res.ok();
				});
			}
			else {
				res.forbidden();
			}

		});
	}
	else if (/^\/roll/i.test(text)) {
		var matches = text.match(/\/roll\s+(.+)/i);
		var roll = matches ? matches[1] : null;

		// Determine outcome
		var rollOutcome;

		if(_.isNumber(+roll) && !_.isNaN(+roll)) {
			var max = +roll;
			rollOutcome = 'rolled ' + Math.ceil(Math.random() * max) + ' out of ' + max;
		}
		// d20 case for D&D nerds
		//else if(/^d\d{1,4}/i.test(roll)) { // a dice roll
		//	rollOutcome = 'rolled a ' + roll + ' for ' + 100;
		//}
		else { // Doesn't fit any of our cases
			return;
		}

		User.findOne(userId).exec(function (error, user) {
			Message.create({
				room: roomId,
				author: null,
				text: user.nick + ' ' + rollOutcome
			}).exec(function (error, message) {
				res.ok(); // send back the message to the original caller
				broadcastMessage(message);
			});
		});
	}
	else if(/^\/me/i.test(text)){
		User.findOne(userId).exec(function (error, user) {
			Message.create({
				room: roomId,
				author: null,
				text: user.nick +  text.substring(3) //hardcoded to simply nuke the '/me' part and keep the space for free
			}).exec(function (error, message) {
				res.ok();
				broadcastMessage(message);
			})
		});
	}
	else { // base case, a regular chat message
		// Create a message model object in the db
		Message.create({ // the model to add into db
			room: roomId,
			author: userId,
			text: text
		}).exec(function (error, message) {
			res.ok(message); // send back the message to the original caller
			broadcastMessage(message);
		});
	}
};

// PUT /message/:id
// Update a message (the edit functionality)
exports.update = function (req, res) {
	var messageEditWindowSeconds = 30;
	var pk = actionUtil.requirePk(req);

	Message.findOne(pk).exec(function (error, message) {
		if (error) return res.serverError(error);
{'fraction_non_alphanumeric': 0.16553057279479091, 'fraction_numerical': 0.004985247736290568, 'mean_word_length': 3.095833333333333, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '5432618', 'n_tokens_mistral': 3742, 'n_tokens_neox': 3196, 'n_words': 875}