<commit_before>'use strict';

/*
 * carry gets energy and brings it to the storage
 *
 * Moves to the 'targetId', picks up energy from container or dropped,
 * move back to storage, on meeting other creeps the energy is transferred,
 * energy is transferred to other structures, too.
 */

roles.carry = {};

roles.carry.buildRoad = true;
roles.carry.flee = true;

roles.carry.boostActions = ['capacity'];

roles.carry.settings = {
  param: ['energyCapacityAvailable'],
  prefixString: {
    300: '',
    550: 'W',
  },
  layoutString: 'MC',
  amount: config.carry.sizes,
  maxLayoutAmount: 1,
};

roles.carry.updateSettings = function(room, creep) {
  if (creep.helper) {
    return {
      prefixString: config.buildRoad.buildToOtherMyRoom ? 'W' : '',
      layoutString: 'MC',
      amount: {
        0: [3, 3], // RCL 1
        550: [4, 4], // RCL 2
        800: [6, 6], // RCL 3
        1300: [11, 11], // RCL 4
        1800: [15, 15], // RCL 5
        2300: [21, 21], // RCL 6
      },
    };
  }
};

roles.carry.checkHelperEmptyStorage = function(creep) {
  // Fix blocked helpers due to empty structure in the room where we get the energy from
  if (creep.room.name === creep.memory.routing.targetRoom) {
    const targetStructure = Game.getObjectById(creep.memory.routing.targetId);
    if (targetStructure === null) {
      creep.suicide();
      return;
    }

    if (targetStructure.structureType === STRUCTURE_STORAGE) {
      creep.say('storage');
      if (targetStructure.store.energy === 0) {
        creep.log('Suiciding the storage I should get the energy from is empty');
        creep.suicide();
      }
    }
  }
};

roles.carry.handleMisplacedSpawn = function(creep) {
  // Misplaced spawn
  // TODO Somehow ugly and maybe better somewhere else
  if (creep.inBase() && (creep.room.memory.misplacedSpawn || creep.room.controller.level < 3)) {
    //     creep.say('cmis', true);
    if (creep.carry.energy > 0) {
      const structure = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {
        filter: (object) => object.energy < object.energyCapacity,
      });
      if (structure) {
        creep.moveTo(structure, {
          ignoreCreeps: true,
        });
        creep.transfer(structure, RESOURCE_ENERGY);
        return true;
      }
    } else {
      const targetId = creep.memory.routing.targetId;

      const source = creep.room.memory.position.creep[targetId];
      // TODO better the position from the room memory
      if (source !== null) {
        const sourcePos = new RoomPosition(source.x, source.y, source.roomName);
        creep.moveTo(sourcePos, {
          ignoreCreeps: true,
        });
        if (creep.pos.getRangeTo(sourcePos) > 1) {
          return true;
        }
      }
    }
    return false;
  }
};

roles.carry.preMove = function(creep, directions) {
  roles.carry.checkHelperEmptyStorage(creep);

  if (roles.carry.handleMisplacedSpawn(creep)) {
    return true;
  }

  if (!creep.room.controller) {
    const target = creep.findClosestSourceKeeper();
    if (target !== null) {
      const range = creep.pos.getRangeTo(target);
      if (range > 6) {
        creep.memory.routing.reverse = false;
      }
      if (range < 6) {
        creep.memory.routing.reverse = true;
      }
    }
  }

  // TODO When does this happen? (Not on path?) - Handle better
  if (!directions) {
    creep.say('No directions');
    return false;
  }

  let reverse = false;
  if (!creep.memory.routing.reverse) {
    reverse = creep.checkForTransfer(directions.forwardDirection);
    if (!reverse && creep.isStuck() && directions.backwardDirection) {
      const adjacentPos = creep.pos.getAdjacentPosition(directions.backwardDirection);
      if (adjacentPos.isValid()) {
        const creeps = adjacentPos.lookFor(LOOK_CREEPS);
        if (creeps.length > 0 && creeps[0].memory && creeps[0].memory.routing && creeps[0].memory.routing.targetId !== creep.memory.routing.targetId) {
          reverse = true;
        }
      }
    }
  }

  if (creep.checkEnergyTransfer()) {
    reverse = true;
    if (creep.inBase()) {
      const transferred = creep.transferToStructures();
      if (transferred) {
        if (transferred.moreStructures) {
          return true;
        }
        reverse = creep.carry.energy - transferred.transferred > 0;
      } else if (creep.memory.routing.pathPos === 0 && !(creep.room.storage && creep.room.storage.my && creep.room.storage.isActive())) {
        creep.drop(RESOURCE_ENERGY);
        reverse = false;

        let resourceAtPosition = 0;
        const resources = creep.pos.lookFor(LOOK_RESOURCES);
        for (const resource of resources) {
          resourceAtPosition += resource.amount;
        }
        let amount = creep.room.getHarvesterAmount();
        amount += Math.floor(resourceAtPosition / config.carry.callHarvesterPerResources);
        creep.room.checkRoleToSpawn('harvester', amount, 'harvester');
      }
    }
    if (directions.backwardDirection && directions.backwardDirection !== null) {
      const transferred = creep.transferToCreep(directions.backwardDirection);
      reverse = !transferred;
    }
  }

  reverse = creep.pickupWhileMoving(reverse);
  if (reverse) {
    //     creep.log('reverse');
    directions.direction = directions.backwardDirection;
  } else {
    //     creep.log('not reverse');
    directions.direction = directions.forwardDirection;
  }
  creep.memory.routing.reverse = reverse;

  if (!directions.direction) {
    return false;
  }
  const posForward = creep.pos.getAdjacentPosition(directions.direction);
  const structures = posForward.lookFor(LOOK_STRUCTURES);
  for (const structure of structures) {
    if (structure.structureType === STRUCTURE_ROAD) {
      continue;
    }
    if (structure.structureType === STRUCTURE_CONTAINER) {
      continue;
    }
    if (structure.structureType === STRUCTURE_RAMPART && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_SPAWN && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_STORAGE && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_LINK && structure.my) {
      continue;
    }

    creep.dismantle(structure);
    creep.say('dismantle');
    break;
  }
};

roles.carry.action = function(creep) {
  // TODO log when this happens, carry is getting energy from the source
  // creep.log('ACTION');
  const source = Game.getObjectById(creep.memory.routing.targetId);
  if (source === null) {
    creep.say('sfener');
    creep.memory.routing.reached = false;
    creep.memory.routing.reverse = true;

    const sources = creep.pos.findInRange(FIND_SOURCES, 3);
    if (sources.length > 0) {
      creep.memory.routing.targetId = sources[0].id;
      return true;
    }

    const resource = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
    if (resource !== null) {
      creep.memory.routing.targetId = resource.id;
      // TODO Use pathfinder
      creep.moveTo(resource);
      creep.pickup(resource, resource.amount - 1);
      return true;
    }
  }
  // TODO this should be last position => reverse - In preMove make sure a reverse stays if it is set here
  let reverse = false;
  reverse = creep.pickupWhileMoving(reverse);

  if (!reverse) {
    creep.harvest(source);
  }

  if (!creep.room.controller) {
    const target = creep.findClosestSourceKeeper();
    if (target !== null) {
      const range = creep.pos.getRangeTo(target);
      if (range < 5) {
        delete creep.memory.routing.reached;
        creep.memory.routing.reverse = true;
      }
    }
  }

  creep.memory.routing.reached = false;
  creep.memory.routing.reverse = true;

  return true;
};

roles.carry.execute = function(creep) {
  // creep.log('Execute!!!');
  const target = Game.getObjectById(creep.memory.routing.targetId);
  if (target === null) {
    delete creep.memory.routing.targetId;
  }
};
<commit_msg>check source for truthiness, not just !== null<commit_after>'use strict';

