<commit_before>/* global logger, processWebhookMessage */
import moment from 'moment';

RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler {
	constructor() {
		this.vm = Npm.require('vm');
		this.successResults = [200, 201, 202];
		this.compiledScripts = {};
		this.triggers = {};

		RocketChat.models.Integrations.find({type: 'webhook-outgoing'}).observe({
			added: (record) => {
				this.addIntegration(record);
			},

			changed: (record) => {
				this.removeIntegration(record);
				this.addIntegration(record);
			},

			removed: (record) => {
				this.removeIntegration(record);
			}
		});
	}

	addIntegration(record) {
		logger.outgoing.debug(`Adding the integration ${ record.name } of the event ${ record.event }!`);
		let channels;
		if (record.event && !RocketChat.integrations.outgoingEvents[record.event].use.channel) {
			logger.outgoing.debug('The integration doesnt rely on channels.');
			//We don't use any channels, so it's special ;)
			channels = ['__any'];
		} else if (_.isEmpty(record.channel)) {
			logger.outgoing.debug('The integration had an empty channel property, so it is going on all the public channels.');
			channels = ['all_public_channels'];
		} else {
			logger.outgoing.debug('The integration is going on these channels:', record.channel);
			channels = [].concat(record.channel);
		}

		for (const channel of channels) {
			if (!this.triggers[channel]) {
				this.triggers[channel] = {};
			}

			this.triggers[channel][record._id] = record;
		}
	}

	removeIntegration(record) {
		for (const trigger of Object.values(this.triggers)) {
			delete trigger[record._id];
		}
	}

	isTriggerEnabled(trigger) {
		for (const trig of Object.values(this.triggers)) {
			if (trig[trigger._id]) {
				return trig[trigger._id].enabled;
			}
		}

		return false;
	}

	updateHistory({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMessage, finished, url, httpCallData, httpError, httpResult, error, errorStack }) {
		const history = {
			type: 'outgoing-webhook',
			step
		};

		// Usually is only added on initial insert
		if (integration) {
			history.integration = integration;
		}

		// Usually is only added on initial insert
		if (event) {
			history.event = event;
		}

		if (data) {
			history.data = data;

			if (data.user) {
				history.data.user = _.omit(data.user, ['meta', '$loki', 'services']);
			}

			if (data.room) {
				history.data.room = _.omit(data.room, ['meta', '$loki', 'usernames']);
				history.data.room.usernames = ['this_will_be_filled_in_with_usernames_when_replayed'];
			}
		}

		if (triggerWord) {
			history.triggerWord = triggerWord;
		}

		if (typeof ranPrepareScript !== 'undefined') {
			history.ranPrepareScript = ranPrepareScript;
		}

		if (prepareSentMessage) {
			history.prepareSentMessage = prepareSentMessage;
		}

		if (processSentMessage) {
			history.processSentMessage = processSentMessage;
		}

		if (resultMessage) {
			history.resultMessage = resultMessage;
		}

		if (typeof finished !== 'undefined') {
			history.finished = finished;
		}

		if (url) {
			history.url = url;
		}

		if (typeof httpCallData !== 'undefined') {
			history.httpCallData = httpCallData;
		}

		if (httpError) {
			history.httpError = httpError;
		}

		if (typeof httpResult !== 'undefined') {
			history.httpResult = httpResult;
		}

		if (typeof error !== 'undefined') {
			history.error = error;
		}

		if (typeof errorStack !== 'undefined') {
			history.errorStack = errorStack;
		}

		if (historyId) {
			RocketChat.models.IntegrationHistory.update({ _id: historyId }, { $set: history });
			return historyId;
		} else {
			history._createdAt = new Date();
			return RocketChat.models.IntegrationHistory.insert(Object.assign({ _id: Random.id() }, history));
		}
	}

	//Trigger is the trigger, nameOrId is a string which is used to try and find a room, room is a room, message is a message, and data contains "user_name" if trigger.impersonateUser is truthful.
	sendMessage({ trigger, nameOrId = '', room, message, data }) {
		let user;
		//Try to find the user who we are impersonating
		if (trigger.impersonateUser) {
			user = RocketChat.models.Users.findOneByUsername(data.user_name);
		}

		//If they don't exist (aka the trigger didn't contain a user) then we set the user based upon the
		//configured username for the integration since this is required at all times.
		if (!user) {
			user = RocketChat.models.Users.findOneByUsername(trigger.username);
		}

		let tmpRoom;
		if (nameOrId || trigger.targetRoom) {
			tmpRoom = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: nameOrId || trigger.targetRoom, errorOnEmpty: false }) || room;
		} else {<commit_msg>Allow channel property in the integrations returned content<commit_after>/* global logger, processWebhookMessage */
import moment from 'moment';

RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler {
	constructor() {
		this.vm = Npm.require('vm');
		this.successResults = [200, 201, 202];
		this.compiledScripts = {};
		this.triggers = {};

		RocketChat.models.Integrations.find({type: 'webhook-outgoing'}).observe({
			added: (record) => {
				this.addIntegration(record);
			},

			changed: (record) => {
				this.removeIntegration(record);
				this.addIntegration(record);
			},

			removed: (record) => {
				this.removeIntegration(record);
			}
		});
	}

	addIntegration(record) {
		logger.outgoing.debug(`Adding the integration ${ record.name } of the event ${ record.event }!`);
		let channels;
		if (record.event && !RocketChat.integrations.outgoingEvents[record.event].use.channel) {
			logger.outgoing.debug('The integration doesnt rely on channels.');
			//We don't use any channels, so it's special ;)
			channels = ['__any'];
		} else if (_.isEmpty(record.channel)) {
			logger.outgoing.debug('The integration had an empty channel property, so it is going on all the public channels.');
			channels = ['all_public_channels'];
		} else {
			logger.outgoing.debug('The integration is going on these channels:', record.channel);
			channels = [].concat(record.channel);
		}

		for (const channel of channels) {
			if (!this.triggers[channel]) {
				this.triggers[channel] = {};
			}

			this.triggers[channel][record._id] = record;
		}
	}

	removeIntegration(record) {
		for (const trigger of Object.values(this.triggers)) {
			delete trigger[record._id];
		}
	}

	isTriggerEnabled(trigger) {
		for (const trig of Object.values(this.triggers)) {
			if (trig[trigger._id]) {
				return trig[trigger._id].enabled;
			}
		}

		return false;
	}

	updateHistory({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMessage, finished, url, httpCallData, httpError, httpResult, error, errorStack }) {
		const history = {
			type: 'outgoing-webhook',
			step
		};

		// Usually is only added on initial insert
		if (integration) {
			history.integration = integration;
		}

		// Usually is only added on initial insert
		if (event) {
			history.event = event;
		}

		if (data) {
			history.data = data;

			if (data.user) {
				history.data.user = _.omit(data.user, ['meta', '$loki', 'services']);
			}

			if (data.room) {
				history.data.room = _.omit(data.room, ['meta', '$loki', 'usernames']);
				history.data.room.usernames = ['this_will_be_filled_in_with_usernames_when_replayed'];
			}
		}

		if (triggerWord) {
			history.triggerWord = triggerWord;
		}

		if (typeof ranPrepareScript !== 'undefined') {
			history.ranPrepareScript = ranPrepareScript;
		}

		if (prepareSentMessage) {
			history.prepareSentMessage = prepareSentMessage;
		}

		if (processSentMessage) {
			history.processSentMessage = processSentMessage;
		}

		if (resultMessage) {
			history.resultMessage = resultMessage;
		}

		if (typeof finished !== 'undefined') {
			history.finished = finished;
		}

		if (url) {
			history.url = url;
		}

		if (typeof httpCallData !== 'undefined') {
			history.httpCallData = httpCallData;
		}

		if (httpError) {
			history.httpError = httpError;
		}

		if (typeof httpResult !== 'undefined') {
			history.httpResult = httpResult;
		}

		if (typeof error !== 'undefined') {
			history.error = error;
		}

		if (typeof errorStack !== 'undefined') {
			history.errorStack = errorStack;
		}

		if (historyId) {
			RocketChat.models.IntegrationHistory.update({ _id: historyId }, { $set: history });
			return historyId;
		} else {
			history._createdAt = new Date();
			return RocketChat.models.IntegrationHistory.insert(Object.assign({ _id: Random.id() }, history));
		}
	}

	//Trigger is the trigger, nameOrId is a string which is used to try and find a room, room is a room, message is a message, and data contains "user_name" if trigger.impersonateUser is truthful.
	sendMessage({ trigger, nameOrId = '', room, message, data }) {
		let user;
		//Try to find the user who we are impersonating
		if (trigger.impersonateUser) {
			user = RocketChat.models.Users.findOneByUsername(data.user_name);
		}

		//If they don't exist (aka the trigger didn't contain a user) then we set the user based upon the
		//configured username for the integration since this is required at all times.
		if (!user) {
			user = RocketChat.models.Users.findOneByUsername(trigger.username);
		}

		let tmpRoom;
		if (nameOrId || trigger.targetRoom || message.channel) {
			tmpRoom = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: nameOrId || message.channel || trigger.targetRoom, errorOnEmpty: false }) || room;
		} else {
{'fraction_non_alphanumeric': 0.13076923076923078, 'fraction_numerical': 0.0018711018711018712, 'mean_word_length': 3.796111665004985, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, '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': '935858', 'n_tokens_mistral': 3455, 'n_tokens_neox': 2980, 'n_words': 755}