<commit_before>/* KAAE ACTIONS (c) 2016 QXIP BV */

import _ from 'lodash';
import mustache from 'mustache';
import config from './config';
import fs from 'fs';

var debug = true;
var hlimit = config.kaae.history ? config.kaae.history : 10;

export default function (server,actions,payload) {

	/* Email Settings */
	if (config.settings.email.active) {
		var email   = require("emailjs");
		var email_server  = email.server.connect({
		   user:    config.settings.email.user,
		   password:<PASSWORD>,
		   host:    config.settings.email.host,
		   ssl:     config.settings.email.ssl
		}, function(err, message) { server.log(['status', 'info', 'Kaae', 'email'], err || message); });
		// server.smtp.debug(100);
	}

	/* Image Report Settings */
	if (config.settings.report) {
		/* Image Report Settings */
		if (config.settings.report.active && config.settings.email.active) {
			try {
				var Horseman = require('node-horseman');
				var horseman = new Horseman();
			} catch(err) {
				server.log(['status', 'info', 'KaaE'],'Horseman and PhantomJS required! '+err);
				server.log(['status', 'info', 'KaaE'],'Install Horseman: "npm install -g node-horseman"');
			};
		} else {
			server.log(['status', 'info', 'KaaE'],'Action Report requires Email Settings! Reports Disabled.');
		}
	}

	/* Slack Settings */
	if (config.settings.slack.active) {
		var Slack   = require("node-slack");
		var slack = new Slack(config.settings.slack.hook);
	}

	/* Internal Support Functions */
	var tmpHistory = function(type,message) {
		// Keep history stack of latest alarms (temp)
		server.kaaeStore.push({id:new Date(), action: type, message: message});
		// Rotate local stack
		if (server.kaaeStore.length > hlimit) { server.kaaeStore.shift(); }
	}

	/* ES Indexing Functions */
	var esHistory = function(type,message,loglevel,payload) {
		var client = server.plugins.elasticsearch.client;
		if (!loglevel) { var loglevel = "INFO"; };
		if (!payload) { var payload = {} };
	        server.log(['status', 'info', 'KaaE'],'Storing Alarm to ES with type:'+type);
		var indexDate = '-' + new Date().toISOString().substr(0, 10).replace(/-/g, '.');
		var index_name = config.es.alarm_index ? config.es.alarm_index + indexDate : 'watcher_alarms' + indexDate;
	        client.create({
	          index: index_name,
	          type: type,
	          body: {
			"@timestamp" : new Date().toISOString(),
			"level" : loglevel,
			"message" : message,
			"action" : type,
			"payload" : payload

		  }
	        }).then(function (resp) {
	           // if (debug) console.log(resp);
	        }, function (err,resp) {
	            console.trace(err,resp);
	        });
	}


	/* Loop Actions */
	_.forOwn(actions, function(action, key) {

	        server.log(['status', 'info', 'KaaE'],'Processing action: '+key);

						/* ***************************************************************************** */
		      	/*
						*   "console" : {
						*      "priority" : "DEBUG",
						*      "message" : "Average {{payload.aggregations.avg.value}}"
						*    }
		      	*/

           					if(_.has(action, 'console')) {
							var priority = action.console.priority ? action.console.priority : "INFO";
							var message = action.console.message ? action.console.message : "{{ payload }}";
						  	server.log(['status', 'info', 'KaaE'],'Console Payload: '+ JSON.stringify(payload));
							esHistory(key,message,priority,payload);
            					}

						/* ***************************************************************************** */
		      	/*
						*   "email" : {
						*      "to" : "root@localhost",
						*      "from" : "k<EMAIL>",
						*      "subject" : "Alarm Title",
						*      "priority" : "high",
						*      "body" : "Series Alarm {{ payload._id}}: {{payload.hits.total}}",
						*      "stateless" : false
						*	    }<commit_msg>Fix for issue #41<commit_after>/* KAAE ACTIONS (c) 2016 QXIP BV */

import _ from 'lodash';
import mustache from 'mustache';
import config from './config';
import fs from 'fs';

var debug = true;
var hlimit = config.kaae.history ? config.kaae.history : 10;

export default function (server,actions,payload) {

	/* Email Settings */
	if (config.settings.email.active) {
		var email   = require("emailjs");
		var email_server  = email.server.connect({
		   user:    config.settings.email.user,
		   password:<PASSWORD>,
		   host:    config.settings.email.host,
		   ssl:     config.settings.email.ssl
		}, function(err, message) { server.log(['status', 'info', 'Kaae', 'email'], err || message); });
		// server.smtp.debug(100);
	}

	/* Image Report Settings */
	if (config.settings.report) {
		/* Image Report Settings */
		if (config.settings.report.active && config.settings.email.active) {
			try {
				var Horseman = require('node-horseman');
				var horseman = new Horseman();
			} catch(err) {
				server.log(['status', 'info', 'KaaE'],'Horseman and PhantomJS required! '+err);
				server.log(['status', 'info', 'KaaE'],'Install Horseman: "npm install -g node-horseman"');
			};
		} else {
			server.log(['status', 'info', 'KaaE'],'Action Report requires Email Settings! Reports Disabled.');
		}
	}

	/* Slack Settings */
	if (config.settings.slack.active) {
		var Slack   = require("node-slack");
		var slack = new Slack(config.settings.slack.hook);
	}

	/* Internal Support Functions */
	var tmpHistory = function(type,message) {
		// Keep history stack of latest alarms (temp)
		server.kaaeStore.push({id:new Date(), action: type, message: message});
		// Rotate local stack
		if (server.kaaeStore.length > hlimit) { server.kaaeStore.shift(); }
	}

	/* ES Indexing Functions */
	var esHistory = function(type,message,loglevel,payload) {
		var client = server.plugins.elasticsearch.client;
		if (!loglevel) { var loglevel = "INFO"; };
		if (!payload) { var payload = {} };
	        server.log(['status', 'info', 'KaaE'],'Storing Alarm to ES with type:'+type);
		var indexDate = '-' + new Date().toISOString().substr(0, 10).replace(/-/g, '.');
		var index_name = config.es.alarm_index ? config.es.alarm_index + indexDate : 'watcher_alarms' + indexDate;
	        client.create({
	          index: index_name,
	          type: type,
	          body: {
			"@timestamp" : new Date().toISOString(),
			"level" : loglevel,
			"message" : message,
			"action" : type,
			"payload" : payload

		  }
	        }).then(function (resp) {
	           // if (debug) console.log(resp);
	        }, function (err,resp) {
	            console.trace(err,resp);
	        });
	}


	/* Loop Actions */
	_.forOwn(actions, function(action, key) {

	        server.log(['status', 'info', 'KaaE'],'Processing action: '+key);

						/* ***************************************************************************** */
		      	/*
						*   "console" : {
						*      "priority" : "DEBUG",
						*      "message" : "Average {{payload.aggregations.avg.value}}"
						*    }
		      	*/

           					if(_.has(action, 'console')) {
							var priority = action.console.priority ? action.console.priority : "INFO";
							var formatter_c = action.console.message ? action.console.message : "{{ payload }}";
							var message = mustache.render(formatter_c, {"payload":payload});
						  	server.log(['status', 'info', 'KaaE'],'Console Payload: '+ JSON.stringify(payload));
							esHistory(key,message,priority,payload);
            					}

						/* ***************************************************************************** */
		      	/*
						*   "email" : {
						*      "to" : "<EMAIL>@localhost",
						*      "from" : "k<EMAIL>",
						*      "subject" : "Alarm Title",
						*      "priority" : "high",
						*      "body" : "Series Alarm {{ payload._id}}: {{payload.hits.total}}",
						*      "stateless" : false
						*	    }
{'fraction_non_alphanumeric': 0.20585579775570748, 'fraction_numerical': 0.003353540564942603, 'mean_word_length': 2.8405151064883607, 'pattern_counts': {'":': 1, '<': 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': '881545', 'n_tokens_mistral': 2834, 'n_tokens_neox': 2379, 'n_words': 519}