/*
 * carry gets energy and brings it to the storage
 *
 * Moves to the 'targetId', picks up energy from container or dropped,
 * move back to storage, on meeting other creeps the energy is transferred,
 * energy is transferred to other structures, too.
 */

roles.carry = {};

roles.carry.buildRoad = true;
roles.carry.flee = true;

roles.carry.boostActions = ['capacity'];

roles.carry.settings = {
  param: ['energyCapacityAvailable'],
  prefixString: {
    300: '',
    550: 'W',
  },
  layoutString: 'MC',
  amount: config.carry.sizes,
  maxLayoutAmount: 1,
};

roles.carry.updateSettings = function(room, creep) {
  if (creep.helper) {
    return {
      prefixString: config.buildRoad.buildToOtherMyRoom ? 'W' : '',
      layoutString: 'MC',
      amount: {
        0: [3, 3], // RCL 1
        550: [4, 4], // RCL 2
        800: [6, 6], // RCL 3
        1300: [11, 11], // RCL 4
        1800: [15, 15], // RCL 5
        2300: [21, 21], // RCL 6
      },
    };
  }
};

roles.carry.checkHelperEmptyStorage = function(creep) {
  // Fix blocked helpers due to empty structure in the room where we get the energy from
  if (creep.room.name === creep.memory.routing.targetRoom) {
    const targetStructure = Game.getObjectById(creep.memory.routing.targetId);
    if (targetStructure === null) {
      creep.suicide();
      return;
    }

    if (targetStructure.structureType === STRUCTURE_STORAGE) {
      creep.say('storage');
      if (targetStructure.store.energy === 0) {
        creep.log('Suiciding the storage I should get the energy from is empty');
        creep.suicide();
      }
    }
  }
};

roles.carry.handleMisplacedSpawn = function(creep) {
  // Misplaced spawn
  // TODO Somehow ugly and maybe better somewhere else
  if (creep.inBase() && (creep.room.memory.misplacedSpawn || creep.room.controller.level < 3)) {
    //     creep.say('cmis', true);
    if (creep.carry.energy > 0) {
      const structure = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {
        filter: (object) => object.energy < object.energyCapacity,
      });
      if (structure) {
        creep.moveTo(structure, {
          ignoreCreeps: true,
        });
        creep.transfer(structure, RESOURCE_ENERGY);
        return true;
      }
    } else {
      const targetId = creep.memory.routing.targetId;

      const source = creep.room.memory.position.creep[targetId];
      // TODO better the position from the room memory
      if (source) {
        const sourcePos = new RoomPosition(source.x, source.y, source.roomName);
        creep.moveTo(sourcePos, {
          ignoreCreeps: true,
        });
        if (creep.pos.getRangeTo(sourcePos) > 1) {
          return true;
        }
      }
    }
    return false;
  }
};

roles.carry.preMove = function(creep, directions) {
  roles.carry.checkHelperEmptyStorage(creep);

  if (roles.carry.handleMisplacedSpawn(creep)) {
    return true;
  }

  if (!creep.room.controller) {
    const target = creep.findClosestSourceKeeper();
    if (target !== null) {
      const range = creep.pos.getRangeTo(target);
      if (range > 6) {
        creep.memory.routing.reverse = false;
      }
      if (range < 6) {
        creep.memory.routing.reverse = true;
      }
    }
  }

  // TODO When does this happen? (Not on path?) - Handle better
  if (!directions) {
    creep.say('No directions');
    return false;
  }

  let reverse = false;
  if (!creep.memory.routing.reverse) {
    reverse = creep.checkForTransfer(directions.forwardDirection);
    if (!reverse && creep.isStuck() && directions.backwardDirection) {
      const adjacentPos = creep.pos.getAdjacentPosition(directions.backwardDirection);
      if (adjacentPos.isValid()) {
        const creeps = adjacentPos.lookFor(LOOK_CREEPS);
        if (creeps.length > 0 && creeps[0].memory && creeps[0].memory.routing && creeps[0].memory.routing.targetId !== creep.memory.routing.targetId) {
          reverse = true;
        }
      }
    }
  }

  if (creep.checkEnergyTransfer()) {
    reverse = true;
    if (creep.inBase()) {
      const transferred = creep.transferToStructures();
      if (transferred) {
        if (transferred.moreStructures) {
          return true;
        }
        reverse = creep.carry.energy - transferred.transferred > 0;
      } else if (creep.memory.routing.pathPos === 0 && !(creep.room.storage && creep.room.storage.my && creep.room.storage.isActive())) {
        creep.drop(RESOURCE_ENERGY);
        reverse = false;

        let resourceAtPosition = 0;
        const resources = creep.pos.lookFor(LOOK_RESOURCES);
        for (const resource of resources) {
          resourceAtPosition += resource.amount;
        }
        let amount = creep.room.getHarvesterAmount();
        amount += Math.floor(resourceAtPosition / config.carry.callHarvesterPerResources);
        creep.room.checkRoleToSpawn('harvester', amount, 'harvester');
      }
    }
    if (directions.backwardDirection && directions.backwardDirection !== null) {
      const transferred = creep.transferToCreep(directions.backwardDirection);
      reverse = !transferred;
    }
  }

  reverse = creep.pickupWhileMoving(reverse);
  if (reverse) {
    //     creep.log('reverse');
    directions.direction = directions.backwardDirection;
  } else {
    //     creep.log('not reverse');
    directions.direction = directions.forwardDirection;
  }
  creep.memory.routing.reverse = reverse;

  if (!directions.direction) {
    return false;
  }
  const posForward = creep.pos.getAdjacentPosition(directions.direction);
  const structures = posForward.lookFor(LOOK_STRUCTURES);
  for (const structure of structures) {
    if (structure.structureType === STRUCTURE_ROAD) {
      continue;
    }
    if (structure.structureType === STRUCTURE_CONTAINER) {
      continue;
    }
    if (structure.structureType === STRUCTURE_RAMPART && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_SPAWN && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_STORAGE && structure.my) {
      continue;
    }
    if (structure.structureType === STRUCTURE_LINK && structure.my) {
      continue;
    }

    creep.dismantle(structure);
    creep.say('dismantle');
    break;
  }
};

roles.carry.action = function(creep) {
  // TODO log when this happens, carry is getting energy from the source
  // creep.log('ACTION');
  const source = Game.getObjectById(creep.memory.routing.targetId);
  if (source === null) {
    creep.say('sfener');
    creep.memory.routing.reached = false;
    creep.memory.routing.reverse = true;

    const sources = creep.pos.findInRange(FIND_SOURCES, 3);
    if (sources.length > 0) {
      creep.memory.routing.targetId = sources[0].id;
      return true;
    }

    const resource = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
    if (resource !== null) {
      creep.memory.routing.targetId = resource.id;
      // TODO Use pathfinder
      creep.moveTo(resource);
      creep.pickup(resource, resource.amount - 1);
      return true;
    }
  }
  // TODO this should be last position => reverse - In preMove make sure a reverse stays if it is set here
  let reverse = false;
  reverse = creep.pickupWhileMoving(reverse);

  if (!reverse) {
    creep.harvest(source);
  }

  if (!creep.room.controller) {
    const target = creep.findClosestSourceKeeper();
    if (target !== null) {
      const range = creep.pos.getRangeTo(target);
      if (range < 5) {
        delete creep.memory.routing.reached;
        creep.memory.routing.reverse = true;
      }
    }
  }

  creep.memory.routing.reached = false;
  creep.memory.routing.reverse = true;

  return true;
};

