<commit_before>
u.sequencePlayer = function(node, options) {

	var player;

	// work with just one player
	if(node) {
		player = u.ae(node, "div", {"class":"sequenceplayer"});
	}
	else {
		player = document.createElement("div");
		u.ac(player, "sequenceplayer");
	}

	// playback timer
	player.t_playback = false;
	// default framerate (12 fps)
	player._framerate = 12;

	// additional info passed to function as JSON object
	if(typeof(options) == "object") {
		var argument;
		for(argument in options) {

			switch(argument) {
				case "framerate"		: this._framerate			= options[argument]; break;
			}

		}
	}
	else {
		options = {};
	}

	// load sequence of images
	player.load = function(images, options) {
//		u.bug("load sequence:" + images.length)

		this._load_callback;
		this._autoplay = false;

		// additional info passed to function as JSON object
		if(typeof(options) == "object") {
			var argument;
			for(argument in options) {

				switch(argument) {
					case "load_callback"		: this._load_callback			= options[argument]; break;
					case "autoplay"				: this._autoplay				= options[argument]; break;
				}

			}
		}

		// setup sequence / clean sequence
		this.setup(images);
	}

	// load sequence and play when loaded
	player.loadAndPlay = function(images, options) {

		// set autoplay to true
		if(!options) {
			options = {};
		}
		options.autoplay = true;

		// save options for use when loading is done
		this._options = options;

		// load will automatically invoke play
		this.load(images, options);
	}

	// play currently loaded sequence
	player.play = function(options) {

		this._ended_callback = null;
		this._from = this.sequence._start;
		this._to = this.sequence._end;

		// additional info passed to function as JSON object
		if(typeof(options) == "object") {
			var argument;
			for(argument in options) {

				switch(argument) {
					case "ended_callback"	: this._ended_callback			= options[argument]; break;
					case "framerate"		: this._framerate				= options[argument]; break;

					case "to"				: this._to						= options[argument]; break;
					case "from"				: this._from					= options[argument]; break;
				}

			}
		}

		// playback direction
		if(this._from <= this._to) {
			this._direction = 1;
		}
		else {
			this._direction = -1;
		}

		u.bug("play sequence:" + this._from + " -> " + this._to + "@" + this._framerate + "fps" + " (direction:"+this._direction+")")

		// playback not in initial order
//		if(1 || this._from != this.sequence._start || this._to != this.sequence._end) {
//			u.bug("reorder stack")

			// forward direction
			if(this._direction > 0) {

				// decrease z-index from 4000
				var start_z_index = 4000;

				// loop through entire sequence
				for(i = this.sequence._start; i <= this.sequence._end; i++) {

					// make first two frames visible (for better playback performance)
					if(i == this._from || i == this._from+1) {
						u.as(this._nodes[i], "display", "block", 1);
					}
					else {
						u.as(this._nodes[i], "display", "none", 1);
					}

					// apply decresed z-index
					u.as(this._nodes[i], "zIndex", start_z_index-i, 1);
				}

			}
			// backwards direction
			else {

				// increase z-index from 4000 minus sequence length
				var start_z_index = 4000 - this._nodes.length;

				// loop through entire sequence
				for(i = this.sequence._end; i <= this.sequence._start; i--) {

					// make first two frames visible (for better playback performance)
					if(i == this._from || i == this._from-1) {
						u.as(this._nodes[i], "display", "block", 1);
					}
					else {
						u.as(this._nodes[i], "display", "none", 1);
					}

					// apply increased z-index
					u.as(this._nodes[i], "zIndex", start_z_index+i, 1);
				}
			}
			// for(i = this._from, j = 0; this._direction > 0 ? i <= this._to : i >= this._to; i += this._direction, j++) {
			// }

			// for(i = this.sequence._start, j = this._from; this._direction > 0 ? i <= this._to : i >= this._to; i += this._direction, j++) {
			//
			//
			// // hide all but first frame
			// for(i = 0; i <= this.sequence._end; i++) {
			//
			// 	if(i == this._from) {
			// 		u.as(this._nodes[i], "display", "block", 1);
			// 	}
			// 	else {
			// 		u.as(this._nodes[i], "display", "none", 1);
			// 	}
			// }

			// // keep first two frames visible (for better performance)
			// if(i > 1) {
			// 	u.as(this._nodes[i], "display", "none", 1);
			// }
			// else {
			// 	u.as(this._nodes[i], "display", "block", 1);
			// }

			// set z-index for new order

				// update dom
			this.offsetHeight;

			this._current_frame = this._from;

//		}
		// initial order - reset sequence
		// else {
		//
		// }

		this.playback(true);
	}

	// playback loop - continues until sequence is done
	player.playback = function(start) {

		// don't do anything on first loop
		if(!start) {
			// go to next frame
			this.nextFrame(this._current_frame);
			// set current frame
			this._current_frame = this._current_frame + this._direction;
		}

		// end loop and callback
		if(this._to == this._current_frame) {

			if(typeof(this._ended_callback) == "function") {
				this._ended_callback();
			}
			else if(typeof(this.ended) == "function") {
				this.ended();
			}

		}
		// continue loop
		else {
			this.t_playback = u.t.setTimer(this, this.playback, (1000/this._framerate));
		}

	}

	// hides last frame and reveals next frame below (part of playback handling)
	player.nextFrame = function(frame) {
//			u.bug("nextframe:" + frame)

		// prepare stack - after_next is not next frame, but frame after next frame (to be sure stack is always prepared two frame ahead)
		// this is done, because firefox causes blinking animation, if animation is started with delay
		var after_next = (frame + (this._direction*2));
		// make next frame visible
		if(this._nodes[after_next] && (this._direction > 0 ? after_next <= this._to : after_next >= this._to)) {
//			u.bug("show after_next:" + after_next);
			u.as(this._nodes[after_next], "display", "block");
		}

		// hide current frame
		if(this._nodes[frame]) {
//			u.bug("hide current:" + frame);
			u.as(this._nodes[frame], "display", "none");
		}
	}

	// hides last frame and reveals next frame below (part of playback handling)
	player.prevFrame = function(frame) {
//			u.bug("nextframe:" + frame)

		var after_next = (frame + this._direction);
		var prev = (frame - this._direction);

		u.bug("prev:" + prev);
		u.bug("after_next:" + after_next);

		// hide current frame
		if(this._nodes[prev]) {
			u.bug("show prev:" + prev);
			u.as(this._nodes[prev], "display", "block");

				// make next frame visible
			if(this._nodes[after_next] && (this._direction > 0 ? after_next <= this._to : after_next >= this._to)) {
	//			u.bug("show after_next:" + after_next);
				u.as(this._nodes[after_next], "display", "none");
			}

		}
		// reset entire order to fit prev scenario
		else {

			for(i = this._from; i < this._to; i += this._direction) {
				if(i == this._to || i == this._to-this._direction) {
					u.as(this._nodes[i], "display", "block");
				}
				else {
					u.as(this._nodes[i], "display", "none");
				}
			}

		}

	}

	// TODO
	player.next = function(loop) {

		if(!loop || this._current_frame + this._direction <= this._to) {
			this.nextFrame(this._current_frame);
			this._current_frame = this._current_frame + this._direction;
		}
		else if(loop){
			this.play();
			this.pause();
			this._current_frame = this._current_frame + this._direction;
		}
	}

	// TODO
	player.prev = function(loop) {

		if(!loop || this._current_frame - this._direction >= this._from) {
			this.prevFrame(this._current_frame);
			this._current_frame = this._current_frame - this._direction;
		}
		else if(loop){
			this.prevFrame(this._current_frame);
			this._current_frame = this._to;

			// this.play();
			// this.pause();
		}
	}

	player.resume = function() {
		this.t_playback = u.t.setTimer(this, this.playback, (1000/this._framerate));
	}

	// TODO
	player.pause = function() {
		u.t.resetTimer(this.t_playback);
	}

	// TODO
	player.stop = function() {
		u.t.resetTimer(this.t_playback);
	}

	// prepare animation for playback
	player.setup = function(images) {

//		u.bug("sequence player setup")

		if(this.sequence) {
			this.removeChild(this.sequence);
		}

		// add sequence node
		this.sequence = u.ie(this, "ul", {"class":"sequence"});
		this.sequence.player = this;

		this._images = images;
		this._nodes = new Array();

		this.sequence._start = 0;
		this.sequence._end = this._images.length-1;
		this._current_frame = 0;

		// after preloading, continue setup
		this._setup = function() {

			// stack images to make playback as light as possible
			for(i = 0; i <= this.sequence._end; i++) {

				this._nodes[i] = u.ae(this.sequence, "li", {"style":"background-image: url(" + this._images[i] + ");"});

				// keep first two frames visible (for better performance)
				u.as(this._nodes[i], "display", "none", 1);
			}

			// update dom
			this.offsetHeight;

			if(typeof(this._load_callback) == "function") {
				this._load_callback();
			}
			// or callback to default (loaded)
			else if(typeof(this.loaded) == "function") {
				this.loaded();
			}

			if(this._autoplay) {
			 	this.play(this._options);
			}

		}

		// preload image sequence
		u.preloader(this, this._images, {"callback":this._setup});

	}

	return player;
}

<commit_msg>nextFrame loop corrected<commit_after>
u.sequencePlayer = function(node, options) {

	var player;

	// work with just one player
	if(node) {
		player = u.ae(node, "div", {"class":"sequenceplayer"});
	}
	else {
		player = document.createElement("div");
		u.ac(player, "sequenceplayer");
	}

	// playback timer
	player.t_playback = false;
	// default framerate (12 fps)
	player._framerate = 12;

	// additional info passed to function as JSON object
	if(typeof(options) == "object") {
		var argument;
		for(argument in options) {

			switch(argument) {
				case "framerate"		: this._framerate			= options[argument]; break;
			}

		}
	}
	else {
		options = {};
	}

	// load sequence of images
	player.load = function(images, options) {
//		u.bug("load sequence:" + images.length)

		this._load_callback;
		this._autoplay = false;

		// additional info passed to function as JSON object
		if(typeof(options) == "object") {
			var argument;
			for(argument in options) {

				switch(argument) {
					case "load_callback"		: this._load_callback			= options[argument]; break;
					case "autoplay"				: this._autoplay				= options[argument]; break;
				}

			}
		}

		// setup sequence / clean sequence
		this.setup(images);
	}

	// load sequence and play when loaded
	player.loadAndPlay = function(images, options) {

		// set autoplay to true
		if(!options) {
			options = {};
		}
		options.autoplay = true;

		// save options for use when loading is done
		this._options = options;

		// load will automatically invoke play
		this.load(images, options);
	}

	// play currently loaded sequence
	player.play = function(options) {

		this._ended_callback = null;
		this._from = this.sequence._start;
		this._to = this.sequence._end;

		// additional info passed to function as JSON object
		if(typeof(options) == "object") {
			var argument;
			for(argument in options) {

				switch(argument) {
					case "ended_callback"	: this._ended_callback			= options[argument]; break;
					case "framerate"		: this._framerate				= options[argument]; break;

					case "to"				: this._to						= options[argument]; break;
					case "from"				: this._from					= options[argument]; break;
				}

			}
		}

		// playback direction
		if(this._from <= this._to) {
			this._direction = 1;
		}
		else {
			this._direction = -1;
		}

//		u.bug("play sequence:" + this._from + " -> " + this._to + "@" + this._framerate + "fps" + " (direction:"+this._direction+")")

		// playback not in initial order
//		if(1 || this._from != this.sequence._start || this._to != this.sequence._end) {
//			u.bug("reorder stack")

			// forward direction
			if(this._direction > 0) {

				// decrease z-index from 4000
				var start_z_index = 4000;

				// loop through entire sequence
				for(i = this.sequence._start; i <= this.sequence._end; i++) {

					// make first two frames visible (for better playback performance)
					if(i == this._from || i == this._from+1) {
						u.as(this._nodes[i], "display", "block", 1);
					}
					else {
						u.as(this._nodes[i], "display", "none", 1);
					}

					// apply decresed z-index
					u.as(this._nodes[i], "zIndex", start_z_index-i, 1);
				}

			}
			// backwards direction
			else {

				// increase z-index from 4000 minus sequence length
				var start_z_index = 4000 - this._nodes.length;

				// loop through entire sequence
				for(i = this.sequence._end; i <= this.sequence._start; i--) {

					// make first two frames visible (for better playback performance)
					if(i == this._from || i == this._from-1) {
						u.as(this._nodes[i], "display", "block", 1);
					}
					else {
						u.as(this._nodes[i], "display", "none", 1);
					}

					// apply increased z-index
					u.as(this._nodes[i], "zIndex", start_z_index+i, 1);
				}
			}
			// for(i = this._from, j = 0; this._direction > 0 ? i <= this._to : i >= this._to; i += this._direction, j++) {
			// }

			// for(i = this.sequence._start, j = this._from; this._direction > 0 ? i <= this._to : i >= this._to; i += this._direction, j++) {
			//
			//
			// // hide all but first frame
			// for(i = 0; i <= this.sequence._end; i++) {
			//
			// 	if(i == this._from) {
			// 		u.as(this._nodes[i], "display", "block", 1);
			// 	}
			// 	else {
			// 		u.as(this._nodes[i], "display", "none", 1);
			// 	}
			// }

			// // keep first two frames visible (for better performance)
			// if(i > 1) {
			// 	u.as(this._nodes[i], "display", "none", 1);
			// }
			// else {
			// 	u.as(this._nodes[i], "display", "block", 1);
			// }

			// set z-index for new order

				// update dom
			this.offsetHeight;

			this._current_frame = this._from;

//		}
		// initial order - reset sequence
		// else {
		//
		// }

		this.playback(true);
	}

	// playback loop - continues until sequence is done
	player.playback = function(start) {

		// don't do anything on first loop
		if(!start) {
			// go to next frame
			this.nextFrame(this._current_frame);
			// set current frame
			this._current_frame = this._current_frame + this._direction;
		}

		// end loop and callback
		if(this._to == this._current_frame) {
//			u.bug("end reached:" + typeof(this._ended_callback) + ", " + this.ended + "," + u.nodeId(this))

			if(typeof(this._ended_callback) == "function") {
				this._ended_callback();
			}
			else if(typeof(this.ended) == "function") {
				this.ended();
			}

		}
		// continue loop
		else {
			this.t_playback = u.t.setTimer(this, this.playback, (1000/this._framerate));
		}

	}

	// hides last frame and reveals next frame below (part of playback handling)
	player.nextFrame = function(frame) {
//			u.bug("nextframe:" + frame)

		// prepare stack - after_next is not next frame, but frame after next frame (to be sure stack is always prepared two frame ahead)
		// this is done, because firefox causes blinking animation, if animation is started with delay
		var after_next = (frame + (this._direction*2));
		// make next frame visible
		if(this._nodes[after_next] && (this._direction > 0 ? after_next <= this._to : after_next >= this._to)) {
//			u.bug("show after_next:" + after_next);
			u.as(this._nodes[after_next], "display", "block");
		}

		// hide current frame
		if(this._nodes[frame]) {
//			u.bug("hide current:" + frame);
			u.as(this._nodes[frame], "display", "none");
		}
	}

	// hides last frame and reveals next frame below (part of playback handling)
	player.prevFrame = function(frame) {
//			u.bug("nextframe:" + frame)

		var after_next = (frame + this._direction);
		var prev = (frame - this._direction);

//		u.bug("prev:" + prev);
//		u.bug("after_next:" + after_next);

		// hide current frame
		if(this._nodes[prev]) {
//			u.bug("show prev:" + prev);
			u.as(this._nodes[prev], "display", "block");

				// make next frame visible
			if(this._nodes[after_next] && (this._direction > 0 ? after_next <= this._to : after_next >= this._to)) {
	//			u.bug("show after_next:" + after_next);
				u.as(this._nodes[after_next], "display", "none");
			}

		}
		// reset entire order to fit prev scenario
		else {

			for(i = this._from; i < this._to; i += this._direction) {
				if(i == this._to || i == this._to-this._direction) {
					u.as(this._nodes[i], "display", "block");
				}
				else {
					u.as(this._nodes[i], "display", "none");
				}
			}

		}

	}

	// TODO
	player.next = function(loop) {
//		u.bug("next:" + loop);

		if(!loop || this._current_frame + this._direction <= this._to) {
//			u.bug("more frames:" + this._current_frame)
			this.nextFrame(this._current_frame);
			this._current_frame = this._current_frame + this._direction;

//			u.bug("new current_frame:" + this._current_frame)
		}
		else if(loop) {
//			u.bug("no more frames:" + this._current_frame);

			this.play();
			this.pause();
			this.nextFrame(this._current_frame);
			this._current_frame = this._current_frame + this._direction;
//			u.bug("new current_frame:" + this._current_frame)
		}
	}

	// TODO
	player.prev = function(loop) {
//		u.bug("prev:" + loop);

		if(!loop || this._current_frame - this._direction >= this._from) {
//			u.bug("more frames:" + this._current_frame)

			this.prevFrame(this._current_frame);
			this._current_frame = this._current_frame - this._direction;
//			u.bug("new current_frame:" + this._current_frame)
		}
		else if(loop) {

//			u.bug("no more frames:" + this._current_frame);

			this.prevFrame(this._current_frame);
			this._current_frame = this._to;

//			u.bug("new current_frame:" + this._current_frame)
		}
	}

	player.resume = function() {
		this.t_playback = u.t.setTimer(this, this.playback, (1000/this._framerate));
	}

	// TODO
	player.pause = function() {
		u.t.resetTimer(this.t_playback);
	}

	// TODO
	player.stop = function() {
		u.t.resetTimer(this.t_playback);
	}

	// prepare animation for playback
	player.setup = function(images) {

//		u.bug("sequence player setup")

		if(this.sequence) {
			this.removeChild(this.sequence);
		}

		// add sequence node
		this.sequence = u.ie(this, "ul", {"class":"sequence"});
		this.sequence.player = this;

		this._images = images;
		this._nodes = new Array();

		this.sequence._start = 0;
		this.sequence._end = this._images.length-1;
		this._current_frame = 0;

		// after preloading, continue setup
		this._setup = function() {

			// stack images to make playback as light as possible
			for(i = 0; i <= this.sequence._end; i++) {

				this._nodes[i] = u.ae(this.sequence, "li", {"style":"background-image: url(" + this._images[i] + ");"});

				// keep first two frames visible (for better performance)
				u.as(this._nodes[i], "display", "none", 1);
			}

			// update dom
			this.offsetHeight;

			if(typeof(this._load_callback) == "function") {
				this._load_callback();
			}
			// or callback to default (loaded)
			else if(typeof(this.loaded) == "function") {
				this.loaded();
			}

			if(this._autoplay) {
			 	this.play(this._options);
			}

		}

		// preload image sequence
		u.preloader(this, this._images, {"callback":this._setup});

	}

	return player;
}