roles.carry.execute = function(creep) {
  // creep.log('Execute!!!');
  const target = Game.getObjectById(creep.memory.routing.targetId);
  if (target === null) {
    delete creep.memory.routing.targetId;
  }
};
<|endoftext|>


<commit_before>(function() {
  var $ = require('jquery');
  var gui = require('nw.gui');

  // Get the current window
  var win = gui.Window.get();

  win.on('new-win-policy', function(frame, url, policy) {
    policy.ignore();
    gui.Shell.openExternal(url);
    //policy.forceNewWindow();
  });

  // FIXME: very hacky way to forcefully update font-family
  win.on('document-end', function() {
    var i = frames[0];
    var d = i.document;

    i.onload = function() {
        console.log('loaded');
        var topbar = d.getElementById("pagelet_bluebar");
        topbar.style.display = "none";
        var sidebar = d.getElementById("pagelet_sidebar");
        sidebar.style.display = "none";
        var dock = d.getElementById("pagelet_dock");
        dock.style.display = "none";
        var ad = d.getElementById("rightCol");
        ad.style.display = "none";

        var root = document.getElementById("main");
        root.setAttribute("class", "visible");
    }
  });

  // Need to set the menu using shortcuts on osx
  // https://github.com/nwjs/nw.js/wiki/Menu#menucreatemacbuiltinappname
  var nativeMenuBar = new gui.Menu({ type: "menubar" });
  if (nativeMenuBar && nativeMenuBar.createMacBuiltin) {
    nativeMenuBar.createMacBuiltin(gui.App.manifest.name);
    win.menu = nativeMenuBar;
  }
}).apply(this);
<commit_msg>adhoc Meiryo Hack<commit_after>(function() {
  var $ = require('jquery');
  var gui = require('nw.gui');

  // Get the current window
  var win = gui.Window.get();

  win.on('new-win-policy', function(frame, url, policy) {
    policy.ignore();
    gui.Shell.openExternal(url);
    //policy.forceNewWindow();
  });

  // FIXME: very hacky way to forcefully update font-family
  win.on('document-end', function() {
    var i = frames[0];
    var d = i.document;

    i.onload = function() {
        console.log('loaded');
        d.body.style.fontFamily = "Meiryo UI";

        var topbar = d.getElementById("pagelet_bluebar");
        topbar.style.display = "none";
        var sidebar = d.getElementById("pagelet_sidebar");
        sidebar.style.display = "none";
        var dock = d.getElementById("pagelet_dock");
        dock.style.display = "none";
        var ad = d.getElementById("rightCol");
        ad.style.display = "none";

        var root = document.getElementById("main");
        root.setAttribute("class", "visible");
    }
  });

  // Need to set the menu using shortcuts on osx
  // https://github.com/nwjs/nw.js/wiki/Menu#menucreatemacbuiltinappname
  var nativeMenuBar = new gui.Menu({ type: "menubar" });
  if (nativeMenuBar && nativeMenuBar.createMacBuiltin) {
    nativeMenuBar.createMacBuiltin(gui.App.manifest.name);
    win.menu = nativeMenuBar;
  }
}).apply(this);
<|endoftext|>