<|endoftext|>


<commit_before>/*
 * dbc
 *
 *
 * Copyright (c) 2013 dmccarthy dbenson
 */

'use strict';
var loglet      = require('loglet');
loglet          = loglet('dbc', 'info', '/opt/peat/cloudlet_platform/logs/dbc.log');

module.exports = (function() {
   return {
      assert: function(arg, errorMessage) {
         if (!arg) {
            loglet.error(errorMessage);
            throw errorMessage;
         }
      },
      hasMember: function(obj, memberName) {
         if (!obj.hasOwnProperty(memberName)) {
            loglet.error('DBC violation: Object is missing member: %s', memberName);
            throw new Error('DBC violation: Object is missing member: ' + memberName);

         }
      },
      hasMemberIn: function(obj, memberName, memberValues) {
         if (!obj.hasOwnProperty(memberName)) {
            loglet.error('Object is missing member: %s', memberName);
            throw new Error('Object is missing member: ' + memberName);
         }
         else if (-1 === memberValues.indexOf(obj[memberName])) {
            loglet.error('DBC violation: Object member ( %s ) should be one of the following: %s', memberName, memberValues);
            throw new Error('DBC violation: Object member (' + memberName + ') should be one of the following: '
               + memberValues);
         }
      },
      conditionalHasMember: function(obj, memberName, condition) {
         if (condition){
            if (!obj.hasOwnProperty(memberName)) {
               loglet.error('DBC violation: Object is missing member: %s', memberName);
               throw new Error('DBC violation: Object is missing member: ' + memberName);
            }
         }
      }
   };
}());<commit_msg>added tmp log config<commit_after>/*
 * dbc
 *
 *
 * Copyright (c) 2013 dmccarthy dbenson
 */

'use strict';
var loglet      = require('loglet');
loglet          = loglet.createLogger('dbc', 'info', '/opt/peat/cloudlet_platform/logs/dbc.log');

module.exports = (function() {
   return {
      assert: function(arg, errorMessage) {
         if (!arg) {
            loglet.error(errorMessage);
            throw errorMessage;
         }
      },
      hasMember: function(obj, memberName) {
         if (!obj.hasOwnProperty(memberName)) {
            loglet.error('DBC violation: Object is missing member: %s', memberName);
            throw new Error('DBC violation: Object is missing member: ' + memberName);

         }
      },
      hasMemberIn: function(obj, memberName, memberValues) {
         if (!obj.hasOwnProperty(memberName)) {
            loglet.error('Object is missing member: %s', memberName);
            throw new Error('Object is missing member: ' + memberName);
         }
         else if (-1 === memberValues.indexOf(obj[memberName])) {
            loglet.error('DBC violation: Object member ( %s ) should be one of the following: %s', memberName, memberValues);
            throw new Error('DBC violation: Object member (' + memberName + ') should be one of the following: '
               + memberValues);
         }
      },
      conditionalHasMember: function(obj, memberName, condition) {
         if (condition){
            if (!obj.hasOwnProperty(memberName)) {
               loglet.error('DBC violation: Object is missing member: %s', memberName);
               throw new Error('DBC violation: Object is missing member: ' + memberName);
            }
         }
      }
   };
}());<|endoftext|>


<commit_before>'use babel';

export default {
  config: {
    ansibleLintExecutablePath: {
      title: 'Ansible-Lint Executable Path',
      type: 'string',
      description: 'Path to Ansible-Lint executable (e.g. /usr/bin/ansible-lint) if not in shell env path.',
      default: 'ansible-lint',
    },
    rulesDirDefault: {
      title: 'Additionally use the default rules directories with Ansible-Lint (only if using non-default rules directories).',
      type: 'boolean',
      default: false,
    },
    rulesDirs: {
      title: 'Rules Directories',
      type: 'array',
      description: 'Non-default rules directories to use with Ansible-Lint.',
      default: [''],
      items: {
        type: 'string'
      }
    },
    excludeDirs: {
      title: 'Exclude Directories',
      type: 'array',
      description: 'Absolute path directories to exclude during linting.',
      default: [''],
      items: {
        type: 'string'
      }
    },
    useProjectConfig: {
      title: 'Use project Ansible-Lint config file.',
      type: 'boolean',
      description: 'Use an ansible-lint configuration file named `.ansible-lint` in the root level of the project directory. Overrides other settings besides executable path and blacklist.',
      default: false,
    },
    blacklist: {
      title: 'Exclude Regexp for .yml',
      type: 'string',
      description: 'Regular expression for .yml filenames to ignore (e.g. travis|docker would ignore docker-compose.yml and .travis.yml).',
      default: '',
    },
    ruleSkips: {
      title: 'Tag/Rule Skips',
      type: 'string',
      description: 'List of comma-delimited tags and/or rules to skip when performing checks.',
      default: '',
    },
    timeout: {
      title: 'Linting Timeout',
      type: 'number',
      description: 'Number of seconds to wait on lint attempt before timing out.',
      default: 10,
    },
    displaySeverity: {
      title: 'Display Severity',
      type: 'boolean',
      description: 'Display the severity of the warning inside the message.',
      default: false,
    }
  },

  // activate linter
  activate() {
    const helpers = require('atom-linter');

    // check for ansible-lint >= minimum version
    helpers.exec(atom.config.get('linter-ansible-linting.ansibleLintExecutablePath'), ['-T']).then(output => {
      if (!(/repeatability/.exec(output))) {
        atom.notifications.addWarning(
          'ansible-lint < 3.5 is unsupported. Backwards compatibility should exist, but is not guaranteed.',
          {
            detail: "Please upgrade your version of ansible-lint to >= 3.5.\n",
            dismissable: true
          }
        );
      }
    });
  },

  provideLinter() {
    return {
      name: 'Ansible-Lint',
      grammarScopes: ['source.ansible', 'source.ansible-advanced'],
      scope: 'project',
      lintsOnChange: false,
      lint: (activeEditor) => {
        // setup variables
        const helpers = require('atom-linter');
        const lint_regex = /(.*):(\d+):\s\[E\d{3}\]\s(.*)/;
        const file = activeEditor.getPath();
        const correct_file = new RegExp(file);

        // bail out if this is on the blacklist
        if (atom.config.get('linter-ansible-linting.blacklist') !== '') {
          blacklist = new RegExp(atom.config.get('linter-ansible-linting.blacklist'))
          if (blacklist.exec(file))
            return [];
        }

        // pep8 output and no color
        var args = ['-p', '--nocolor'];

        // add parseable severity flag if requested
        if (atom.config.get('linter-ansible-linting.displaySeverity'))
          args.push('--parseable-severity');

        // use config file if specified
        if (atom.config.get('linter-ansible-linting.useProjectConfig')) {
          // cannot cwd in project path and then add file relative path to args because ansible relies on pathing relative to directory execution for includes
          const project_path = atom.project.relativizePath(file)[0];

          // use ansible-lint config file in root project level
          args.push(...['-c', project_path + '/.ansible-lint'])
        }
        else {
          // skip checks that user has opted to skip
          if (atom.config.get('linter-ansible-linting.ruleSkips') != '')
            args.push(...['-x', atom.config.get('linter-ansible-linting.ruleSkips')])

          // add additional rules directories
          if (atom.config.get('linter-ansible-linting.rulesDirs')[0] !== '') {
            if (atom.config.get('linter-ansible-linting.rulesDirDefault'))
              args.push('-R')

            for (i = 0; i < atom.config.get('linter-ansible-linting.rulesDirs').length; i++)
              args.push(...['-r', atom.config.get('linter-ansible-linting.rulesDirs')[i]]);
          }

          // exclude certain directories from checks
          if (atom.config.get('linter-ansible-linting.excludeDirs')[0] != '')
            for (i = 0; i < atom.config.get('linter-ansible-linting.excludeDirs').length; i++)
              args.push(...['--exclude', atom.config.get('linter-ansible-linting.excludeDirs')[i]]);
        }

        // add file to check
        args.push(file);

        // initialize variable for linter return here for either linter output or errors
        var toReturn = [];

        return helpers.exec(atom.config.get('linter-ansible-linting.ansibleLintExecutablePath'), args, {cwd: require('path').dirname(file), ignoreExitCode: true, timeout: atom.config.get('linter-ansible-linting.timeout') * 1000}).then(output => {
          output.split(/\r?\n/).forEach((line) => {
            const lint_matches = lint_regex.exec(line);
            const correct_file_matches = correct_file.exec(line);

            // check for normal linter checks output
            if (lint_matches != null && correct_file_matches != null) {
              toReturn.push({
                severity: 'warning',
                excerpt: lint_matches[3],
                location: {
                  file: file,
                  position: [[Number.parseInt(lint_matches[2]) - 1, 0], [Number.parseInt(lint_matches[2]) - 1, 1]],
                },
              });
            }
            // check for linting issues in other files
            else if (lint_matches != null) {
              toReturn.push({
                severity: 'warning',
                excerpt: lint_matches[3],
                location: {
                  file: lint_matches[1],
                  position: [[Number.parseInt(lint_matches[2]) - 1, 0], [Number.parseInt(lint_matches[2]) - 1, 1]],
                },
              });
            }
          });
          return toReturn;
        })
        .catch(error => {
          // check for unusual issues with playbook files
          const missing_file_matches = /WARNING: Couldn't open (.*) - No such file or directory/.exec(error.message);
          const unreadable_file_matches = /the file_name (.*) does not exist, or is not readable|Could not find or access '(.*)'|error occurred while trying to read the file '(.*)'/.exec(error.message);
          const yaml_syntax_matches = /Syntax Error while loading YAML/.exec(error.message);
          const syntax_matches = /(?:raise Ansible(Parser)?Error|Syntax Error while loading YAML|Couldn't parse task at|AttributeError)/.exec(error.message);
          const vault_matches = /vault password.*decrypt/.exec(error.message);
          const stdin_matches = /\.dirname/.exec(error.message);

          // check for missing file or directory
          if (missing_file_matches != null) {
            toReturn.push({
              severity: 'error',
              excerpt: 'Missing file ' + missing_file_matches[1] + '. Please fix before continuing linter use.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for unreadable file
          else if (unreadable_file_matches != null) {
            // the unreadable filename might be in either 1 or 2 depending upon the message which depends upon the version of ansible-lint
            unreadable_file = unreadable_file_matches[1] == null ? unreadable_file_matches[2] : unreadable_file_matches[1]

            toReturn.push({
              severity: 'error',
              excerpt: unreadable_file + ' is unreadable or not a file. Please fix before continuing linter use.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for yaml syntax issue
          else if (yaml_syntax_matches != null) {
            // capture file and line info
            const file_matches = /The error appears to be in '(.*)':/.exec(error.message);
            const range_matches = /line\s(\d+),\scolumn\s(\d+)/.exec(error.message);

            toReturn.push({
              severity: 'error',
              excerpt: 'YAML syntax error.',
              location: {
                file: file_matches[1],
                position: [[Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2]) - 1], [Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2])]],
              },
            });
          }
          // check for syntax issue
          else if (syntax_matches != null) {
            toReturn.push({
              severity: 'error',
              excerpt: 'This file, an include, or role, has an Ansible syntax error. Please fix before continuing linter use.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for vault encrypted file
          else if (vault_matches != null) {
            toReturn.push({
              severity: 'info',
              excerpt: 'File must be decrypted with ansible-vault prior to linting.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for stdin lint attempt
          else if (stdin_matches != null) {
            toReturn.push({
              severity: 'info',
              excerpt: 'Ansible-Lint cannot reliably lint on stdin due to nonexistent pathing on includes and roles. Please save this playbook to your filesystem.',
              location: {
                file: 'Save this playbook.',
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // output other errors directly to Atom notification display
          else {
            atom.notifications.addError(
              'An unexpected error with ansible, ansible-lint, linter-ansible-linting, atom, linter, and/or your playbook, has occurred.',
              {
                detail: error.message
              }
            );
          };
          return toReturn;
        });
      }
    };
  }
};
<commit_msg>notify details on ansible syntax errors<commit_after>'use babel';

export default {
  config: {
    ansibleLintExecutablePath: {
      title: 'Ansible-Lint Executable Path',
      type: 'string',
      description: 'Path to Ansible-Lint executable (e.g. /usr/bin/ansible-lint) if not in shell env path.',
      default: 'ansible-lint',
    },
    rulesDirDefault: {
      title: 'Additionally use the default rules directories with Ansible-Lint (only if using non-default rules directories).',
      type: 'boolean',
      default: false,
    },
    rulesDirs: {
      title: 'Rules Directories',
      type: 'array',
      description: 'Non-default rules directories to use with Ansible-Lint.',
      default: [''],
      items: {
        type: 'string'
      }
    },
    excludeDirs: {
      title: 'Exclude Directories',
      type: 'array',
      description: 'Absolute path directories to exclude during linting.',
      default: [''],
      items: {
        type: 'string'
      }
    },
    useProjectConfig: {
      title: 'Use project Ansible-Lint config file.',
      type: 'boolean',
      description: 'Use an ansible-lint configuration file named `.ansible-lint` in the root level of the project directory. Overrides other settings besides executable path and blacklist.',
      default: false,
    },
    blacklist: {
      title: 'Exclude Regexp for .yml',
      type: 'string',
      description: 'Regular expression for .yml filenames to ignore (e.g. travis|docker would ignore docker-compose.yml and .travis.yml).',
      default: '',
    },
    ruleSkips: {
      title: 'Tag/Rule Skips',
      type: 'string',
      description: 'List of comma-delimited tags and/or rules to skip when performing checks.',
      default: '',
    },
    timeout: {
      title: 'Linting Timeout',
      type: 'number',
      description: 'Number of seconds to wait on lint attempt before timing out.',
      default: 10,
    },
    displaySeverity: {
      title: 'Display Severity',
      type: 'boolean',
      description: 'Display the severity of the warning inside the message.',
      default: false,
    }
  },

  // activate linter
  activate() {
    const helpers = require('atom-linter');

    // check for ansible-lint >= minimum version
    helpers.exec(atom.config.get('linter-ansible-linting.ansibleLintExecutablePath'), ['-T']).then(output => {
      if (!(/repeatability/.exec(output))) {
        atom.notifications.addWarning(
          'ansible-lint < 3.5 is unsupported. Backwards compatibility should exist, but is not guaranteed.',
          {
            detail: "Please upgrade your version of ansible-lint to >= 3.5.\n",
            dismissable: true
          }
        );
      }
    });
  },

  provideLinter() {
    return {
      name: 'Ansible-Lint',
      grammarScopes: ['source.ansible', 'source.ansible-advanced'],
      scope: 'project',
      lintsOnChange: false,
      lint: (activeEditor) => {
        // setup variables
        const helpers = require('atom-linter');
        const lint_regex = /(.*):(\d+):\s\[E\d{3}\]\s(.*)/;
        const file = activeEditor.getPath();
        const correct_file = new RegExp(file);

        // bail out if this is on the blacklist
        if (atom.config.get('linter-ansible-linting.blacklist') !== '') {
          blacklist = new RegExp(atom.config.get('linter-ansible-linting.blacklist'))
          if (blacklist.exec(file))
            return [];
        }

        // pep8 output and no color
        var args = ['-p', '--nocolor'];

        // add parseable severity flag if requested
        if (atom.config.get('linter-ansible-linting.displaySeverity'))
          args.push('--parseable-severity');

        // use config file if specified
        if (atom.config.get('linter-ansible-linting.useProjectConfig')) {
          // cannot cwd in project path and then add file relative path to args because ansible relies on pathing relative to directory execution for includes
          const project_path = atom.project.relativizePath(file)[0];

          // use ansible-lint config file in root project level
          args.push(...['-c', project_path + '/.ansible-lint'])
        }
        else {
          // skip checks that user has opted to skip
          if (atom.config.get('linter-ansible-linting.ruleSkips') != '')
            args.push(...['-x', atom.config.get('linter-ansible-linting.ruleSkips')])

          // add additional rules directories
          if (atom.config.get('linter-ansible-linting.rulesDirs')[0] !== '') {
            if (atom.config.get('linter-ansible-linting.rulesDirDefault'))
              args.push('-R')

            for (i = 0; i < atom.config.get('linter-ansible-linting.rulesDirs').length; i++)
              args.push(...['-r', atom.config.get('linter-ansible-linting.rulesDirs')[i]]);
          }

          // exclude certain directories from checks
          if (atom.config.get('linter-ansible-linting.excludeDirs')[0] != '')
            for (i = 0; i < atom.config.get('linter-ansible-linting.excludeDirs').length; i++)
              args.push(...['--exclude', atom.config.get('linter-ansible-linting.excludeDirs')[i]]);
        }

        // add file to check
        args.push(file);

        // initialize variable for linter return here for either linter output or errors
        var toReturn = [];

        return helpers.exec(atom.config.get('linter-ansible-linting.ansibleLintExecutablePath'), args, {cwd: require('path').dirname(file), ignoreExitCode: true, timeout: atom.config.get('linter-ansible-linting.timeout') * 1000}).then(output => {
          output.split(/\r?\n/).forEach((line) => {
            const lint_matches = lint_regex.exec(line);
            const correct_file_matches = correct_file.exec(line);

            // check for normal linter checks output
            if (lint_matches != null && correct_file_matches != null) {
              toReturn.push({
                severity: 'warning',
                excerpt: lint_matches[3],
                location: {
                  file: file,
                  position: [[Number.parseInt(lint_matches[2]) - 1, 0], [Number.parseInt(lint_matches[2]) - 1, 1]],
                },
              });
            }
            // check for linting issues in other files
            else if (lint_matches != null) {
              toReturn.push({
                severity: 'warning',
                excerpt: lint_matches[3],
                location: {
                  file: lint_matches[1],
                  position: [[Number.parseInt(lint_matches[2]) - 1, 0], [Number.parseInt(lint_matches[2]) - 1, 1]],
                },
              });
            }
          });
          return toReturn;
        })
        .catch(error => {
          // check for unusual issues with playbook files
          const missing_file_matches = /WARNING: Couldn't open (.*) - No such file or directory/.exec(error.message);
          const unreadable_file_matches = /the file_name (.*) does not exist, or is not readable|Could not find or access '(.*)'|error occurred while trying to read the file '(.*)'/.exec(error.message);
          const yaml_syntax_matches = /Syntax Error while loading YAML/.exec(error.message);
          const syntax_matches = /(?:raise Ansible(Parser)?Error|Couldn't parse task at|AttributeError)/.exec(error.message);
          const vault_matches = /vault password.*decrypt/.exec(error.message);
          const stdin_matches = /\.dirname/.exec(error.message);

          // check for missing file or directory
          if (missing_file_matches != null) {
            toReturn.push({
              severity: 'error',
              excerpt: 'Missing file ' + missing_file_matches[1] + '. Please fix before continuing linter use.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for unreadable file
          else if (unreadable_file_matches != null) {
            // the unreadable filename might be in either 1 or 2 depending upon the message which depends upon the version of ansible-lint
            unreadable_file = unreadable_file_matches[1] == null ? unreadable_file_matches[2] : unreadable_file_matches[1]

            toReturn.push({
              severity: 'error',
              excerpt: unreadable_file + ' is unreadable or not a file. Please fix before continuing linter use.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for yaml syntax issue
          else if (yaml_syntax_matches != null) {
            // capture file and line info
            const file_matches = /The error appears to be in '(.*)':/.exec(error.message);
            const range_matches = /line\s(\d+),\scolumn\s(\d+)/.exec(error.message);

            toReturn.push({
              severity: 'error',
              excerpt: 'YAML syntax error.',
              location: {
                file: file_matches[1],
                position: [[Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2]) - 1], [Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2])]],
              },
            });
          }
          // check for syntax issue
          else if (syntax_matches != null) {
            // capture file and line info
            const file_matches = /The error appears to be in '(.*)':/.exec(error.message);
            const range_matches = /line\s(\d+),\scolumn\s(\d+)/.exec(error.message);

            toReturn.push({
              severity: 'error',
              excerpt: 'Ansible syntax error.',
              location: {
                file: file_matches[1],
                position: [[Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2]) - 1], [Number.parseInt(range_matches[1]) - 1, Number.parseInt(range_matches[2])]],
              },
            });
          }
          // check for vault encrypted file
          else if (vault_matches != null) {
            toReturn.push({
              severity: 'info',
              excerpt: 'File must be decrypted with ansible-vault prior to linting.',
              location: {
                file: file,
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // check for stdin lint attempt
          else if (stdin_matches != null) {
            toReturn.push({
              severity: 'info',
              excerpt: 'Ansible-Lint cannot reliably lint on stdin due to nonexistent pathing on includes and roles. Please save this playbook to your filesystem.',
              location: {
                file: 'Save this playbook.',
                position: [[0, 0], [0, 1]],
              },
            });
          }
          // output other errors directly to Atom notification display
          else {
            atom.notifications.addError(
              'An unexpected error with ansible, ansible-lint, linter-ansible-linting, atom, linter, and/or your playbook, has occurred.',
              {
                detail: error.message
              }
            );
          };
          return toReturn;
        });
      }
    };
  }
};
<|endoftext|>


<commit_before>var STATE = {};

var GLOBAL = {
	WIN: 7,
	LOSE: 5,
	LIMIT: 13
}

var db = firebase.database();
var gref = db.ref('globals');
var missionRef = db.ref(MISSION_PATH);

function main(){

	gref.once('value', function(snapshot){
		var val = snapshot.val();
		GLOBAL.WIN = val.win || 10;
		GLOBAL.LOSE = val.lose || 10;
		GLOBAL.LIMIT = val.limit || 10;
	}).then((done) => {

		missionRef.orderByChild('timestamp').on('child_added', function(snapshot){
			var data = snapshot.val();
			var reducer = REDUCERS[data.action];
			if(reducer){
				STATE = reducer(clone(STATE), data);
			}
			var renderer = RENDERERS[data.action];
			if(renderer){
				renderer(STATE, data);
			}
		});

	});
}
<commit_msg>Time limit LOL<commit_after>var STATE = {};

var GLOBAL = {
	WIN: 7,
	LOSE: 5,
	LIMIT: 27
}

var db = firebase.database();
var gref = db.ref('globals');
var missionRef = db.ref(MISSION_PATH);

function main(){

	gref.once('value', function(snapshot){
		var val = snapshot.val();
		GLOBAL.WIN = val.win || 10;
		GLOBAL.LOSE = val.lose || 10;
		GLOBAL.LIMIT = 27;
	}).then((done) => {

		missionRef.orderByChild('timestamp').on('child_added', function(snapshot){
			var data = snapshot.val();
			var reducer = REDUCERS[data.action];
			if(reducer){
				STATE = reducer(clone(STATE), data);
			}
			var renderer = RENDERERS[data.action];
			if(renderer){
				renderer(STATE, data);
			}
		});

	});
}
<|endoftext|>


<commit_before>"use strict";

/*
 *  npm-boilerplate
 *  http://github.com/sdeering/npm-boilerplate
 *  A good starting point for your new Node.js NPM packages.
 */

/**
 * Module dependencies.
 */

var path = require( 'path' )
  , utils = require( path.resolve( path.join( __dirname, 'utils' ) ) )
  , _ = require( 'lodash' );

/**
 * Module constructor.
 */

function MyModule( config ) {

  this.init( config );

};

/**
 * Module init.
 */

MyModule.prototype.init = function( config ) {

  //Specify module default config here
  var defaults = {

      defaultValue1: true,
      defaultValue2: true

  };

  //override config defaults if specified
  this.config = _.extend(defaults, config);

  //for example
  this.numbers = [ 1, 2, 3 ];

};

/**
 * Module public API example function - multiply
 */

MyModule.prototype.multiply = function( multiplyBy ) {

  var mutipliedNumbers = [];

  for ( var i = 0; i < this.numbers.length; i++ ) {

    mutipliedNumbers.push( this.numbers[i] * multiplyBy );

  }

  return mutipliedNumbers;

};

/**
 * Test module utils functions work.
 */

MyModule.prototype.stripHTML = function( html ) {

  return utils.stripHTML( html );

};

/**
 * Example function to get config
 */

MyModule.prototype.getConfig = function() {

  return this.config;

};

/**
 * Export default singleton.
 *
 * @api public
 */

exports = module.exports = new MyModule();

/**
 * Expose module constructor.
 */

// module.exports = MyModule;

// exports.MyModule = MyModule;
<commit_msg>tidy up<commit_after>"use strict";

/*
 *  npm-boilerplate
 *  http://github.com/sdeering/npm-boilerplate
 *  A good starting point for your new Node.js NPM packages.
 */

/**
 * Module dependencies.
 */

var path = require( 'path' )
  , utils = require( path.resolve( path.join( __dirname, 'utils' ) ) )
  , _ = require( 'lodash' );

/**
 * Module constructor.
 */

function MyModule( config ) {

  this.init( config );

};

/**
 * Module init.
 */

MyModule.prototype.init = function( config ) {

  //Specify module default config here
  var defaults = {

      defaultValue1: true,
      defaultValue2: true

  };

  //override config defaults if specified
  this.config = _.extend(defaults, config);

  //for example
  this.numbers = [ 1, 2, 3 ];

};

/**
 * Module public API example function - multiply
 */

MyModule.prototype.multiply = function( multiplyBy ) {

  var mutipliedNumbers = [];

  for ( var i = 0; i < this.numbers.length; i++ ) {

    mutipliedNumbers.push( this.numbers[i] * multiplyBy );

  }

  return mutipliedNumbers;

};

/**
 * Test module utils functions work.
 */

MyModule.prototype.stripHTML = function( html ) {

  return utils.stripHTML( html );

};

/**
 * Example function to get config
 */

MyModule.prototype.getConfig = function() {

  return this.config;

};

/**
 * Export default singleton.
 *
 * @api public
 */

exports = module.exports = new MyModule();
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var crypto = require('crypto');
var fs = require('fs');
var config = require('./config');
var _ = require('lodash');
var async = require('async');
var tracklet = {};
var token_auth = config.token_auth;
var domain = config.domain;

//todo add /piwik/ before index.php in url when moving away from local php server
//todo set up more accurate geolocation http://piwik.org/faq/how-to/#faq_164
//todo currently uses name & password for login but name is not unique, change to email

tracklet.init = function(params) {

   async.waterfall([
         async.apply(initCheck, params),
         createUser,
         createSite,
         getSiteId,
         setAccess
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 200) {
               console.log('Success');
            }
         }
      });
};

tracklet.track = function(params) {
   async.waterfall([
         async.apply(trackCheck, params),
         getSiteId,
         track
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 204) {
               console.log('Success');
            }
         }
      });
};

tracklet.remove = function(params) {

   async.waterfall([
         async.apply(deleteCheck, params),
         deleteUser,
         getSiteId,
         deleteSite
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 200) {
               console.log('Success');
            }
         }
      });
};

function trackCheck(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth="+token_auth;
   var re = /http:\/\//gi;
   if(!params.cloudlet) {
      callback('missing cloudletID');
   } else if (!params.app || !params.company || !params.object) {
      callback('must have at least one tracking parameter');
   } else {
      request(url, function (error, response, body) {
         if (error) {
            callback(error);
         }

         var sites = _.values(JSON.parse(body));

         var siteIds = _.map(sites, function (n) {
            return (n.main_url.replace(re, ''));
         });

         if (!_.includes(siteIds, params.cloudlet)) {
            callback('Cloudlet ID not valid: ' + params.cloudlet);
         } else {
            callback(null, params);
         }
      });
   }
}

function track(params, callback) {
   var url = domain+'piwik.php?rec=1&send_image=0&apiv=1&new_visit=1&';
   var arr = [];

   arr.push('urlref=http://' + params.app);
   arr.push('uid=' + params.company);
   arr.push('c_n=' + params.object);
   arr.push('idsite=' + params.idSite);

   var id = crypto.createHash("md5").update(params.company+params.app).digest("hex").slice(0, -16);
   arr.push('_id='+id);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else {
         callback(null, response.statusCode);
      }
   })

}

function initCheck(params, callback) {

   if(!params.name || !params.password || !params.email || !params.cloudlet || !params.access) {
      callback('missing parameters');
   } else {

      async.parallel([
            async.apply(emailCheck, params),
            async.apply(cloudletCheck, params)
         ],
         function(err, result){
            if (err) {
               console.log('Error: ' + err);
            } else {
               callback(null, params);
            }
         });
   }
}

function emailCheck(params, callback) {

   var url = domain+"index.php?module=API&method=UsersManager.userEmailExists&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userEmail=' + params.email);
   request(url + arr.join('&'), function (error, response, body) {
      if (error) {
         callback(error);
      }

      if (JSON.parse(body).value === true) {
         callback('an account with this email already exists: ' + params.email);
      } else {
         callback(null, params);
      }

   });
}

function cloudletCheck(params, callback) {

   var url = domain+"index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth="+token_auth;
   var re = /http:\/\//gi;

   request(url, function (error, response, body) {
      if (error) {
         callback(error);
      }

      var sites = _.values(JSON.parse(body));

      var siteIds = _.map(sites, function (n) {
         return (n.main_url.replace(re, ''));
      });

      if (_.includes(siteIds, params.cloudlet)) {
         callback('an account with this cloudlet ID already exists: ' + params.cloudlet);
      } else {
         callback(null, params);
      }
   });

}

function createUser(params, callback) {
   var url = domain+"index.php?module=API&method=UsersManager.addUser&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);
   arr.push('password=' + params.password);
   arr.push('email=' + params.email);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }

   })

}

function createSite(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.addSite&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('siteName=' + params.email);
   arr.push('urls=' + params.cloudlet);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }
   })
}

function setAccess(params, callback) {

   var url = domain+"index.php?module=API&method=UsersManager.setUserAccess&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);
   arr.push('access=' + params.access);
   arr.push('idSites=' + params.idSite);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, response.statusCode);
      }
   })
}