<commit_before>/* http://github.com/mindmup/bootstrap-wysiwyg */
/*global $*/
/*jslint browser:true*/
$.fn.cleanHtml = function () {
	'use strict';
	var html = $(this).html();
	return html && html.replace(/(
|\s|

<\/div>| )*$/, '');
};
$.fn.wysiwyg = function (options) {
	'use strict';
	var editor = this,
		selectedRange,
		defaultOptions = {
			hotKeys: {
				'ctrl+b meta+b': 'bold',
				'ctrl+i meta+i': 'italic',
				'ctrl+u meta+u': 'underline',
				'ctrl+z meta+z': 'undo',
				'ctrl+y meta+y meta+shift+z': 'redo',
				'ctrl+l meta+l': 'justifyleft',
				'ctrl+r meta+r': 'justifyright',
				'ctrl+e meta+e': 'justifycenter',
				'ctrl+j meta+j': 'justifyfull',
				'shift+tab': 'outdent',
				'tab': 'indent'
            },
			toolbarRole: 'editor-toolbar',
			commandRole: 'edit'
		},
		execCommand = function (commandWithArgs, valueArg) {
			var commandArr = commandWithArgs.split(' '),
				command = commandArr.shift(),
				args = commandArr.join(' ') + (valueArg || '');
			document.execCommand(command, 0, args);
		},
		bindHotkeys = function (hotKeys) {
			$.each(hotKeys, function (hotkey, command) {
				editor.keydown(hotkey, function (e) {
					e.preventDefault();
					e.stopPropagation();
					execCommand(command);
				}).keyup(hotkey, function (e) {
					e.preventDefault();
					e.stopPropagation();
				});
			});
		},
		saveSelectionRange = function () {
			var sel = window.getSelection();
			if (sel.getRangeAt && sel.rangeCount) {
				selectedRange = sel.getRangeAt(0);
			}
		},
		restoreSelectionRange = function () {
			var selection = window.getSelection();
			if (selectedRange) {
				selection.removeAllRanges();
				selection.addRange(selectedRange);
			}
		},
		bindToolbar = function (toolbar, options) {
			toolbar.find('a[data-' + options.commandRole + ']').click(function () {
				restoreSelectionRange();
				execCommand($(this).data(options.commandRole));
				saveSelectionRange();
			});
			toolbar.find('input[data-' + options.commandRole + ']').change(function () {
				var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
				this.value = '';
				restoreSelectionRange();
				if (newValue) {
					execCommand($(this).data(options.commandRole), newValue);
				}
				saveSelectionRange();
			});
		};
	options = $.extend({}, defaultOptions, options);
	bindHotkeys(options.hotKeys);
	$.each($.find('[data-role=' + options.toolbarRole + ']'), function () { bindToolbar($(this), options); });
	$.each(this, function () {
		var before,
			element = $(this);
		element.attr('contenteditable', true)
			.on('focus', function () {
				before = element.html();
			})
			.on('mouseup keyup mouseout', saveSelectionRange)
			.on('input blur keyup paste', function () {
				if (before !== element.html()) {
					before = element.html();
					element.trigger('change');
				}
			});
	});
	return this;
}
<commit_msg>touch events<commit_after>/* http://github.com/mindmup/bootstrap-wysiwyg */
/*global $*/
/*jslint browser:true*/
$.fn.cleanHtml = function () {
	'use strict';
	var html = $(this).html();
	return html && html.replace(/(
|\s|

<\/div>| )*$/, '');
};
$.fn.wysiwyg = function (options) {
	'use strict';
	var editor = this,
		selectedRange,
		defaultOptions = {
			hotKeys: {
				'ctrl+b meta+b': 'bold',
				'ctrl+i meta+i': 'italic',
				'ctrl+u meta+u': 'underline',
				'ctrl+z meta+z': 'undo',
				'ctrl+y meta+y meta+shift+z': 'redo',
				'ctrl+l meta+l': 'justifyleft',
				'ctrl+r meta+r': 'justifyright',
				'ctrl+e meta+e': 'justifycenter',
				'ctrl+j meta+j': 'justifyfull',
				'shift+tab': 'outdent',
				'tab': 'indent'
            },
			toolbarRole: 'editor-toolbar',
			commandRole: 'edit'
		},
		execCommand = function (commandWithArgs, valueArg) {
			var commandArr = commandWithArgs.split(' '),
				command = commandArr.shift(),
				args = commandArr.join(' ') + (valueArg || '');
			document.execCommand(command, 0, args);
		},
		bindHotkeys = function (hotKeys) {
			$.each(hotKeys, function (hotkey, command) {
				editor.keydown(hotkey, function (e) {
					e.preventDefault();
					e.stopPropagation();
					execCommand(command);
				}).keyup(hotkey, function (e) {
					e.preventDefault();
					e.stopPropagation();
				});
			});
		},
		saveSelectionRange = function () {
			var sel = window.getSelection();
			if (sel.getRangeAt && sel.rangeCount) {
				selectedRange = sel.getRangeAt(0);
			}
		},
		restoreSelectionRange = function () {
			var selection = window.getSelection();
			if (selectedRange) {
				selection.removeAllRanges();
				selection.addRange(selectedRange);
			}
		},
		bindToolbar = function (toolbar, options) {
			toolbar.find('a[data-' + options.commandRole + ']').click(function () {
				restoreSelectionRange();
				execCommand($(this).data(options.commandRole));
				saveSelectionRange();
			});
			toolbar.find('input[data-' + options.commandRole + ']').change(function () {
				var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
				this.value = '';
				restoreSelectionRange();
				if (newValue) {
					execCommand($(this).data(options.commandRole), newValue);
				}
				saveSelectionRange();
			});
		};
	options = $.extend({}, defaultOptions, options);
	bindHotkeys(options.hotKeys);
	$.each($.find('[data-role=' + options.toolbarRole + ']'), function () { bindToolbar($(this), options); });
	$.each(this, function () {
		var before,
			element = $(this);
		element.attr('contenteditable', true)
			.on('focus', function () {
				before = element.html();
			})
			.on('mouseup keyup mouseout', saveSelectionRange)
			.on('input blur keyup paste', function () {
				if (before !== element.html()) {
					before = element.html();
					element.trigger('change');
				}
			});
		$(window).bind('touchend', saveSelectionRange);
	});
	return this;
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    // Handle dragging.
    var floated = false;
    var originalHeight;
    var originalWidth;
    var miniScreenLastTop;
    var miniScreenLastLeft;
    var miniScreenLastHeight;
    var miniScreenLastWidth;
    var start;
    var longpress = 100;
    var dragStartX, dragStartY, dragStartWidth, dragStartHeight, dragRatio;
    var maxWidth = 640;
    var minWidth = 310;
    var resizing = false;

    (function($) {
        $.fn.drags = function(opt) {

            opt = $.extend({handle:"",cursor:"move"}, opt);

            if(opt.handle === "") {
                var $el = this;
            } else {
                var $el = this.find(opt.handle);
            }

            return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
                // If the clicked div is resizer, don't make it draggable.
                if(e.target.className === "resizer") {
                    return false;
                }

                var $drag = $(this).addClass('draggable');

                var z_idx = $drag.css('z-index'),
                    drg_h = $drag.outerHeight(),
                    drg_w = $drag.outerWidth(),
                    pos_y = $drag.offset().top + drg_h - e.pageY,
                    pos_x = $drag.offset().left + drg_w - e.pageX;
                $drag.css('z-index', 1000).parent().on("mousemove", function(e) {
                    // Prevent going out of screen horizontally.
                    var left = e.pageX + pos_x - drg_w;
                    if (left < 5) {
                        left = 5;
                    } else if (left > $(window).width() - drg_w - 5) {
                        left = $(window).width() - drg_w - 5;
                    }

                    // Prevent going out of screen vertically.
                    var top = e.pageY + pos_y - drg_h;
                    if (top < $(document).scrollTop() + 55) {
                        top = $(document).scrollTop() + 55;
                    } else if (top > $(document).scrollTop() + $(window).height() - drg_h - 5) {
                        top = $(document).scrollTop() + $(window).height() - drg_h - 5;
                    }

                    $('.draggable').offset({
                        top: top,
                        left: left
                    }).on("mouseup", function() {
                        $(this).removeClass('draggable').css('z-index', z_idx);
                    });
                }).on("mouseup", function() {
                    $(this).parent().unbind('mousemove');
                    $(this).removeClass('draggable');
                });

                e.preventDefault(); // disable selection
            });
        }
    })(jQuery);

    // Keep track of the position of view and show small screen when original video div is out of view
    $(window).scroll(function() {
        if (floated == false && $('.ended-mode').length) {
            // If the video has ended and there is no floating screen, do nothing
            return false;
        } else if (floated == false && $(document).scrollTop() > $('.html5-video-container').offset().top + $('.html5-video-container').height()) {
            // 1. Create the mini screen div to hold the video
            $miniScreen = $('
</div');
            // Put the screen back to its last position, if defined.
            // Else default to top right.
            var miniScreenTop = 55;
            if (miniScreenLastTop)
                miniScreenTop = miniScreenLastTop;

            var miniScreenLeft = $(window).width() - 380;
            if (miniScreenLastLeft)
                miniScreenLeft = miniScreenLastLeft;
            $miniScreen.css('top', miniScreenTop);
            $miniScreen.css('left', miniScreenLeft);

            if (miniScreenLastHeight) {
                $miniScreen.height(miniScreenLastHeight);
            }
            if (miniScreenLastWidth) {
                $miniScreen.width(miniScreenLastWidth);
            }

            // 2. Grab the video element
            $video = $('.video-stream');

            // 3. Store the status of the video
            var videoPaused = $video.get(0).paused;

            // 4. Store the current width and height to restore later
            originalWidth = $video.width();
            originalHeight = $video.height();

            // 5. Wrap the video into the small element div
            $video.wrap($miniScreen);

            // 6. Modify clicking to differentiate long vs short clicks.
            // Long click -> dragging. Short click -> pause/play
            $('#miniyoutube').on('mousedown', function(e) {
                start = new Date().getTime();
            });
            $('#miniyoutube').on('mouseleave', function(e) {
                start = 0;
            });
            $('#miniyoutube').on('mouseup', function(e) {
                // If it's a short click, toggle the video status.
                if (resizing == true) {
                    stopDrag(e);
                    return false;
                }

                if (new Date().getTime() < (start + longpress)) {
                   toggleVideo();
                }
                return false;
            });
            $('#miniyoutube').click(function() {
                return false;
            });
            // Disable double click to full screen.
            $('#miniyoutube').dblclick(function() {
                return false;
            });

            // 7. If the video was playing before, make sure it's not paused
            if (!videoPaused) {
                $video.get(0).play();
            }

            // 8. Set the width and height of the video to fit the div
            $video.css('width', '100%');
            $video.css('height', '100%');

            // 9. Activate the draggable feature of the small screen
            $('#miniyoutube').drags();

            // 10. Set flag to true
            floated = true;

            // Add resizers to the right corners of the div
            $('#miniyoutube').append('
\

\

\

');

            // Add listener for the resizers
            $('.resizer').bind('mousedown.resizer', initDrag);

        } else if (floated == true && $(document).scrollTop() <= $('.html5-video-container').offset().top + $('.html5-video-container').height()) {
            // Put back the screen when the user scrolls up to the original player
            // 1. Grab the video element
            $video = $('.video-stream');

            // 2. Store the status of the video
            var videoPaused = $video.get(0).paused;

            // 3. Save the current top and left of the mini screen.
            miniScreenLastTop = $('#miniyoutube').css('top');
            miniScreenLastLeft = $('#miniyoutube').css('left');
            miniScreenLastHeight = $('#miniyoutube').height();
            miniScreenLastWidth = $('#miniyoutube').width();

            // 4. Restore the width and heigh of the video
            $video.css('width', originalWidth);
            $video.css('height', originalHeight);

            // Remove the resizers
            $('.resizer').unbind('mousedown');
            $video.next().remove();

            // 5. Take away the parent.
            $video.unwrap();

            // 6. Make the video status consistent
            if (!videoPaused) {
                $video.get(0).play();
            }

            // 7. Set flag to false
            floated = false;
        } else if (floated == true && $('.ended-mode').length) {
            // If the video has ended and the screen is still around, clear it.
            // 1. Grab the video element
            $video = $('.video-stream');

            // 2. Restore the width and heigh of the video
            $video.css('width', originalWidth);
            $video.css('height', originalHeight);

            // Remove the resizers
            $('.resizer').unbind('mousedown');
            $video.next().remove();

            // 3. Take away the parent.
            $video.unwrap();

            // 4. Set flag to false
            floated = false;
        }
    });

    function initDrag(e) {
        resizing = true;
        // Store the initial values to calculate new size later
        dragStartX = e.clientX;
        dragStartY = e.clientY;
        dragStartWidth = $('#miniyoutube').width();
        dragStartHeight = $('#miniyoutube').height();
        dragRatio = dragStartHeight/dragStartWidth;
        // Add event listeners to perform resize
        $(document).mousemove(doDrag);
        e.preventDefault();

        return false;
    }

    function doDrag(e) {
        // if not resizing, do nothing
        if (resizing == false) {
            return false;
        }

        var newWidth = dragStartWidth + e.clientX - dragStartX;
        // Make sure the new width does not exceed the max width
        if (newWidth > maxWidth) {
            newWidth = maxWidth;
        }
        if (newWidth < minWidth) {
            newWidth = minWidth;
        }

        var newHeight = parseInt(newWidth * dragRatio);
        $('#miniyoutube').width(newWidth);
        $('#miniyoutube').height(newHeight);
        e.preventDefault();

        return false;
    }

    function stopDrag(e) {
        // Set the flag to false
        resizing = false;
        // Remove the listensers
        $(document).unbind('mousemove');
        return false;
    }

    function toggleVideo() {
        $vid = $('.video-stream').get(0);
        if ($vid.paused)
            $vid.play();
        else
            $vid.pause();
    }
});<commit_msg>Added mouseup handler to window<commit_after>$(document).ready(function() {
    // Handle dragging.
    var floated = false;
    var originalHeight;
    var originalWidth;
    var miniScreenLastTop;
    var miniScreenLastLeft;
    var miniScreenLastHeight;
    var miniScreenLastWidth;
    var start;
    var longpress = 100;
    var dragStartX, dragStartY, dragStartWidth, dragStartHeight, dragRatio;
    var maxWidth = 640;
    var minWidth = 310;
    var resizing = false;

    (function($) {
        $.fn.drags = function(opt) {

            opt = $.extend({handle:"",cursor:"move"}, opt);

            if(opt.handle === "") {
                var $el = this;
            } else {
                var $el = this.find(opt.handle);
            }

            return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
                // If the clicked div is resizer, don't make it draggable.
                if(e.target.className === "resizer") {
                    return false;
                }

                var $drag = $(this).addClass('draggable');

                var z_idx = $drag.css('z-index'),
                    drg_h = $drag.outerHeight(),
                    drg_w = $drag.outerWidth(),
                    pos_y = $drag.offset().top + drg_h - e.pageY,
                    pos_x = $drag.offset().left + drg_w - e.pageX;
                $drag.css('z-index', 1000).parent().on("mousemove", function(e) {
                    // Prevent going out of screen horizontally.
                    var left = e.pageX + pos_x - drg_w;
                    if (left < 5) {
                        left = 5;
                    } else if (left > $(window).width() - drg_w - 5) {
                        left = $(window).width() - drg_w - 5;
                    }

                    // Prevent going out of screen vertically.
                    var top = e.pageY + pos_y - drg_h;
                    if (top < $(document).scrollTop() + 55) {
                        top = $(document).scrollTop() + 55;
                    } else if (top > $(document).scrollTop() + $(window).height() - drg_h - 5) {
                        top = $(document).scrollTop() + $(window).height() - drg_h - 5;
                    }

                    $('.draggable').offset({
                        top: top,
                        left: left
                    }).on("mouseup", function() {
                        $(this).removeClass('draggable').css('z-index', z_idx);
                    });
                }).on("mouseup", function() {
                    $(this).parent().unbind('mousemove');
                    $(this).removeClass('draggable');
                });

                e.preventDefault(); // disable selection
            });
        }
    })(jQuery);

    // Keep track of the position of view and show small screen when original video div is out of view
    $(window).scroll(function() {
        if (floated == false && $('.ended-mode').length) {
            // If the video has ended and there is no floating screen, do nothing
            return false;
        } else if (floated == false && $(document).scrollTop() > $('.html5-video-container').offset().top + $('.html5-video-container').height()) {
            // 1. Create the mini screen div to hold the video
            $miniScreen = $('
</div');
            // Put the screen back to its last position, if defined.
            // Else default to top right.
            var miniScreenTop = 55;
            if (miniScreenLastTop)
                miniScreenTop = miniScreenLastTop;

            var miniScreenLeft = $(window).width() - 380;
            if (miniScreenLastLeft)
                miniScreenLeft = miniScreenLastLeft;
            $miniScreen.css('top', miniScreenTop);
            $miniScreen.css('left', miniScreenLeft);

            if (miniScreenLastHeight) {
                $miniScreen.height(miniScreenLastHeight);
            }
            if (miniScreenLastWidth) {
                $miniScreen.width(miniScreenLastWidth);
            }

            // 2. Grab the video element
            $video = $('.video-stream');

            // 3. Store the status of the video
            var videoPaused = $video.get(0).paused;

            // 4. Store the current width and height to restore later
            originalWidth = $video.width();
            originalHeight = $video.height();

            // 5. Wrap the video into the small element div
            $video.wrap($miniScreen);

            // 6. Modify clicking to differentiate long vs short clicks.
            // Long click -> dragging. Short click -> pause/play
            $('#miniyoutube').on('mousedown', function(e) {
                start = new Date().getTime();
            });
            $('#miniyoutube').on('mouseleave', function(e) {
                start = 0;
            });
            $('#miniyoutube').on('mouseup', function(e) {
                // If it's a short click, toggle the video status.
                if (resizing == true) {
                    stopDrag(e);
                    return false;
                }

                if (new Date().getTime() < (start + longpress)) {
                   toggleVideo();
                }
                return false;
            });
            $('#miniyoutube').click(function() {
                return false;
            });
            // Disable double click to full screen.
            $('#miniyoutube').dblclick(function() {
                return false;
            });

            // 7. If the video was playing before, make sure it's not paused
            if (!videoPaused) {
                $video.get(0).play();
            }

            // 8. Set the width and height of the video to fit the div
            $video.css('width', '100%');
            $video.css('height', '100%');

            // 9. Activate the draggable feature of the small screen
            $('#miniyoutube').drags();

            // 10. Set flag to true
            floated = true;

            // Add resizers to the right corners of the div
            $('#miniyoutube').append('
\

\

\

');

            // Add listener for the resizers
            $('.resizer').bind('mousedown.resizer', initDrag);

        } else if (floated == true && $(document).scrollTop() <= $('.html5-video-container').offset().top + $('.html5-video-container').height()) {
            // Put back the screen when the user scrolls up to the original player
            // 1. Grab the video element
            $video = $('.video-stream');

            // 2. Store the status of the video
            var videoPaused = $video.get(0).paused;

            // 3. Save the current top and left of the mini screen.
            miniScreenLastTop = $('#miniyoutube').css('top');
            miniScreenLastLeft = $('#miniyoutube').css('left');
            miniScreenLastHeight = $('#miniyoutube').height();
            miniScreenLastWidth = $('#miniyoutube').width();

            // 4. Restore the width and heigh of the video
            $video.css('width', originalWidth);
            $video.css('height', originalHeight);

            // Remove the resizers
            $('.resizer').unbind('mousedown');
            $video.next().remove();

            // 5. Take away the parent.
            $video.unwrap();

            // 6. Make the video status consistent
            if (!videoPaused) {
                $video.get(0).play();
            }

            // 7. Set flag to false
            floated = false;
        } else if (floated == true && $('.ended-mode').length) {
            // If the video has ended and the screen is still around, clear it.
            // 1. Grab the video element
            $video = $('.video-stream');

            // 2. Restore the width and heigh of the video
            $video.css('width', originalWidth);
            $video.css('height', originalHeight);

            // Remove the resizers
            $('.resizer').unbind('mousedown');
            $video.next().remove();

            // 3. Take away the parent.
            $video.unwrap();

            // 4. Set flag to false
            floated = false;
        }
    });

    function initDrag(e) {
        resizing = true;
        // Store the initial values to calculate new size later
        dragStartX = e.clientX;
        dragStartY = e.clientY;
        dragStartWidth = $('#miniyoutube').width();
        dragStartHeight = $('#miniyoutube').height();
        dragRatio = dragStartHeight/dragStartWidth;
        // Add event listeners to perform resize
        $(document).mousemove(doDrag);
        window.addEventListener('mouseup', stopDrag);
        e.preventDefault();

        return false;
    }

    function doDrag(e) {
        // if not resizing, do nothing
        if (resizing == false) {
            return false;
        }

        var newWidth = dragStartWidth + e.clientX - dragStartX;
        // Make sure the new width does not exceed the max width
        if (newWidth > maxWidth) {
            newWidth = maxWidth;
        }
        if (newWidth < minWidth) {
            newWidth = minWidth;
        }

        var newHeight = parseInt(newWidth * dragRatio);
        $('#miniyoutube').width(newWidth);
        $('#miniyoutube').height(newHeight);
        e.preventDefault();

        return false;
    }

    function stopDrag(e) {
        // Set the flag to false
        resizing = false;
        // Remove the listensers
        $(document).unbind('mousemove');
        return false;
    }

    function toggleVideo() {
        $vid = $('.video-stream').get(0);
        if ($vid.paused)
            $vid.play();
        else
            $vid.pause();
    }
});<|endoftext|>