function getSiteId(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.getSitesIdFromSiteUrl&format=JSON&token_auth="+token_auth+"&";
   var arr =[];
   arr.push('url=http://' + params.cloudlet);

   request(url + arr.join('&'), function (error, response, body) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         params.idSite = parseInt(JSON.parse(body)[0].idsite);
         callback(null, params);
      }
   })
}

function deleteCheck(params, callback) {

   if(!params.email || !params.cloudlet) {
      callback('missing parameters');
   } else {

      async.parallel([
            async.apply(emailCheck2, params),
            async.apply(cloudletCheck2, params)
         ],
         function(err, result){
            if (err) {
               console.log('Error: ' + err);
            } else {
               callback(null, params);
            }
         });
   }
}

function emailCheck2(params, callback) {

   var url = domain+"index.php?module=API&method=UsersManager.userExists&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);
   request(url + arr.join('&'), function (error, response, body) {
      if (error) {
         callback(error);
      }

      if (JSON.parse(body).value === false) {
         callback('an account with this email does not exist: ' + params.email);
      } else {
         callback(null, params);
      }

   });
}

function cloudletCheck2(params, callback) {

   var url = domain+"index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth="+token_auth;
   var re = /http:\/\//gi;

   request(url, function (error, response, body) {
      if (error) {
         callback(error);
      }

      var sites = _.values(JSON.parse(body));

      var siteIds = _.map(sites, function (n) {
         return (n.main_url.replace(re, ''));
      });

      if (!_.includes(siteIds, params.cloudlet)) {
         callback('an account with this cloudlet ID does not exist: ' + params.cloudlet);
      } else {
         callback(null, params);
      }
   });

}

function deleteUser(params, callback) {
   var url = domain+"index.php?module=API&method=UsersManager.deleteUser&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }
   })
}

function deleteSite(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.deleteSite&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('idSite=' + params.idSite);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, response.statusCode);
      }

   })
}

module.exports = tracklet;

<commit_msg>consolidate checking functions<commit_after>'use strict';

var request = require('request');
var crypto = require('crypto');
var fs = require('fs');
var config = require('./config');
var _ = require('lodash');
var async = require('async');
var tracklet = {};
var token_auth = config.token_auth;
var domain = config.domain;

//todo add /piwik/ before index.php in url when moving away from local php server
//todo set up more accurate geolocation http://piwik.org/faq/how-to/#faq_164
//todo currently uses name & password for login but name is not unique, change to email

tracklet.init = function(params) {

   async.waterfall([
         async.apply(initCheck, params),
         createUser,
         createSite,
         getSiteId,
         setAccess
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 200) {
               console.log('Success');
            }
         }
      });
};

tracklet.track = function(params) {
   async.waterfall([
         async.apply(trackCheck, params),
         getSiteId,
         track
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 204) {
               console.log('Success');
            }
         }
      });
};

tracklet.remove = function(params) {

   async.waterfall([
         async.apply(deleteCheck, params),
         deleteUser,
         getSiteId,
         deleteSite
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 200) {
               console.log('Success');
            }
         }
      });
};