<commit_before>const http = require('http');
const express = require('express');
const mongo = require('mongodb');
const fs = require('fs');
const bodyparser = require('body-parser');
var ascoltatori_mqtt = require('ascoltatori');
var mqtt = require('mqtt');
const BSON = require('bson').BSONPure;
var path = require('path');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var expressapp = express();
var mongoUrl;
var mongoPort;
var kafkaUrl;
var kafkaPort;
var roadMapIdTemp;
var db;
var latestOffset;
var MyDate = new Date();
var MyDateString;
var consumer;
var kafka = require('kafka-node'),
Producer = kafka.Producer,
Consumer = kafka.Consumer,
client = new kafka.Client(),
producer = new Producer(client),
payloads = [
    {
        topic:'event',
        messages: '',
        partition: 0
    }
],
offset = new kafka.Offset(client);
//make server starts from latest logs
offset.fetchLatestOffsets(['log'], function (error, offsets) {
    if (error)
    return handleError(error);
    console.log('start from...\n\tkafka topic: log\n\toffset : '+offsets['log'][0]);
    latestOffset = offsets['log'][0];
    consumer = new Consumer(
        client,
        [
            {
                topic: 'log',
                partition: 0,
                offset: latestOffset
            }
        ],
        {
            autoCommit: false,
            fromOffset: true

        }
    );
    consumer.on('message', function (message) {
        MyDate = new Date();
        MyDate.setDate(MyDate.getDate() + 20);
        MyDateString = MyDate.getFullYear() + '/'
        +('0' + MyDate.getMonth()).slice(-2) + '/'
        +('0' + MyDate.getDate()).slice(-2) + '   '
        +('0' + MyDate.getHours()).slice(-2) + ':'
        +('0' + MyDate.getMinutes()).slice(-2) + ':'
        +('0' + MyDate.getSeconds()).slice(-2);
        console.log(MyDateString+"   "+JSON.stringify(message));
        fs.appendFile('.log', '['+MyDateString+']  '+ JSON.stringify(message)+'\r\n', 'utf8', function(err) {
        });
    });
});