function trackCheck(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth="+token_auth;
   var re = /http:\/\//gi;
   if(!params.cloudlet) {
      callback('missing cloudletID');
   } else if (!params.app || !params.company || !params.object) {
      callback('must have at least one tracking parameter');
   } else {
      request(url, function (error, response, body) {
         if (error) {
            callback(error);
         }

         var sites = _.values(JSON.parse(body));

         var siteIds = _.map(sites, function (n) {
            return (n.main_url.replace(re, ''));
         });

         if (!_.includes(siteIds, params.cloudlet)) {
            callback('Cloudlet ID not valid: ' + params.cloudlet);
         } else {
            callback(null, params);
         }
      });
   }
}

function track(params, callback) {
   var url = domain+'piwik.php?rec=1&send_image=0&apiv=1&new_visit=1&';
   var arr = [];

   arr.push('urlref=http://' + params.app);
   arr.push('uid=' + params.company);
   arr.push('c_n=' + params.object);
   arr.push('idsite=' + params.idSite);

   var id = crypto.createHash("md5").update(params.company+params.app).digest("hex").slice(0, -16);
   arr.push('_id='+id);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else {
         callback(null, response.statusCode);
      }
   })

}

function initCheck(params, callback) {

   if(!params.name || !params.password || !params.email || !params.cloudlet || !params.access) {
      callback('missing parameters');
   } else {

      async.parallel([
            async.apply(emailCheck, params),
            async.apply(cloudletCheck, params)
         ],
         function(err, result){
            if (err) {
               console.log('Error: ' + err);
            } else {
               callback(null, params);
            }
         });
   }
}