// var KEY;
// var CERT;
// var TRUSTED_CA_LIST;
// var options = {
//     key: KEY,
//     cert: CERT,
//     rejectUnauthorized: true,
//     // The CA list will be used to determine if server is authorized
//     ca: TRUSTED_CA_LIST
// }

var settings = {
    type: 'mqtt',
    json: true,
    mqtt: require('mqtt'),
    url: 'mqtt://127.0.0.1:8883'
};

//
// var client = mqtt.connect('mqtt://localhost:8883', options);
// client.subscribe('enow/+/+/+/order');
// client.publish('enow/+/+/+/order');
//
//
// client.on('message', function (topic, message) {
//     //console.log(message.toString())
//     console.log(arguments[0]);
// });

expressapp.use(bodyparser.json());
expressapp.use(function(req,res,next){
    res.setTimeout(5000, function(){
        console.log('time out..');
        res.sendStatus(408);
    });
    next();
});
expressapp.use(express.static(path.join(__dirname+"/../", 'console')));
const port = 1111;
expressapp.set('port', port);

expressapp.post('/post_db', function(req, res){
    connectDB(req.body, 'enow', 'recipes', 'save', res);
});
expressapp.post('/run_db', function(req, res){
    var obj = new Object();
    console.log('Running RoadMap!');

    for(var i=1; i<= Object.keys(req.body['nodeIds']).length ; ++i){
        obj[req.body['nodeIds'][i]['brokerId']] = obj[req.body['nodeIds'][i]['brokerId']] || [];
        obj[req.body['nodeIds'][i]['brokerId']].push(req.body['nodeIds'][i]['deviceId']);
    }
    console.log(obj);

    for(var key.value in obj) {

    }

    connectDB(req.body, 'enow', 'execute', 'run', res);

    // ascoltatori_mqtt.build(settings, function(err, listener){
    //     listener.publish('enow/a/b/c/order', '{send:"hi die"}', function(){
    //         console.log('message published');
    //     })
    //
    //     listener.subscribe('enow/+/+/+/order', function(){
    //         console.log(arguments);
    //     });
    // });
    //
    // payloads[0]['messages']='{"roadMapId":"'+roadMapIdTemp+'"}';
    // setTimeout(function () {
    //     producer.send(payloads, function (err, data) {
    //         console.log(payloads);
    //     });
    //     producer.on('error', function (err) {
    //         console.log(err);
    //     });
    // }, 1000);
});
expressapp.post('/kill_db', function(req, res){
    console.log('kill execute...');
    connectDB(req.body, 'enow', 'execute', 'kill', res)
});
expressapp.post('/add_broker', function(req, res){
    console.log('add broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveBroker', res);
});
expressapp.post('/add_device', function(req, res){
    console.log('add device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveDevice', res);
});
expressapp.post('/find_device', function(req, res){
    console.log('find device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findDevice', res);
});
expressapp.post('/post_url_settings', function(req, res){
    console.log('setting url...');
    mongoUrl = req.body['mongoUrl'];
    mongoPort = req.body['mongoPort'];
    kafkaUrl = req.body['kafkaUrl'];
    kafkaPort = req.body['kafkaPort'];
    producer.client.connectionString = kafkaUrl+':'+kafkaPort;
    if(db){
        db.close();
    }
    MongoClient.connect('mongodb://'+ mongoUrl+'/'+mongoPort, function(err, database, callback) {
        if(err){
            console.log(err);
            res.send('no_connect');
            return;
        }
        db = database;
        console.log('connected to mongodb://'+ mongoUrl+'/'+mongoPort);
        res.send("done");
    });
});
expressapp.post('/load_roadmap', function(req, res){
    console.log('load roadmap...');
    console.log(req.body['db']);
    connectDB(req.body, req.body['db'], req.body['collection'], 'findTarget', res);
    // connectDB(req.body, 'enow', 'recipes', 'findTarget', res);
});
expressapp.post('/get_broker', function(req, res){
    console.log('get broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});

expressapp.post('/add_secure', function(req, res){
    console.log('add secure...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'addSecure', res);
});

expressapp.get('/get_brokers', function(req, res){
    console.log('get brokers...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});
expressapp.get('/get_settings', function(req, res){
    console.log('get settings...');
    connectDB(null, 'connectionData', 'settings', 'find', res);
});
expressapp.get('/get_roadmaps', function(req, res){
    console.log('get roadmaps...');
    connectDB(null, 'enow', 'recipes', 'find', res);
});
expressapp.get('/get_running_roadmaps', function(req, res){
    console.log('get running roadmaps...');
    connectDB(null, 'enow', 'execute', 'find', res);
});
expressapp.get('/get_devices', function(req, res){
    console.log('get devices...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});

var server = expressapp.listen(expressapp.get('port'), function(){
    console.log("\n\n\n");
    console.log(
        "  ███████╗███╗   ██╗ ██████╗ ██╗    ██╗\
        \n  ██╔════╝████╗  ██║██╔═══██╗██║    ██║  ENOW Started!\
        \n  █████╗  ██╔██╗ ██║██║   ██║██║ █╗ ██║  Connect to 127.0.0.1:1111\
        \n  ██╔══╝  ██║╚██╗██║██║   ██║██║███╗██║\
        \n  ███████╗██║ ╚████║╚██████╔╝╚███╔███╔╝  Version 0.0.1\
        \n  ╚══════╝╚═╝  ╚═══╝ ╚═════╝  ╚══╝╚══╝   Copyright © 2016 ENOW. All rights reserved.");
    });
    function connectDB(source, dbName, collectionName, command, response){
        console.log('connecting to '+mongoUrl+':'+mongoPort+'...'+dbName+'.'+collectionName);
        console.log('connected!');
        var findDocument = function(callback){
            db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                response.send(result);
            });
        };
        var findBroker = function(callback){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                response.send(result);
            });
        };

        var findTarget = function(callback){
            console.log("abcd");
            var o_id = BSON.ObjectID.createFromHexString(source['_id']);
            db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){
                console.log(result);
                response.send(result);
                o_id = null;
            });
        }

        var findDevice = function(callback){
            db.db(dbName).collection(collectionName).find({deviceId:source['deviceId']}).toArray(function(err,result){
                response.send(result);
            });
        }

        var insertDocument = function(callback){
            var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                if(result.length!=0){
                    roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
                }
                else{
                    roadMapIdTemp = 1;
                }
                db.db(dbName).collection(collectionName).insertOne({
                    "roadMapId" : roadMapIdTemp.toString(),
                    "clientId" : source['clientId'],
                    "orderNode" : source['orderNode'],
                    "initNode" : source['initNode'],
                    "lastNode" : source['lastNode'],
                    "incomingNode" : source['incomingNode'],
                    "outingNode" : source['outingNode'],
                    "isInput" : source['isInput'],
                    "isOutput" : source['isOutput'],
                    "nodeIds" : source['nodeIds']
                },function(err, result){
                    response.send("done");
                });
            });

        };

        var insertDocumentDevice = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$push' : { 'deviceId': source['deviceId']}
            }, function(err,result){
                response.send("done");
            });
        };

        var insertDocumentBroker = function(callback){
            db.db(dbName).collection(collectionName).count({}, function(err, cnt) {
                db.db(dbName).collection(collectionName).insertOne({
                    "brokerNum" : (cnt+1).toString(),
                    "brokerId" : source['brokerId'],
                    "ipAddress" : source['ipAddress'],
                    "port" : source['port'],
                    "deviceId" : source['deviceId'],
                },function(err, result){
                    response.send("done");
                });
            });
        };

        var updateBroker = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$set' : { 'ca': source['ca'], 'hostCrt': source['hostCrt'], 'hostKey': source['hostKey']}
            }, function(err,result){
                response.send("done");
            });
        };

        var deleteDocument = function(callback){
            db.db(dbName).collection(collectionName).deleteOne({
            },function(err, result){
                response.send("done");
            });
        };

        if(command=="save" || command=="run"){
            insertDocument(db, function(){
            });
        }else if(command=="saveBroker"){
            insertDocumentBroker(db, function(){
            });
        }else if(command=="saveDevice"){
            insertDocumentDevice(db, function(){
            });
        }else if(command=="findDevice"){
            findDevice(db, function(){
            });
        }else if(command=="kill"){
            deleteDocument(db,function(){
            });
        }else if(command=="find"){
            findDocument(db, function(){
            });
        }else if(command=="findTarget"){
            console.log("qwertty");
            findTarget(db, function(){
            });
        }else if(command=="findBroker"){
            findBroker(db, function(){
            });
        }else if(command=="addSecure"){
            updateBroker(db, function(){
            });
        }
    };
<commit_msg>no ascoltatori<commit_after>const http = require('http');
const express = require('express');
const mongo = require('mongodb');
const fs = require('fs');
const bodyparser = require('body-parser');
var ascoltatori_mqtt = require('ascoltatori');
var mqtt = require('mqtt');
const BSON = require('bson').BSONPure;
var path = require('path');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var expressapp = express();
var mongoUrl;
var mongoPort;
var kafkaUrl;
var kafkaPort;
var roadMapIdTemp;
var db;
var latestOffset;
var MyDate = new Date();
var MyDateString;
var consumer;
var kafka = require('kafka-node'),
Producer = kafka.Producer,
Consumer = kafka.Consumer,
client = new kafka.Client(),
producer = new Producer(client),
payloads = [
    {
        topic:'event',
        messages: '',
        partition: 0
    }
],
offset = new kafka.Offset(client);
//make server starts from latest logs
offset.fetchLatestOffsets(['log'], function (error, offsets) {
    if (error)
    return handleError(error);
    console.log('start from...\n\tkafka topic: log\n\toffset : '+offsets['log'][0]);
    latestOffset = offsets['log'][0];
    consumer = new Consumer(
        client,
        [
            {
                topic: 'log',
                partition: 0,
                offset: latestOffset
            }
        ],
        {
            autoCommit: false,
            fromOffset: true

        }
    );
    consumer.on('message', function (message) {
        MyDate = new Date();
        MyDate.setDate(MyDate.getDate() + 20);
        MyDateString = MyDate.getFullYear() + '/'
        +('0' + MyDate.getMonth()).slice(-2) + '/'
        +('0' + MyDate.getDate()).slice(-2) + '   '
        +('0' + MyDate.getHours()).slice(-2) + ':'
        +('0' + MyDate.getMinutes()).slice(-2) + ':'
        +('0' + MyDate.getSeconds()).slice(-2);
        console.log(MyDateString+"   "+JSON.stringify(message));
        fs.appendFile('.log', '['+MyDateString+']  '+ JSON.stringify(message)+'\r\n', 'utf8', function(err) {
        });
    });
});

var settings = {
    type: 'mqtt',
    json: true,
    mqtt: require('mqtt'),
    url: 'mqtt://127.0.0.1:8883'
};

expressapp.use(bodyparser.json());
expressapp.use(function(req,res,next){
    res.setTimeout(5000, function(){
        console.log('time out..');
        res.sendStatus(408);
    });
    next();
});
expressapp.use(express.static(path.join(__dirname+"/../", 'console')));
const port = 1111;
expressapp.set('port', port);