function createUser(params, callback) {
   var url = domain+"index.php?module=API&method=UsersManager.addUser&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);
   arr.push('password=' + params.password);
   arr.push('email=' + params.email);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }

   })

}

function createSite(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.addSite&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('siteName=' + params.email);
   arr.push('urls=' + params.cloudlet);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }
   })
}

function setAccess(params, callback) {

   var url = domain+"index.php?module=API&method=UsersManager.setUserAccess&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);
   arr.push('access=' + params.access);
   arr.push('idSites=' + params.idSite);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, response.statusCode);
      }
   })
}

function getSiteId(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.getSitesIdFromSiteUrl&format=JSON&token_auth="+token_auth+"&";
   var arr =[];
   arr.push('url=http://' + params.cloudlet);

   request(url + arr.join('&'), function (error, response, body) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         params.idSite = parseInt(JSON.parse(body)[0].idsite);
         callback(null, params);
      }
   })
}

function deleteCheck(params, callback) {

   if(!params.email || !params.cloudlet) {
      callback('missing parameters');
   } else {

      async.parallel([
            async.apply(emailCheck, params),
            async.apply(cloudletCheck, params)
         ],
         function(err, result){
            if (err) {
               console.log('Error: ' + err);
            } else {
               callback(null, params);
            }
         });
   }
}

function emailCheck(params, callback) {
   var url;
   var arr = [];

   if(_.size(params) === 5) {
      url = domain+"index.php?module=API&method=UsersManager.userEmailExists&format=JSON&token_auth="+token_auth+"&";
      arr = [];

      arr.push('userEmail=' + params.email);
      request(url + arr.join('&'), function (error, response, body) {
         if (error) {
            callback(error);
         }

         if (JSON.parse(body).value === true) {
            callback('an account with this email already exists: ' + params.email);
         } else {
            callback(null, params);
         }

      });
   } else if (_.size(params) === 2) {
      url = domain+"index.php?module=API&method=UsersManager.userExists&format=JSON&token_auth="+token_auth+"&";
      arr = [];

      arr.push('userLogin=' + params.email);
      request(url + arr.join('&'), function (error, response, body) {
         if (error) {
            callback(error);
         }

         if (JSON.parse(body).value === false) {
            callback('an account with this email does not exist: ' + params.email);
         } else {
            callback(null, params);
         }

      });
   }
}

function cloudletCheck(params, callback) {

   var url = domain+"index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth="+token_auth;
   var re = /http:\/\//gi;

   request(url, function (error, response, body) {
      if (error) {
         callback(error);
      }

      var sites = _.values(JSON.parse(body));

      var siteIds = _.map(sites, function (n) {
         return (n.main_url.replace(re, ''));
      });

      if (_.includes(siteIds, params.cloudlet)) {
         if(_.size(params) === 5) {
            callback('an account with this cloudlet ID already exists: ' + params.cloudlet);
         }
         if(_.size(params) === 2) {
            callback(null, params);
         }
      } else {
         if(_.size(params) === 5) {
            callback(null, params);
         }
         if(_.size(params) === 2) {
            callback('an account with this cloudlet ID does not exist: ' + params.cloudlet);
         }

      }
   });
}

function deleteUser(params, callback) {
   var url = domain+"index.php?module=API&method=UsersManager.deleteUser&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('userLogin=' + params.email);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, params);
      }
   })
}

function deleteSite(params, callback) {
   var url = domain+"index.php?module=API&method=SitesManager.deleteSite&format=JSON&token_auth="+token_auth+"&";
   var arr = [];

   arr.push('idSite=' + params.idSite);

   request(url + arr.join('&'), function (error, response) {
      if (error) {
         callback(error);
      } else if (response.statusCode === 200) {
         callback(null, response.statusCode);
      }

   })
}

module.exports = tracklet;

<|endoftext|>