expressapp.post('/post_db', function(req, res){
    connectDB(req.body, 'enow', 'recipes', 'save', res);
});
expressapp.post('/run_db', function(req, res){
    var obj = new Object();
    console.log('Running RoadMap!');

    for(var i=1; i<= Object.keys(req.body['nodeIds']).length ; ++i){
        obj[req.body['nodeIds'][i]['brokerId']] = obj[req.body['nodeIds'][i]['brokerId']] || [];
        obj[req.body['nodeIds'][i]['brokerId']].push(req.body['nodeIds'][i]['deviceId']);
    }
    console.log(obj);

    for(key in obj){
        for(val in obj[key]){
            console.log(key+':'+obj[key][val]);
            // settings['url'] = 'mqtt://127.0.0.1:8883'
            // setTimeout(function(){
            //     ascoltatori_mqtt.build(settings, function(err, listener){
            //         listener.publish('aliveRequest', 'enow/server0/'+key+'/'+obj[key][val]+'/order', function(){
            //             console.log('message published');
            //         })
            //         listener.subscribe('aliveResponse', function(){
            //             console.log(arguments);
            //         });
            //     });
            // },1000);

        }
    }

    connectDB(req.body, 'enow', 'execute', 'run', res);
    payloads[0]['messages']='{"roadMapId":"'+roadMapIdTemp+'"}';
    setTimeout(function () {
        producer.send(payloads, function (err, data) {
            console.log(payloads);
        });
        producer.on('error', function (err) {
            console.log(err);
        });
    }, 1000);
});
expressapp.post('/kill_db', function(req, res){
    console.log('kill execute...');
    connectDB(req.body, 'enow', 'execute', 'kill', res)
});
expressapp.post('/add_broker', function(req, res){
    console.log('add broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveBroker', res);
});
expressapp.post('/add_device', function(req, res){
    console.log('add device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveDevice', res);
});
expressapp.post('/find_device', function(req, res){
    console.log('find device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findDevice', res);
});
expressapp.post('/post_url_settings', function(req, res){
    console.log('setting url...');
    mongoUrl = req.body['mongoUrl'];
    mongoPort = req.body['mongoPort'];
    kafkaUrl = req.body['kafkaUrl'];
    kafkaPort = req.body['kafkaPort'];
    producer.client.connectionString = kafkaUrl+':'+kafkaPort;
    if(db){
        db.close();
    }
    MongoClient.connect('mongodb://'+ mongoUrl+'/'+mongoPort, function(err, database, callback) {
        if(err){
            console.log(err);
            res.send('no_connect');
            return;
        }
        db = database;
        console.log('connected to mongodb://'+ mongoUrl+'/'+mongoPort);
        res.send("done");
    });
});
expressapp.post('/load_roadmap', function(req, res){
    console.log('load roadmap...');
    console.log(req.body['db']);
    connectDB(req.body, req.body['db'], req.body['collection'], 'findTarget', res);
    // connectDB(req.body, 'enow', 'recipes', 'findTarget', res);
});
expressapp.post('/get_broker', function(req, res){
    console.log('get broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});

expressapp.post('/add_secure', function(req, res){
    console.log('add secure...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'addSecure', res);
});

expressapp.get('/get_brokers', function(req, res){
    console.log('get brokers...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});
expressapp.get('/get_settings', function(req, res){
    console.log('get settings...');
    connectDB(null, 'connectionData', 'settings', 'find', res);
});
expressapp.get('/get_roadmaps', function(req, res){
    console.log('get roadmaps...');
    connectDB(null, 'enow', 'recipes', 'find', res);
});
expressapp.get('/get_running_roadmaps', function(req, res){
    console.log('get running roadmaps...');
    connectDB(null, 'enow', 'execute', 'find', res);
});
expressapp.get('/get_devices', function(req, res){
    console.log('get devices...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});

var server = expressapp.listen(expressapp.get('port'), function(){
    console.log("\n\n\n");
    console.log(
        "  ███████╗███╗   ██╗ ██████╗ ██╗    ██╗\
        \n  ██╔════╝████╗  ██║██╔═══██╗██║    ██║  ENOW Started!\
        \n  █████╗  ██╔██╗ ██║██║   ██║██║ █╗ ██║  Connect to 127.0.0.1:1111\
        \n  ██╔══╝  ██║╚██╗██║██║   ██║██║███╗██║\
        \n  ███████╗██║ ╚████║╚██████╔╝╚███╔███╔╝  Version 0.0.1\
        \n  ╚══════╝╚═╝  ╚═══╝ ╚═════╝  ╚══╝╚══╝   Copyright © 2016 ENOW. All rights reserved.");
    });
    function connectDB(source, dbName, collectionName, command, response){
        console.log('connecting to '+mongoUrl+':'+mongoPort+'...'+dbName+'.'+collectionName);
        console.log('connected!');
        var findDocument = function(callback){
            db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                response.send(result);
            });
        };
        var findBroker = function(callback){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                response.send(result);
            });
        };

        var findTarget = function(callback){
            console.log("abcd");
            var o_id = BSON.ObjectID.createFromHexString(source['_id']);
            db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){
                console.log(result);
                response.send(result);
                o_id = null;
            });
        }

        var findDevice = function(callback){
            db.db(dbName).collection(collectionName).find({deviceId:source['deviceId']}).toArray(function(err,result){
                response.send(result);
            });
        }

        var insertDocument = function(callback){
            var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                if(result.length!=0){
                    roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
                }
                else{
                    roadMapIdTemp = 1;
                }
                db.db(dbName).collection(collectionName).insertOne({
                    "roadMapId" : roadMapIdTemp.toString(),
                    "clientId" : source['clientId'],
                    "orderNode" : source['orderNode'],
                    "initNode" : source['initNode'],
                    "lastNode" : source['lastNode'],
                    "incomingNode" : source['incomingNode'],
                    "outingNode" : source['outingNode'],
                    "isInput" : source['isInput'],
                    "isOutput" : source['isOutput'],
                    "nodeIds" : source['nodeIds']
                },function(err, result){
                    response.send("done");
                });
            });

        };

        var insertDocumentDevice = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$push' : { 'deviceId': source['deviceId']}
            }, function(err,result){
                response.send("done");
            });
        };

        var insertDocumentBroker = function(callback){
            db.db(dbName).collection(collectionName).count({}, function(err, cnt) {
                db.db(dbName).collection(collectionName).insertOne({
                    "brokerNum" : (cnt+1).toString(),
                    "brokerId" : source['brokerId'],
                    "ipAddress" : source['ipAddress'],
                    "port" : source['port'],
                    "deviceId" : source['deviceId'],
                },function(err, result){
                    response.send("done");
                });
            });
        };

        var updateBroker = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$set' : { 'ca': source['ca'], 'hostCrt': source['hostCrt'], 'hostKey': source['hostKey']}
            }, function(err,result){
                response.send("done");
            });
        };

        var deleteDocument = function(callback){
            db.db(dbName).collection(collectionName).deleteOne({
            },function(err, result){
                response.send("done");
            });
        };

        if(command=="save" || command=="run"){
            insertDocument(db, function(){
            });
        }else if(command=="saveBroker"){
            insertDocumentBroker(db, function(){
            });
        }else if(command=="saveDevice"){
            insertDocumentDevice(db, function(){
            });
        }else if(command=="findDevice"){
            findDevice(db, function(){
            });
        }else if(command=="kill"){
            deleteDocument(db,function(){
            });
        }else if(command=="find"){
            findDocument(db, function(){
            });
        }else if(command=="findTarget"){
            console.log("qwertty");
            findTarget(db, function(){
            });
        }else if(command=="findBroker"){
            findBroker(db, function(){
            });
        }else if(command=="addSecure"){
            updateBroker(db, function(){
            });
        }
    };
<|endoftext|>