<commit_before>var couchWrapper = require('./couch-wrapper')

var http = require('http');
var crypto = require('crypto');

var users = [];
users["token"] = "kikoo";
var server = http.createServer().listen(8080, '127.0.0.1');

server.on('request', function(request, response) {
	var body = "";
	request.on('data', function(chunk) {
		body += chunk;
	});

	request.on('end', function() {
		function badRequest(body) {
			response.writeHead(400, "Bad Request");
			if (body)
				response.write(body);
			response.end();
		}

		console.log(body);

		/* we provide a public API */
		response.setHeader("Access-Control-Allow-Origin", "*");

		/* Parse request */
		parsedUrl = require('url').parse(request.url, true);

		/* Parse request's parameters */
		var params;
		try {
			if ((request.method == "POST" || request.method == "PUT" || request.method == "DELETE")) {
				if (body)
					params = JSON.parse(body);
				else
					params = {};

				// the token should be in the URL's query string
				if (parsedUrl.query.token)
					params.token = parsedUrl.query.token;
			}
			else if (request.method == "GET")
				params = parsedUrl.query;
			else
				params = {};
		}
		catch (error) {
			badRequest("Unable to parse parameters.");
		}

		console.log(params);

		/* CORS handling
		 * Thanks to nilcolor.
		 * https://gist.github.com/nilcolor/816580
		 */

		if (request.method === 'OPTIONS') {
			var headers = {};
			// IE8 does not allow domains to be specified, just the *
			// headers["Access-Control-Allow-Origin"] = req.headers.origin;
			// Already done
			// headers["Access-Control-Allow-Origin"] = "*";
			headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
			headers["Access-Control-Allow-Credentials"] = false;
			headers["Access-Control-Max-Age"] = '86400'; // 24 hours
			headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
			response.writeHead(200, headers);
			response.end();
		}

		/* USER */

		// Sign in
		else if (parsedUrl.pathname == "/users/signin" && request.method == "POST") {
			if (!params.login || !params.passwd) {
				badRequest("Login or password is missing.");
			}

			else {
				var shasum = crypto.createHash('sha512').update(params.passwd, 'utf8').digest('hex');
				couchWrapper.userLogin(params.login, function(user_data) {
					if (user_data && user_data.shasum && shasum == user_data.shasum) {
						users[user_data.uuid] = params.login;
						response.writeHead(200, "OK");
						response.write(JSON.stringify(user_data.uuid));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
		}

		// Sign out
		else if (parsedUrl.pathname == "/user/signout" && request.method == "POST") {
			if (params.token && users[params.token]) {
				delete users[params.token];
				response.writeHead(204, "No Content");
			}
			else {
				response.writeHead(401, "Unauthorized");
			}
			response.end();
		}

		// Sign up
		else if (parsedUrl.pathname == "/users/signup" && request.method == "POST") {
			if (!params.login || !params.passwd || !params.email || !params.imgUrl) {
				badRequest("Parameters are missing.");
			}
			else {
				// generate shasum...
				var shasum = crypto.createHash('sha512').update(params.passwd, 'utf8').digest('hex');
				params.shasum = shasum;
				// ... then delete the password
				delete params.passwd;
				couchWrapper.userCreate(params, function(uuid) {
					if (uuid) {
						users[uuid] = params.login
						response.writeHead(201, "Created");
						response.write(JSON.stringify(uuid));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
		}

		// Get a single user or get the authenticated user
		else if (((parsedUrl.pathname.indexOf('/users/') == 0 && parsedUrl.pathname.split('/').length == 3) || parsedUrl.pathname == '/user') && request.method == 'GET') {
			// determine the user
			var login = request.url.indexOf('/users/') == 0 ? request.url.substr('/users/'.length) : users[params.token];
			if (params.token && users[params.token]) {
				couchWrapper.userGet(login, function(user_object) {
					if (user_object) {
						couchWrapper.docByUser(login, function(docs_list) {
							if (docs_list !== null) {
								user_object.documents = docs_list;
								response.writeHead(200, "OK");
								response.write(JSON.stringify(user_object));
							}
							else {
								response.writeHead(403, "Forbidden");
							}
							response.end();
						});
					}
					else {
						response.writeHead(403, "Forbidden");
						response.end();
					}
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Delete the authenticated user
		else if (parsedUrl.pathname == "/user" && request.method == "DELETE") {
			if (params.token && users[params.token]) {
				couchWrapper.userDelete(users[params.token], function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
				delete users[params.token];
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Get the login associated to a token
		else if (parsedUrl.pathname.indexOf("/tokens/") == 0 && request.method == "GET") {
			if (parsedUrl.pathname == "/tokens/") {
				badRequest("Parameters are missing.");
			}
			else {
				if (users[parsedUrl.pathname.substr("/tokens/".length)]) {
					response.writeHead(200, "OK");
					response.write(JSON.stringify(users[parsedUrl.pathname.substr("/tokens/".length)]));
				}
				else {
					response.writeHead(404, "Not Found");
				}
				response.end();
			}
		}

		/* Document */

		// Create a single document
		else if (parsedUrl.pathname == "/documents" && request.method == "POST") {
			if (params.token && users[params.token]) {
				couchWrapper.docAdd(params, function(id) {
					if (id) {
						response.writeHead(201, "Created");
						response.write(JSON.stringify(id));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Update a document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "PUT") {
			if (params.token && users[params.token]) {
				couchWrapper.docUpdate(params, function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}

		}

		// Delete a document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "DELETE") {
			if (params.token && users[params.token]) {
				couchWrapper.docDelete(parsedUrl.pathname.substr('/documents/'.length), function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// List your documents or user documents
		else if ((parsedUrl.pathname == "/documents" || (parsedUrl.pathname.indexOf("/users/") == 0 && parsedUrl.pathname.indexOf("/documents") == parsedUrl.pathname.length - "/documents".length) && parsedUrl.pathname.split('/').length == 4) && request.method == "GET") {
			if (params.token && users[params.token]) {
				var login = parsedUrl.pathname == "/documents" ? users[params.token] : parsedUrl.pathname.substring('/users/'.length, parsedUrl.pathname.indexOf('/documents'));
				if (login) {
					couchWrapper.docByUser(login, function(docs_list) {
						if (docs_list !== null) {
							response.writeHead(200, "OK");
							response.write(JSON.stringify(docs_list));
						}
						else {
							response.writeHead(403, "Forbidden");
						}
						response.end();
					});
				}
				else {
					badRequest("Parameters are missing.");
				}
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Get a single document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "GET") {
			if (params.token && users[params.token]) {
				couchWrapper.docGet(parsedUrl.pathname.substr('/documents/'.length), function(doc) {
					if (doc) {
						response.writeHead(200, "OK");
						response.write(JSON.stringify(doc));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Default
		else {
			badRequest("The request does not match with an API function.");
		}
	});
});
<commit_msg>Fix token storage in server.js.<commit_after>var couchWrapper = require('./couch-wrapper')

var http = require('http');
var crypto = require('crypto');

var users = [];
users["token"] = "kikoo";
var server = http.createServer().listen(8080, '127.0.0.1');

server.on('request', function(request, response) {
	var body = "";
	request.on('data', function(chunk) {
		body += chunk;
	});

	request.on('end', function() {

		/* response handling */
		function badRequest(body) {
			response.writeHead(400, "Bad Request");
			if (body)
				response.write(body);
			response.end();
		}
		 // we provide a public API
		response.setHeader("Access-Control-Allow-Origin", "*");

		/* request handling */
		// parse request
		parsedUrl = require('url').parse(request.url, true);

		// parse request's parameters
		var params;
		try {
			if ((request.method == "POST" || request.method == "PUT" || request.method == "DELETE")) {
				if (body)
					params = JSON.parse(body);
				else
					params = {};
			}
			else if (request.method == "GET")
				params = parsedUrl.query;
			else
				params = {};
		}
		catch (error) {
			badRequest("Unable to parse parameters.");
		}
		var token = "";
		if (params.token) {
			token = params.token;
			delete params.token;
		}
		if (parsedUrl.query.token) {
			token = parsedUrl.query.token;
		}

		/* CORS handling
		 * Thanks to nilcolor.
		 * https://gist.github.com/nilcolor/816580
		 */

		if (request.method === 'OPTIONS') {
			var headers = {};
			// IE8 does not allow domains to be specified, just the *
			// headers["Access-Control-Allow-Origin"] = req.headers.origin;
			// Already done
			// headers["Access-Control-Allow-Origin"] = "*";
			headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
			headers["Access-Control-Allow-Credentials"] = false;
			headers["Access-Control-Max-Age"] = '86400'; // 24 hours
			headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
			response.writeHead(200, headers);
			response.end();
		}

		/* USER */

		// Sign in
		else if (parsedUrl.pathname == "/users/signin" && request.method == "POST") {
			if (!params.login || !params.passwd) {
				badRequest("Login or password is missing.");
			}

			else {
				var shasum = crypto.createHash('sha512').update(params.passwd, 'utf8').digest('hex');
				couchWrapper.userLogin(params.login, function(user_data) {
					if (user_data && user_data.shasum && shasum == user_data.shasum) {
						users[user_data.uuid] = params.login;
						response.writeHead(200, "OK");
						response.write(JSON.stringify(user_data.uuid));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
		}

		// Sign out
		else if (parsedUrl.pathname == "/user/signout" && request.method == "POST") {
			if (token && users[token]) {
				delete users[token];
				response.writeHead(204, "No Content");
			}
			else {
				response.writeHead(401, "Unauthorized");
			}
			response.end();
		}

		// Sign up
		else if (parsedUrl.pathname == "/users/signup" && request.method == "POST") {
			if (!params.login || !params.passwd || !params.email || !params.imgUrl) {
				badRequest("Parameters are missing.");
			}
			else {
				// generate shasum...
				var shasum = crypto.createHash('sha512').update(params.passwd, 'utf8').digest('hex');
				params.shasum = shasum;
				// ... then delete the password
				delete params.passwd;
				couchWrapper.userCreate(params, function(uuid) {
					if (uuid) {
						users[uuid] = params.login
						response.writeHead(201, "Created");
						response.write(JSON.stringify(uuid));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
		}

		// Get a single user or get the authenticated user
		else if (((parsedUrl.pathname.indexOf('/users/') == 0 && parsedUrl.pathname.split('/').length == 3) || parsedUrl.pathname == '/user') && request.method == 'GET') {
			// determine the user
			var login = request.url.indexOf('/users/') == 0 ? request.url.substr('/users/'.length) : users[token];
			if (token && users[token]) {
				couchWrapper.userGet(login, function(user_object) {
					if (user_object) {
						couchWrapper.docByUser(login, function(docs_list) {
							if (docs_list !== null) {
								user_object.documents = docs_list;
								response.writeHead(200, "OK");
								response.write(JSON.stringify(user_object));
							}
							else {
								response.writeHead(403, "Forbidden");
							}
							response.end();
						});
					}
					else {
						response.writeHead(403, "Forbidden");
						response.end();
					}
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Delete the authenticated user
		else if (parsedUrl.pathname == "/user" && request.method == "DELETE") {
			if (token && users[token]) {
				couchWrapper.userDelete(users[token], function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
				delete users[token];
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Get the login associated to a token
		else if (parsedUrl.pathname.indexOf("/tokens/") == 0 && request.method == "GET") {
			if (parsedUrl.pathname == "/tokens/") {
				badRequest("Parameters are missing.");
			}
			else {
				if (users[parsedUrl.pathname.substr("/tokens/".length)]) {
					response.writeHead(200, "OK");
					response.write(JSON.stringify(users[parsedUrl.pathname.substr("/tokens/".length)]));
				}
				else {
					response.writeHead(404, "Not Found");
				}
				response.end();
			}
		}

		/* Document */

		// Create a single document
		else if (parsedUrl.pathname == "/documents" && request.method == "POST") {
			if (token && users[token]) {
				couchWrapper.docAdd(params, function(id) {
					if (id) {
						response.writeHead(201, "Created");
						response.write(JSON.stringify(id));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Update a document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "PUT") {
			if (token && users[token]) {
				couchWrapper.docUpdate(params, function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}

		}

		// Delete a document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "DELETE") {
			if (token && users[token]) {
				couchWrapper.docDelete(parsedUrl.pathname.substr('/documents/'.length), function(success) {
					if (success) {
						response.writeHead(204, "No Content");
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// List your documents or user documents
		else if ((parsedUrl.pathname == "/documents" || (parsedUrl.pathname.indexOf("/users/") == 0 && parsedUrl.pathname.indexOf("/documents") == parsedUrl.pathname.length - "/documents".length) && parsedUrl.pathname.split('/').length == 4) && request.method == "GET") {
			if (token && users[token]) {
				var login = parsedUrl.pathname == "/documents" ? users[token] : parsedUrl.pathname.substring('/users/'.length, parsedUrl.pathname.indexOf('/documents'));
				if (login) {
					couchWrapper.docByUser(login, function(docs_list) {
						if (docs_list !== null) {
							response.writeHead(200, "OK");
							response.write(JSON.stringify(docs_list));
						}
						else {
							response.writeHead(403, "Forbidden");
						}
						response.end();
					});
				}
				else {
					badRequest("Parameters are missing.");
				}
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Get a single document
		else if (parsedUrl.pathname.indexOf("/documents/") == 0 && request.method == "GET") {
			if (token && users[token]) {
				couchWrapper.docGet(parsedUrl.pathname.substr('/documents/'.length), function(doc) {
					if (doc) {
						response.writeHead(200, "OK");
						response.write(JSON.stringify(doc));
					}
					else {
						response.writeHead(403, "Forbidden");
					}
					response.end();
				});
			}
			else {
				response.writeHead(401, "Unauthorized");
				response.end();
			}
		}

		// Default
		else {
			badRequest("The request does not match with an API function.");
		}
	});
});
<|endoftext|>


<commit_before>(function() {
	var editorModule = angular.module('baddEditor', []);

	var editorController = function($scope, $window) {
		// if attr are not set, use default values
		$scope.title = angular.isDefined($scope.title) ? $scope.title : 'Bootstrap visual editor';
		$scope.componentsTitle = angular.isDefined($scope.componentsTitle) ? $scope.componentsTitle : 'Components';

		$window.addEventListener('message', function() {
			alert('received something');
		});

		// default draggable components
		$scope.draggables = [
			{ titleLg: 'Row', title: 'ROW', label:'row', element: '

A simple row with a single column

' },
			{ titleLg: 'Column', title: 'COL', label:'col', element: '

You can make me a smaller column

' },
			{ titleLg: 'Header 1', title: 'H1', label:'h1', element: '
An important title
' },
			{ titleLg: 'Header 2', title: 'H2', label:'h2', element: '
A secondary title
' },
			{ titleLg: 'Header 3', title: 'H3', label:'h3', element: '
A third level title
' },
			{ titleLg: 'Header 4', title: 'H4', label:'h4', element: '
A fourth level title
' },
			{ titleLg: 'Paragraph', title: 'P', label:'p', element: '
Write something useful here
' },
			{ titleLg: 'Button', title: 'BTN', label:'btn', element: '<btn class="btn btn-primary">My brand new button</btn>' },
			{ titleLg: 'Jumbotron', title: 'JMB', label:'jmb', element: '

Hello, world!

My name is Jumbotron

' },
			{ titleLg: 'Panel', title: 'PNL', label:'pnl', element: '

Panel title

Panel content

' },
			{ titleLg: 'Well', title: 'WLL', label:'wll', element: '
Look, I\'m in a well.
' },
			{ titleLg: 'Image', title: 'IMG', label:'img', element: '' }
		];
	};
	editorController.$inject = ['$scope', '$window'];

	var editorDirective = function () {
		return {
			restrict: 'E',
			templateUrl: 'badd-editor.html',
			scope: {
				title: '@',
				componentsTitle: '@',
				template: '@'
			},
			controller: editorController
		};
	};

	editorModule.directive('baddEditor', editorDirective);

	var editorService = function($compile, $document) {
		var service = this;

		service.initializeFrame = function(frame, scope) {
			return function () {
				service.document = $document[0];

				// set service properties with raw dom html5 element
				service.iframe = frame[0];
				service.frame = frame.contents()[0];
				service.frameHtml = service.frame.querySelector('html');
				service.frameHead = service.frame.querySelector('head');
				service.frameBody = service.frame.querySelector('body');

				// create transfer area
				service.transferArea = service.document.createElement('div');
				service.transferArea.className = 'badd-transfer-area';
				service.frameBody.appendChild(service.transferArea);

				// create droppable area highlighter
				service.transferArea.innerHTML = '<svg class="badd-highlighter"></svg>';
				service.highlightBorder = service.transferArea.childNodes[0];
				service.frameBody.appendChild(service.highlightBorder);

				// start baddEditor module
				service.frameHtml.setAttribute('ng-app', 'baddEditor');

				// give editable style to editable page
				service.stylesheet = service.document.createElement('link');
				service.stylesheet.setAttribute('rel', 'stylesheet');
				service.stylesheet.setAttribute('href', 'badd-editor-frame.min.css');
				service.stylesheet.setAttribute('type', 'text/css');
				service.frameHead.appendChild(service.stylesheet);

				// enable controller on body
				service.frameBody.setAttribute('badd-droppable', '');
				service.frameBody.setAttribute('badd-configurable', '');

				// make divs droppable
				var divs = _.toArray(service.frameBody.querySelectorAll('div'));
				divs.forEach(function(div) {
					if (div.className !== 'badd-highlight' && div.className !== 'badd-transfer-area') {
						div.setAttribute('badd-droppable', '');
					}
				});

				// make everything else draggable and configurable
				var elements = _.toArray(service.frameBody.querySelectorAll('*'));
				elements.forEach(function(element) {
					if (element.className !== 'badd-highlight' && element.className !== 'badd-transfer-area') {
						element.setAttribute('badd-draggable', '');
						element.setAttribute('badd-configurable', '');
					}
				});

				$compile(service.frameHtml)(scope);
			};
		};

		service.startDragging = function (event) {
			event.dataTransfer.setData('text', 'firefox needs data');

			if (event.target.getAttribute('badd-configurable') === '') {
				service.previewElement = event.target;
			} else {
				service.transferArea.innerHTML = event.target.getAttribute('data-element');
				service.previewElement = service.transferArea.querySelector('*');
			}
		};

		service.stopDragging = function(event) {
			service.transferArea.innerHTML = '';
			if (service.previewElement && service.previewElement.parentNode) {
				service.previewElement.parentNode.removeChild(service.previewElement);
				service.previewElement = null;
			}
			service.hideHighlightBorder();
		};

		service.elementEntering = function(event) {
			service.previewElement.classList.remove('badd-hidden-preview-element');

			event.stopPropagation();
			event.preventDefault();
		};

		service.elementLeaving = function (event) {
			var iframePosition = service.iframe.getBoundingClientRect();
			var elementBeingHovered = service.document.elementFromPoint(event.clientX + iframePosition.left,
																		event.clientY + iframePosition.top);
			if (elementBeingHovered == null || elementBeingHovered.tagName !== 'IFRAME' ||
				! _.contains(elementBeingHovered.classList, 'badd-editor-browser')) {

				service.previewElement.classList.add('badd-hidden-preview-element');
				service.hideHighlightBorder();
			}
		};

		service.elementHovering = function(event) {
			event.stopPropagation();
			event.preventDefault();

			if (!event.target.getAttribute
				|| event.target === service.previewElement
				|| event.target.getAttribute('badd-droppable') !== '') {

				return;
			}

			var children = _.toArray(event.target.childNodes);
			var nearestSibling = null;
			var nearestSiblingPosition = null;
			children.forEach(function(child) {
				if (!child.getBoundingClientRect || child.className == 'badd-transfer-area'
					|| child.className == 'badd-highlighter'
					|| child == service.previewElement) {

					//this does not break. _.each will run the whole array
					return;
				}

				var childPosition = child.getBoundingClientRect();

				var childCenter = {
					X: childPosition.width / 2 + childPosition.left,
					Y: childPosition.height / 2 + childPosition.top
				};

				var belowThreshold = childCenter.Y;
				if (belowThreshold - childPosition.top > 30) {
					// no need to be so greedy
					belowThreshold = childPosition.top + 30;
				}

				var besidesThreshold = childCenter.X;
				if (besidesThreshold - childPosition.left > 30) {
					// no need to be so greedy
					besidesThreshold = childPosition.left + 30;
				}

				if ((event.clientY > belowThreshold && event.clientX > besidesThreshold)
					|| (event.clientY > childPosition.bottom)){
					//this does not break. _.each will run the whole array
					return;
				}

				if (nearestSibling == null) {
					nearestSibling = child;
					nearestSiblingPosition = childPosition;
				} else if (nearestSiblingPosition.left >= childPosition.left
							&& nearestSiblingPosition.top >= childPosition.top) {
					nearestSibling = child;
					nearestSiblingPosition = childPosition;
				}
			});

			if (nearestSibling) {
				event.target.insertBefore(service.previewElement, nearestSibling);
			} else {
				event.target.appendChild(service.previewElement);
			}
			service.showHighlightBorder(event.target);
		};

		service.elementDropped = function(event) {
			event.stopPropagation();
			event.preventDefault();

			if (service.previewElement.getAttribute('badd-draggable') !== '') {
				service.previewElement.setAttribute('badd-draggable', '');
				service.previewElement.setAttribute('badd-configurable', '');
			}
			service.previewElement = null;
		};

		service.showHighlightBorder = function(target) {
			var targetPosition = target.getBoundingClientRect();
			service.highlightBorder.style.top = targetPosition.top + 'px';
			service.highlightBorder.style.left = targetPosition.left + 'px';
			service.highlightBorder.style.width = target.offsetWidth + 'px';
			service.highlightBorder.style.height = target.offsetHeight + 'px';
			service.highlightBorder.style.display = 'block';
		};

		service.hideHighlightBorder = function() {
			service.highlightBorder.style.display = 'none';
			service.highlightBorder.style.top = 0;
			service.highlightBorder.style.left = 0;
			service.highlightBorder.style.width = 0;
			service.highlightBorder.style.height = 0;
		};

		service.mouseHovering = function(event) {
			event.stopPropagation();
			event.preventDefault();

			service.showHighlightBorder(event.target);
		};

		service.mouseClick = function(event) {
			event.stopPropagation();
			event.preventDefault();

			console.log('mouseClick - ' + event.target.className);
		};

		service.mouseLeaving = function(event) {
			event.stopPropagation();
			event.preventDefault();

			service.hideHighlightBorder();
		}
	};
	editorService.$inject = ['$compile', '$document'];
	editorModule.service('editorService', editorService);
}());
<commit_msg>updating highlight border after scrolling<commit_after>(function() {
	var editorModule = angular.module('baddEditor', []);

	var editorController = function($scope, $window) {
		// if attr are not set, use default values
		$scope.title = angular.isDefined($scope.title) ? $scope.title : 'Bootstrap visual editor';
		$scope.componentsTitle = angular.isDefined($scope.componentsTitle) ? $scope.componentsTitle : 'Components';

		$window.addEventListener('message', function() {
			alert('received something');
		});

		// default draggable components
		$scope.draggables = [
			{ titleLg: 'Row', title: 'ROW', label:'row', element: '

A simple row with a single column

' },
			{ titleLg: 'Column', title: 'COL', label:'col', element: '

You can make me a smaller column

' },
			{ titleLg: 'Header 1', title: 'H1', label:'h1', element: '
An important title
' },
			{ titleLg: 'Header 2', title: 'H2', label:'h2', element: '
A secondary title
' },
			{ titleLg: 'Header 3', title: 'H3', label:'h3', element: '
A third level title
' },
			{ titleLg: 'Header 4', title: 'H4', label:'h4', element: '
A fourth level title
' },
			{ titleLg: 'Paragraph', title: 'P', label:'p', element: '
Write something useful here
' },
			{ titleLg: 'Button', title: 'BTN', label:'btn', element: '<btn class="btn btn-primary">My brand new button</btn>' },
			{ titleLg: 'Jumbotron', title: 'JMB', label:'jmb', element: '

Hello, world!

My name is Jumbotron

' },
			{ titleLg: 'Panel', title: 'PNL', label:'pnl', element: '

Panel title

Panel content

' },
			{ titleLg: 'Well', title: 'WLL', label:'wll', element: '
Look, I\'m in a well.
' },
			{ titleLg: 'Image', title: 'IMG', label:'img', element: '' }
		];
	};
	editorController.$inject = ['$scope', '$window'];

	var editorDirective = function () {
		return {
			restrict: 'E',
			templateUrl: 'badd-editor.html',
			scope: {
				title: '@',
				componentsTitle: '@',
				template: '@'
			},
			controller: editorController
		};
	};

	editorModule.directive('baddEditor', editorDirective);

	var editorService = function($compile, $document) {
		var service = this;

		service.initializeFrame = function(frame, scope) {
			return function () {
				service.document = $document[0];

				// set service properties with raw dom html5 element
				service.iframe = frame[0];
				service.frame = frame.contents()[0];
				service.frame.addEventListener("scroll", service.updateHighlightBorderPosition);
				service.frameHtml = service.frame.querySelector('html');
				service.frameHead = service.frame.querySelector('head');
				service.frameBody = service.frame.querySelector('body');

				// create transfer area
				service.transferArea = service.document.createElement('div');
				service.transferArea.className = 'badd-transfer-area';
				service.frameBody.appendChild(service.transferArea);

				// create droppable area highlighter
				service.transferArea.innerHTML = '<svg class="badd-highlighter"></svg>';
				service.highlightBorder = service.transferArea.childNodes[0];
				service.frameBody.appendChild(service.highlightBorder);

				// start baddEditor module
				service.frameHtml.setAttribute('ng-app', 'baddEditor');

				// give editable style to editable page
				service.stylesheet = service.document.createElement('link');
				service.stylesheet.setAttribute('rel', 'stylesheet');
				service.stylesheet.setAttribute('href', 'badd-editor-frame.min.css');
				service.stylesheet.setAttribute('type', 'text/css');
				service.frameHead.appendChild(service.stylesheet);

				// enable controller on body
				service.frameBody.setAttribute('badd-droppable', '');
				service.frameBody.setAttribute('badd-configurable', '');

				// make divs droppable
				var divs = _.toArray(service.frameBody.querySelectorAll('div'));
				divs.forEach(function(div) {
					if (div.className !== 'badd-highlight' && div.className !== 'badd-transfer-area') {
						div.setAttribute('badd-droppable', '');
					}
				});

				// make everything else draggable and configurable
				var elements = _.toArray(service.frameBody.querySelectorAll('*'));
				elements.forEach(function(element) {
					if (element.className !== 'badd-highlight' && element.className !== 'badd-transfer-area') {
						element.setAttribute('badd-draggable', '');
						element.setAttribute('badd-configurable', '');
					}
				});

				$compile(service.frameHtml)(scope);
			};
		};

		service.startDragging = function (event) {
			event.dataTransfer.setData('text', 'firefox needs data');

			if (event.target.getAttribute('badd-configurable') === '') {
				service.previewElement = event.target;
			} else {
				service.transferArea.innerHTML = event.target.getAttribute('data-element');
				service.previewElement = service.transferArea.querySelector('*');
			}
		};

		service.stopDragging = function(event) {
			service.transferArea.innerHTML = '';
			if (service.previewElement && service.previewElement.parentNode) {
				service.previewElement.parentNode.removeChild(service.previewElement);
				service.previewElement = null;
			}
			service.hideHighlightBorder();
		};

		service.elementEntering = function(event) {
			service.previewElement.classList.remove('badd-hidden-preview-element');

			event.stopPropagation();
			event.preventDefault();
		};

		service.elementLeaving = function (event) {
			var iframePosition = service.iframe.getBoundingClientRect();
			var elementBeingHovered = service.document.elementFromPoint(event.clientX + iframePosition.left,
																		event.clientY + iframePosition.top);
			if (elementBeingHovered == null || elementBeingHovered.tagName !== 'IFRAME' ||
				! _.contains(elementBeingHovered.classList, 'badd-editor-browser')) {

				service.previewElement.classList.add('badd-hidden-preview-element');
				service.hideHighlightBorder();
			}
		};

		service.elementHovering = function(event) {
			event.stopPropagation();
			event.preventDefault();

			if (!event.target.getAttribute
				|| event.target === service.previewElement
				|| event.target.getAttribute('badd-droppable') !== '') {

				return;
			}

			var children = _.toArray(event.target.childNodes);
			var nearestSibling = null;
			var nearestSiblingPosition = null;
			children.forEach(function(child) {
				if (!child.getBoundingClientRect || child.className == 'badd-transfer-area'
					|| child.className == 'badd-highlighter'
					|| child == service.previewElement) {

					//this does not break. _.each will run the whole array
					return;
				}

				var childPosition = child.getBoundingClientRect();

				var childCenter = {
					X: childPosition.width / 2 + childPosition.left,
					Y: childPosition.height / 2 + childPosition.top
				};

				var belowThreshold = childCenter.Y;
				if (belowThreshold - childPosition.top > 30) {
					// no need to be so greedy
					belowThreshold = childPosition.top + 30;
				}

				var besidesThreshold = childCenter.X;
				if (besidesThreshold - childPosition.left > 30) {
					// no need to be so greedy
					besidesThreshold = childPosition.left + 30;
				}

				if ((event.clientY > belowThreshold && event.clientX > besidesThreshold)
					|| (event.clientY > childPosition.bottom)){
					//this does not break. _.each will run the whole array
					return;
				}

				if (nearestSibling == null) {
					nearestSibling = child;
					nearestSiblingPosition = childPosition;
				} else if (nearestSiblingPosition.left >= childPosition.left
							&& nearestSiblingPosition.top >= childPosition.top) {
					nearestSibling = child;
					nearestSiblingPosition = childPosition;
				}
			});

			if (nearestSibling) {
				event.target.insertBefore(service.previewElement, nearestSibling);
			} else {
				event.target.appendChild(service.previewElement);
			}
			service.showHighlightBorder(event.target);
		};

		service.elementDropped = function(event) {
			event.stopPropagation();
			event.preventDefault();

			if (service.previewElement.getAttribute('badd-draggable') !== '') {
				service.previewElement.setAttribute('badd-draggable', '');
				service.previewElement.setAttribute('badd-configurable', '');
			}
			service.previewElement = null;
		};

		service.updateHighlightBorderPosition = function() {
			if (service.highlightBorder.style.display === 'block' && service.lastHoveredTarget) {
				service.showHighlightBorder(service.lastHoveredTarget);
			}
		};

		service.showHighlightBorder = function(target) {
			var targetPosition = target.getBoundingClientRect();
			service.highlightBorder.style.top = targetPosition.top + 'px';
			service.highlightBorder.style.left = targetPosition.left + 'px';
			service.highlightBorder.style.width = target.offsetWidth + 'px';
			service.highlightBorder.style.height = target.offsetHeight + 'px';
			service.highlightBorder.style.display = 'block';
			service.lastHoveredTarget = target;
		};

		service.hideHighlightBorder = function() {
			service.highlightBorder.style.display = 'none';
			service.highlightBorder.style.top = 0;
			service.highlightBorder.style.left = 0;
			service.highlightBorder.style.width = 0;
			service.highlightBorder.style.height = 0;
		};

		service.mouseHovering = function(event) {
			event.stopPropagation();
			event.preventDefault();

			service.showHighlightBorder(event.target);
		};

		service.mouseClick = function(event) {
			event.stopPropagation();
			event.preventDefault();

			console.log('mouseClick - ' + event.target.className);
		};

		service.mouseLeaving = function(event) {
			event.stopPropagation();
			event.preventDefault();

			service.hideHighlightBorder();
		};
	};
	editorService.$inject = ['$compile', '$document'];
	editorModule.service('editorService', editorService);
}());
<|endoftext|>


<commit_before>/*    Copyright 2019-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

let instance = null;

const log = require('../../net2/logger.js')(__filename);

const sem = require('../../sensor/SensorEventManager.js').getInstance();

const rclient = require('../../util/redis_manager').getRedisClient();

const _ = require('lodash');

const exec = require('child-process-promise').exec;

const f = require('../../net2/Firewalla.js');

const configKey = "ext.wireguard.config";
const sharedPeerConfigKey = "ext.wireguard.peers.config";

const sysManager = require('../../net2/SysManager.js')
const firerouter = require('../../net2/FireRouter.js')

const intf = "wg0";

const fs = require('fs');

const Promise = require('bluebird');
Promise.promisifyAll(fs);

class WireGuard {
  constructor() {
    if (instance === null) {
      instance = this;
      this.config = {};
      this.ready = false;
    }
    return instance;
  }

  async randomServerConfig() {
    const privateKey = (await exec("wg genkey")).stdout.replace("\n", "");
    const publicKey = (await exec(`echo ${privateKey} | wg pubkey`)).stdout.replace("\n", "");
    const listenPort = 36060;
    const localNet = "10.1.0.0/24";
    const localAddressCIDR = "10.1.0.1/24";
    return {
      privateKey, publicKey, listenPort, localAddress, localNet, intf, localAddressCIDR
    };
  }

  async randomClientConfig() {
    const privateKey = (await exec("wg genkey")).stdout.replace("\n", "");
    const publicKey = (await exec(`echo ${privateKey} | wg pubkey`)).stdout.replace("\n", "");

    const localAddress = `10.1.0.${Math.floor(Math.random()*253) + 2}/24`;

    return {
      privateKey, publicKey, localAddress
    };
  }

  async getConfig() {
    const redisConfig = await rclient.getAsync(configKey);
    if (redisConfig) {
      try {
        return JSON.parse(redisConfig);
      } catch (err) {
        log.error("Got error when parsing wg config, err:", err);
        return null;
      }
    } else {
      const config = await this.randomServerConfig();
      await rclient.setAsync(configKey, JSON.stringify(config));
      return config;
    }
  }

  async createPeer(id) {
    const peerConfig = await this.randomClientConfig();
    peerConfig.id = id;
    await rclient.saddAsync(sharedPeerConfigKey, JSON.stringify(peerConfig));
    const config = await this.getConfig();
    await this.addPeer(config, peerConfig);
  }

  async getAllPeers() {
    const configs = [];
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for(const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        if(peerConfig && peerConfig.id === id) {
          config.push(peerConfig);
        }
      } catch(err) {
        log.error("Failed to parse config, err:", err);
      }
    }

    return configs;
  }

  async getPeer(id) {
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for(const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        if(peerConfig && peerConfig.id === id) {
          return peerConfig;
        }
      } catch(err) {
        log.error("Failed to parse config, err:", err);
      }
    }
  }

  async start() {
    const config = await this.getConfig();
    log.info(`Starting wireguard on interface ${config.intf}`);
    log.info("Config is", config);
    await exec(`sudo ip link add dev ${config.intf} type wireguard`).catch(() => undefined);
    await exec(`sudo wg set ${config.intf} listen-port ${config.listenPort}`);
    const privateKeyLocation = `/etc/wireguard/${config.intf}.privateKey`;
    await exec(`echo ${config.privateKey} | sudo bash -c 'cat > ${privateKeyLocation}'`);
    await exec(`sudo wg set ${config.intf} private-key ${privateKeyLocation}`);
    //await exec(`sudo wg setconfig ${config.intf} ${runtimeConfigFile}`).catch(() => undefined);
    await exec(`sudo ip addr add ${config.localAddressCIDR} dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo ip link set up dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo iptables -t nat -A POSTROUTING -o ${firerouter.getDefaultWanIntfName()} -j MASQUERADE`).catch(() => undefined);
    await exec(`sudo ip rule add from all iif ${config.intf} lookup wan_routable`).catch(() => undefined);
    await this.addPeers().catch(() => undefined);
    log.info(`Wireguard ${config.intf} is started successfully.`);
  }

  async addPeers() {
    const config = await this.getConfig();
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for (const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        await this.addPeer(config, peerConfig);
      } catch (err) {
        log.error("Got error when parsing peerConfig, err:", peer);
      }
    }
  }

  async addPeer(config, peerConfig) {
    const pubKey = peerConfig && peerConfig.publicKey;
    if (pubKey) {
      log.info(`Adding Peer ${pubKey}...`);
      await exec(`sudo wg set ${config.intf} peer ${pubKey} allowed-ips 0.0.0.0/0`).catch((err) => {
        log.error("Got error when adding peer to wg, err:", err);
      });
    }
  }

  async stop() {
    const config = await this.getConfig();
    log.info(`Stopping wireguard ${config.intf}...`);
    await exec(`sudo ip rule del from all iif ${config.intf} lookup wan_routable`).catch(() => undefined);
    await exec(`sudo iptables -t nat -D POSTROUTING -o ${firerouter.getDefaultWanIntfName()} -j MASQUERADE`).catch(() => undefined);
    await exec(`sudo ip link set down dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo ip link del dev ${config.intf}`).catch(() => undefined);
    log.info(`Wireguard ${config.intf} is stopped successfully.`);
  }

  async restart() {
    await this.stop();
    await this.start();
  }
}

module.exports = new WireGuard();
<commit_msg>add ipsets<commit_after>/*    Copyright 2019-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

let instance = null;

const log = require('../../net2/logger.js')(__filename);

const sem = require('../../sensor/SensorEventManager.js').getInstance();

const rclient = require('../../util/redis_manager').getRedisClient();

const _ = require('lodash');

const exec = require('child-process-promise').exec;

const f = require('../../net2/Firewalla.js');

const configKey = "ext.wireguard.config";
const sharedPeerConfigKey = "ext.wireguard.peers.config";

const sysManager = require('../../net2/SysManager.js')
const firerouter = require('../../net2/FireRouter.js')

const intf = "wg0";

const fs = require('fs');

const Promise = require('bluebird');
Promise.promisifyAll(fs);

class WireGuard {
  constructor() {
    if (instance === null) {
      instance = this;
      this.config = {};
      this.ready = false;
    }
    return instance;
  }

  async randomServerConfig() {
    const privateKey = (await exec("wg genkey")).stdout.replace("\n", "");
    const publicKey = (await exec(`echo ${privateKey} | wg pubkey`)).stdout.replace("\n", "");
    const listenPort = 36060;
    const localNet = "10.1.0.0/24";
    const localAddressCIDR = "10.1.0.1/24";
    return {
      privateKey, publicKey, listenPort, localAddress, localNet, intf, localAddressCIDR
    };
  }

  async randomClientConfig() {
    const privateKey = (await exec("wg genkey")).stdout.replace("\n", "");
    const publicKey = (await exec(`echo ${privateKey} | wg pubkey`)).stdout.replace("\n", "");

    const localAddress = `10.1.0.${Math.floor(Math.random()*253) + 2}/24`;

    return {
      privateKey, publicKey, localAddress
    };
  }

  async getConfig() {
    const redisConfig = await rclient.getAsync(configKey);
    if (redisConfig) {
      try {
        return JSON.parse(redisConfig);
      } catch (err) {
        log.error("Got error when parsing wg config, err:", err);
        return null;
      }
    } else {
      const config = await this.randomServerConfig();
      await rclient.setAsync(configKey, JSON.stringify(config));
      return config;
    }
  }

  async createPeer(id) {
    const peerConfig = await this.randomClientConfig();
    peerConfig.id = id;
    await rclient.saddAsync(sharedPeerConfigKey, JSON.stringify(peerConfig));
    const config = await this.getConfig();
    await this.addPeer(config, peerConfig);
  }

  async getAllPeers() {
    const configs = [];
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for(const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        if(peerConfig && peerConfig.id === id) {
          config.push(peerConfig);
        }
      } catch(err) {
        log.error("Failed to parse config, err:", err);
      }
    }

    return configs;
  }

  async getPeer(id) {
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for(const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        if(peerConfig && peerConfig.id === id) {
          return peerConfig;
        }
      } catch(err) {
        log.error("Failed to parse config, err:", err);
      }
    }
  }

  async start() {
    const config = await this.getConfig();
    log.info(`Starting wireguard on interface ${config.intf}`);
    log.info("Config is", config);
    await exec(`sudo ip link add dev ${config.intf} type wireguard`).catch(() => undefined);
    await exec(`sudo wg set ${config.intf} listen-port ${config.listenPort}`);
    const privateKeyLocation = `/etc/wireguard/${config.intf}.privateKey`;
    await exec(`echo ${config.privateKey} | sudo bash -c 'cat > ${privateKeyLocation}'`);
    await exec(`sudo wg set ${config.intf} private-key ${privateKeyLocation}`);
    //await exec(`sudo wg setconfig ${config.intf} ${runtimeConfigFile}`).catch(() => undefined);
    await exec(`sudo ip addr add ${config.localAddressCIDR} dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo ip link set up dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo iptables -t nat -A POSTROUTING -o ${firerouter.getDefaultWanIntfName()} -j MASQUERADE`).catch(() => undefined);
    await exec(`sudo ip rule add from all iif ${config.intf} lookup wan_routable`).catch(() => undefined);

    // FIXME: should support in FireRouter
    const ipsetName = `c_net_vpn-${config.intf}_set`;
    await exec(`sudo ipset create -! ${ipsetName} hash:net,iface maxelem 1024`).catch((err) => undefined);
    await exec(`sudo ipset add -! ${ipsetName} 10.1.0.0/24,wg0`)
    await exec(`sudo ipset add -! monitored_net_set ${ipsetName}`);

    await this.addPeers().catch(() => undefined);
    log.info(`Wireguard ${config.intf} is started successfully.`);
  }

  async addPeers() {
    const config = await this.getConfig();
    const peers = await rclient.smembersAsync(sharedPeerConfigKey);
    for (const peer of peers) {
      try {
        const peerConfig = JSON.parse(peer);
        await this.addPeer(config, peerConfig);
      } catch (err) {
        log.error("Got error when parsing peerConfig, err:", peer);
      }
    }
  }

  async addPeer(config, peerConfig) {
    const pubKey = peerConfig && peerConfig.publicKey;
    if (pubKey) {
      log.info(`Adding Peer ${pubKey}...`);
      await exec(`sudo wg set ${config.intf} peer ${pubKey} allowed-ips 0.0.0.0/0`).catch((err) => {
        log.error("Got error when adding peer to wg, err:", err);
      });
    }
  }

  async stop() {
    const config = await this.getConfig();
    log.info(`Stopping wireguard ${config.intf}...`);
    await exec(`sudo ip rule del from all iif ${config.intf} lookup wan_routable`).catch(() => undefined);
    await exec(`sudo iptables -t nat -D POSTROUTING -o ${firerouter.getDefaultWanIntfName()} -j MASQUERADE`).catch(() => undefined);
    await exec(`sudo ip link set down dev ${config.intf}`).catch(() => undefined);
    await exec(`sudo ip link del dev ${config.intf}`).catch(() => undefined);
    log.info(`Wireguard ${config.intf} is stopped successfully.`);
  }

  async restart() {
    await this.stop();
    await this.start();
  }
}

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


<commit_before>'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
var render = require('./utils').render;

/**
* Backbone view for transcription form for creating a new transcription
* @class TranscriptionFormView
* @constructor
* @extends Backbone.View
*/
module.exports = Backbone.View.extend({
  events :{
  	'click #submitBtn': 'save',
    "keypress .form-control": "onEnterListener"

  },

  onEnterListener: function(e){
    var key = e.which || e.keyCode;
    if (key === 13 ) { // 13 is enter
      // code for enter
       e.preventDefault();
    }
  },

  save: function(e){
  	e.preventDefault();

    var sttEngine;

    //reading values from form
    var newTitle        = this.$('input[name=title]').val();
    var newDescription  = this.$('textarea[name=description]').val();;
    var newFilePath     = this.$('input[name=file]').val();
    var newLanguage     = $('#languageModel').find(":selected")[0].value;

    if($('#IBMoption')[0].checked){
      sttEngine         = "ibm";
    }else if($('#genelteOption')[0].checked){
       sttEngine        = "gentle";
    };

    var newSTTLanguage  = $('#IBMoption')[0].checked;

  	this.model.save({title: newTitle, description: newDescription,videoUrl:newFilePath, languageModel: newLanguage, sttEngine: sttEngine},{
      success: function(mode, response, option){
           Backbone.history.navigate("transcriptions", {trigger:true});
      },
      error: function(model, xhr,options){
        var errors = JSON.parse(xhr.responseText).errors;
        alert("ops, something when wrong with saving the transcription:" + errors)
      }
    });
  },

  render: function(){
    this.$el.html(render('transcriptionFormTemplate', this.model.attributes));
    return this;
  }
});
<commit_msg>Removed the # substitution thing coz it was in wrong place<commit_after>'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
var render = require('./utils').render;

/**
* Backbone view for transcription form for creating a new transcription
* @class TranscriptionFormView
* @constructor
* @extends Backbone.View
*/
module.exports = Backbone.View.extend({
  events :{
  	'click #submitBtn': 'save',
    "keypress .form-control": "onEnterListener"

  },

  onEnterListener: function(e){
    var key = e.which || e.keyCode;
    if (key === 13 ) { // 13 is enter
      // code for enter
       e.preventDefault();
    }
  },

  save: function(e){
  	e.preventDefault();

    var sttEngine;

    //reading values from form
    var newTitle        = this.$('input[name=title]').val();
    var newDescription  = this.$('textarea[name=description]').val();;
    //removing # carachter coz it breaks file path as it gets converted to %23
    //TODO: there might be other symbols that have effect. figure proper way to sanitise input
    var newFilePath     = this.$('input[name=file]').val();
    var newLanguage     = $('#languageModel').find(":selected")[0].value;

    if($('#IBMoption')[0].checked){
      sttEngine         = "ibm";
    }else if($('#genelteOption')[0].checked){
       sttEngine        = "gentle";
    };

    var newSTTLanguage  = $('#IBMoption')[0].checked;

  	this.model.save({title: newTitle, description: newDescription,videoUrl:newFilePath, languageModel: newLanguage, sttEngine: sttEngine},{
      success: function(mode, response, option){
           Backbone.history.navigate("transcriptions", {trigger:true});
      },
      error: function(model, xhr,options){
        var errors = JSON.parse(xhr.responseText).errors;
        alert("ops, something when wrong with saving the transcription:" + errors)
      }
    });
  },

  render: function(){
    this.$el.html(render('transcriptionFormTemplate', this.model.attributes));
    return this;
  }
});
<|endoftext|>


<commit_before>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';

import BaseBinding from 'axiom/bindings/base';
import FileSystem from 'axiom/bindings/fs/file_system';

/**
 * A binding that represents a running executable on FileSystem.
 *
 * You should only create an ExecuteContext by calling an instance of
 * FileSystem..createContext('execute', ...).
 *
 * @param {FileSystem} The parent file system.
 */
export var ExecuteContext = function(fileSystem, pathSpec, arg) {
  BaseBinding.call(this);

  /**
   * Parent file system.
   */
  this.fileSystem = fileSystem;

  /**
   * The path we're supposed to execute.
   */
  this.pathSpec = pathSpec;

  /**
   * The argument to pass to the executable.
   */
  this.arg = arg;

  // If the parent file system is closed, we close too.
  this.dependsOn(this.fileSystem);

  this.describeMethod('execute', {type: 'method', arg: []},
                      this.execute_.bind(this));

  /**
   * The ExecuteContext we're currently calling out to, if any.
   *
   * See ..setCallee().
   */
  this.callee = null;

  /**
   * Events sourced by this binding in addition to the inherited events from
   * BaseBinding.
   *
   * These are raised after the corresponding method is invoked.  For example,
   * signal(...) raises the onSignal event.
   */
  this.onSignal = new AxiomEvent();
  this.onStdOut = new AxiomEvent();
  this.onStdErr = new AxiomEvent();
  this.onStdIn = new AxiomEvent();
  this.onTTYChange = new AxiomEvent();
  this.onTTYRequest = new AxiomEvent();

  // An indication that the execute() method was called.
  this.didExecute_ = false;

  // The environtment variables for this execute context.
  this.env_ = {};

  // The tty state for this execute context.
  this.tty_ = {
    isatty: false,
    rows: 0,
    columns: 0,
    interrupt: String.fromCharCode('C'.charCodeAt(0) - 64)  // ^C
  };
};

export default ExecuteContext;

ExecuteContext.prototype = Object.create(BaseBinding.prototype);

ExecuteContext.prototype.execute_ = function() {
  if (this.didExecute_) {
    return Promise.reject(new AxiomError.Runtime(
        'ExecuteContext..execute called multiple times'));
  }

  this.didExecute_ = true;
  return Promise.resolve();
};

/**
 * Set the given ExecuteContext as the callee for this instance.
 *
 * When calling another executable, incoming calls and outbound events are
 * wired up to the caller as appropriate.  This instance will not receive
 * the stdio-like events while a call is in progress.  The onSignal event,
 * however, is delivered to this instance even when a call is in progress.
 *
 * If the callee is closed, events are rerouted back to this instance and the
 * callee instance property is set to null.
 */
ExecuteContext.prototype.setCallee = function(executeContext) {
  if (this.callee)
    throw new Error('Still waiting for call:', this.callee);

  this.callee = executeContext;
  var previousInterruptChar = this.tty_.interrupt;

  var onClose = function() {
    this.callee.onStdOut.removeListener(this.onStdOut.fire);
    this.callee.onStdOut.removeListener(this.onStdErr.fire);
    this.callee.onTTYRequest.removeListener(this.onTTYRequest.fire);
    this.callee = null;

    if (this.tty_.interrupt != previousInterruptChar)
      this.requestTTY({interrupt: previousInterruptChar});
  }.bind(this);

  this.callee.onClose.listenOnce(onClose);
  this.callee.onStdOut.addListener(this.onStdOut.fire);
  this.callee.onStdErr.addListener(this.onStdErr.fire);
  this.callee.onTTYRequest.addListener(this.onTTYRequest.fire);
  this.callee.setEnvs(this.env_);
  this.callee.setTTY(this.tty_);
};

/**
 * Utility method to construct a new ExecuteContext, set it as the callee, and
 * execute it with the given path and arg.
 */
ExecuteContext.prototype.call = function(pathSpec, arg) {
  this.setCallee(this.fileSystem.createContext('execute', pathSpec, arg));
  this.callee.execute();
  return this.callee;
};

/**
 * Return a copy of the internal tty state.
 */
ExecuteContext.prototype.getTTY = function() {
  var rv = {};
  for (var key in this.tty_) {
    rv[key] = this.tty_[key];
  }

  return rv;
};

/**
 * Set the authoritative state of the tty.
 *
 * This should only be invoked in the direction of tty->executable.  Calls in
 * the reverse direction will only affect this instance and those derived (via
 * setCallee) from it, and will be overwritten the next time the authoritative
 * state changes.
 *
 * Executables should use requestTTY to request changes to the authoritative
 * state.
 *
 * The tty state is an object with the following properties:
 *
 *   tty {
 *     isatty: boolean, True if stdio-like methods are attached to a visual
 *       terminal.
 *     rows: integer, The number of rows in the tty.
 *     columns: integer, The number of columns in the tty.
 *     interrupt: string, The key used to raise an
 *       'Interrupt' signal.
 *   }
 *
 * @param {Object} tty An object containing one or more of the properties
 *   described above.
 */
ExecuteContext.prototype.setTTY = function(tty) {
  this.assertReadyState('WAIT', 'READY');

  if ('isatty' in tty)
    this.tty_.isatty = !!tty.isatty;
  if ('rows' in tty)
    this.tty_.rows = tty.rows;
  if ('columns' in tty)
    this.tty_.columns = tty.columns;

  if (!this.tty_.rows || !this.tty_.columns) {
    this.tty_.rows = 0;
    this.tty_.columns = 0;
    this.tty_.isatty = false;
  } else {
    this.tty_.isatty = true;
  }

  if (tty.rows < 0 || tty.columns < 0)
    throw new Error('Invalid tty size.');

  if ('interrupt' in tty)
    this.tty_.interrupt = tty.interrupt;

  this.onTTYChange.fire(this.tty_);

  if (this.callee)
    this.callee.setTTY(tty);
};

/**
 * Request a change to the controlling tty.
 *
 * At the moment only the 'interrupt' property can be changed.
 *
 * @param {Object} tty An object containing a changeable property of the
 *   tty.
 */
ExecuteContext.prototype.requestTTY = function(tty) {
  this.assertReadyState('READY');

  if (typeof tty.interrupt == 'string')
    this.onTTYRequest.fire({interrupt: tty.interrupt});
};

/**
 * Get a copy of the current environment variables.
 */
ExecuteContext.prototype.getEnvs = function() {
  var rv = {};
  for (var key in this.env_) {
    rv[key] = this.env_[key];
  }

  return rv;
};

/**
 * Get the value of the given environment variable, or the provided
 * defaultValue if it is not set.
 *
 * @param {string} name
 * @param {*} defaultValue
 */
ExecuteContext.prototype.getEnv = function(name, defaultValue) {
  if (this.env_.hasOwnProperty(name))
    return this.env_[name];

  return defaultValue;
};

/**
 * Overwrite the current environment.
 *
 * @param {Object} env
 */
ExecuteContext.prototype.setEnvs = function(env) {
  this.assertReadyState('WAIT', 'READY');
  for (var key in env) {
    this.env_[key] = env[key];
  }
};

/**
 * Set the given environment variable.
 *
 * @param {string} name
 * @param {*} value
 */
ExecuteContext.prototype.setEnv = function(name, value) {
  this.assertReadyState('WAIT', 'READY');
  this.env_[name] = value;
};

/**
 * Create a new context using the fs.FileSystem for this execute context, bound
 * to the lifetime of this context.
 */
ExecuteContext.prototype.createContext = function(name, pathSpec, arg) {
  var cx = this.fileSystem.createContext(name, pathSpec, arg);
  cx.dependsOn(this);
  return cx;
};

/**
 * Attempt to execute the given path with the given argument.
 *
 * This can only be called once per ExecuteContext instance.
 *
 * This function attempts to execute a path.  If the execute succeeds, the
 * onReady event of this binding will fire and you're free to start
 * communicating with the target process.
 *
 * When you're finished, call closeOk, closeError, or closeErrorValue to clean
 * up the execution context.
 *
 * If the execute fails the context will be close with an 'error' reason.
 *
 * The onClose event of this binding will fire when the context is closed,
 * regardless of which side of the context initiated the close.
 */
ExecuteContext.prototype.execute = function() {
  this.assertReadyState('WAIT');

  if (this.didExecute_)
    throw new Error('Already executed on this context');

  this.onExecute.fire();
};

/**
 * Send a signal to the running executable.
 *
 * The only signal defined at this time has the name 'Interrupt' and a null
 * value.
 *
 * @param {name}
 * @param {value}
 */
ExecuteContext.prototype.signal = function(name, value) {
  this.assertReady();
  if (this.callee) {
    this.callee.closeErrorValue(new AxiomError.Interrupt());
  } else {
    this.onSignal.fire(name, value);
  }
};

/**
 * Send stdout from this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdOut handler if necessary.
 *
 * TODO(rginda): Add numeric argument onAck to support partial consumption.
 *
 * @param {*} value The value to send.
 * @param {function()} opt_onAck The optional function to invoke when the
 *   recipient acknowledges receipt.
 */
ExecuteContext.prototype.stdout = function(value, opt_onAck) {
  if (!this.isReadyState('READY')) {
    console.warn('Dropping stdout to closed execute context:', value);
    return;
  }

  this.onStdOut.fire(value, opt_onAck);
};

/**
 * Send stderr from this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdErr handler if necessary.
 *
 * TODO(rginda): Add numeric argument onAck to support partial consumption.
 *
 * @param {*} value The value to send.
 * @param {function()} opt_onAck The optional function to invoke when the
 *   recipient acknowledges receipt.
 */
ExecuteContext.prototype.stderr = function(value, opt_onAck) {
  if (!this.isReadyState('READY')) {
    console.warn('Dropping stderr to closed execute context:', value);
    return;
  }

  this.onStdErr.fire(value, opt_onAck);
};

/**
 * Send stdout to this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdIn handler if necessary.
 *
 * TODO(rginda): Add opt_onAck.
 *
 * @param {*} value The value to send.
 */
ExecuteContext.prototype.stdin = function(value) {
  this.assertReady();
  if (this.callee) {
    this.callee.stdin(value);
  } else {
    this.onStdIn.fire(value);
  }
};
<commit_msg>Add executePromise<commit_after>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';

import BaseBinding from 'axiom/bindings/base';
import FileSystem from 'axiom/bindings/fs/file_system';

/**
 * A binding that represents a running executable on FileSystem.
 *
 * You should only create an ExecuteContext by calling an instance of
 * FileSystem..createContext('execute', ...).
 *
 * @param {FileSystem} The parent file system.
 */
export var ExecuteContext = function(fileSystem, pathSpec, arg) {
  BaseBinding.call(this);

  /**
   * Parent file system.
   */
  this.fileSystem = fileSystem;

  /**
   * The path we're supposed to execute.
   */
  this.pathSpec = pathSpec;

  /**
   * The argument to pass to the executable.
   */
  this.arg = arg;

  // If the parent file system is closed, we close too.
  this.dependsOn(this.fileSystem);

  this.describeMethod('execute', {type: 'method', arg: []},
                      this.execute_.bind(this));

  /**
   * The ExecuteContext we're currently calling out to, if any.
   *
   * See ..setCallee().
   */
  this.callee = null;

  /**
   * Events sourced by this binding in addition to the inherited events from
   * BaseBinding.
   *
   * These are raised after the corresponding method is invoked.  For example,
   * signal(...) raises the onSignal event.
   */
  this.onSignal = new AxiomEvent();
  this.onStdOut = new AxiomEvent();
  this.onStdErr = new AxiomEvent();
  this.onStdIn = new AxiomEvent();
  this.onTTYChange = new AxiomEvent();
  this.onTTYRequest = new AxiomEvent();

  // An indication that the execute() method was called.
  this.didExecute_ = false;

  // The environtment variables for this execute context.
  this.env_ = {};

  // The tty state for this execute context.
  this.tty_ = {
    isatty: false,
    rows: 0,
    columns: 0,
    interrupt: String.fromCharCode('C'.charCodeAt(0) - 64)  // ^C
  };
};

export default ExecuteContext;

ExecuteContext.prototype = Object.create(BaseBinding.prototype);

ExecuteContext.prototype.executePromise = function() {
  var resolvePromise = null;
  var rejectPromise = null;
  var promise = new Promise(function(resolve, reject) {
      resolvePromise = resolve;
      rejectPromise = reject;
    });

  this.onClose.listenOnce(function(reason, value) {
    if (reason === 'ok') {
      resolvePromise(value);
    } else {
      rejectPromise(value);
    }
  });

  this.execute();

  return promise;
};

ExecuteContext.prototype.execute_ = function() {
  if (this.didExecute_) {
    return Promise.reject(new AxiomError.Runtime(
        'ExecuteContext..execute called multiple times'));
  }

  this.didExecute_ = true;
  return Promise.resolve();
};

/**
 * Set the given ExecuteContext as the callee for this instance.
 *
 * When calling another executable, incoming calls and outbound events are
 * wired up to the caller as appropriate.  This instance will not receive
 * the stdio-like events while a call is in progress.  The onSignal event,
 * however, is delivered to this instance even when a call is in progress.
 *
 * If the callee is closed, events are rerouted back to this instance and the
 * callee instance property is set to null.
 */
ExecuteContext.prototype.setCallee = function(executeContext) {
  if (this.callee)
    throw new Error('Still waiting for call:', this.callee);

  this.callee = executeContext;
  var previousInterruptChar = this.tty_.interrupt;

  var onClose = function() {
    this.callee.onStdOut.removeListener(this.onStdOut.fire);
    this.callee.onStdOut.removeListener(this.onStdErr.fire);
    this.callee.onTTYRequest.removeListener(this.onTTYRequest.fire);
    this.callee = null;

    if (this.tty_.interrupt != previousInterruptChar)
      this.requestTTY({interrupt: previousInterruptChar});
  }.bind(this);

  this.callee.onClose.listenOnce(onClose);
  this.callee.onStdOut.addListener(this.onStdOut.fire);
  this.callee.onStdErr.addListener(this.onStdErr.fire);
  this.callee.onTTYRequest.addListener(this.onTTYRequest.fire);
  this.callee.setEnvs(this.env_);
  this.callee.setTTY(this.tty_);
};

/**
 * Utility method to construct a new ExecuteContext, set it as the callee, and
 * execute it with the given path and arg.
 */
ExecuteContext.prototype.call = function(pathSpec, arg) {
  this.setCallee(this.fileSystem.createContext('execute', pathSpec, arg));
  this.callee.execute();
  return this.callee;
};

/**
 * Return a copy of the internal tty state.
 */
ExecuteContext.prototype.getTTY = function() {
  var rv = {};
  for (var key in this.tty_) {
    rv[key] = this.tty_[key];
  }

  return rv;
};

/**
 * Set the authoritative state of the tty.
 *
 * This should only be invoked in the direction of tty->executable.  Calls in
 * the reverse direction will only affect this instance and those derived (via
 * setCallee) from it, and will be overwritten the next time the authoritative
 * state changes.
 *
 * Executables should use requestTTY to request changes to the authoritative
 * state.
 *
 * The tty state is an object with the following properties:
 *
 *   tty {
 *     isatty: boolean, True if stdio-like methods are attached to a visual
 *       terminal.
 *     rows: integer, The number of rows in the tty.
 *     columns: integer, The number of columns in the tty.
 *     interrupt: string, The key used to raise an
 *       'Interrupt' signal.
 *   }
 *
 * @param {Object} tty An object containing one or more of the properties
 *   described above.
 */
ExecuteContext.prototype.setTTY = function(tty) {
  this.assertReadyState('WAIT', 'READY');

  if ('isatty' in tty)
    this.tty_.isatty = !!tty.isatty;
  if ('rows' in tty)
    this.tty_.rows = tty.rows;
  if ('columns' in tty)
    this.tty_.columns = tty.columns;

  if (!this.tty_.rows || !this.tty_.columns) {
    this.tty_.rows = 0;
    this.tty_.columns = 0;
    this.tty_.isatty = false;
  } else {
    this.tty_.isatty = true;
  }

  if (tty.rows < 0 || tty.columns < 0)
    throw new Error('Invalid tty size.');

  if ('interrupt' in tty)
    this.tty_.interrupt = tty.interrupt;

  this.onTTYChange.fire(this.tty_);

  if (this.callee)
    this.callee.setTTY(tty);
};

/**
 * Request a change to the controlling tty.
 *
 * At the moment only the 'interrupt' property can be changed.
 *
 * @param {Object} tty An object containing a changeable property of the
 *   tty.
 */
ExecuteContext.prototype.requestTTY = function(tty) {
  this.assertReadyState('READY');

  if (typeof tty.interrupt == 'string')
    this.onTTYRequest.fire({interrupt: tty.interrupt});
};

/**
 * Get a copy of the current environment variables.
 */
ExecuteContext.prototype.getEnvs = function() {
  var rv = {};
  for (var key in this.env_) {
    rv[key] = this.env_[key];
  }

  return rv;
};

/**
 * Get the value of the given environment variable, or the provided
 * defaultValue if it is not set.
 *
 * @param {string} name
 * @param {*} defaultValue
 */
ExecuteContext.prototype.getEnv = function(name, defaultValue) {
  if (this.env_.hasOwnProperty(name))
    return this.env_[name];

  return defaultValue;
};

/**
 * Overwrite the current environment.
 *
 * @param {Object} env
 */
ExecuteContext.prototype.setEnvs = function(env) {
  this.assertReadyState('WAIT', 'READY');
  for (var key in env) {
    this.env_[key] = env[key];
  }
};

/**
 * Set the given environment variable.
 *
 * @param {string} name
 * @param {*} value
 */
ExecuteContext.prototype.setEnv = function(name, value) {
  this.assertReadyState('WAIT', 'READY');
  this.env_[name] = value;
};

/**
 * Create a new context using the fs.FileSystem for this execute context, bound
 * to the lifetime of this context.
 */
ExecuteContext.prototype.createContext = function(name, pathSpec, arg) {
  var cx = this.fileSystem.createContext(name, pathSpec, arg);
  cx.dependsOn(this);
  return cx;
};

/**
 * Send a signal to the running executable.
 *
 * The only signal defined at this time has the name 'Interrupt' and a null
 * value.
 *
 * @param {name}
 * @param {value}
 */
ExecuteContext.prototype.signal = function(name, value) {
  this.assertReady();
  if (this.callee) {
    this.callee.closeErrorValue(new AxiomError.Interrupt());
  } else {
    this.onSignal.fire(name, value);
  }
};

/**
 * Send stdout from this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdOut handler if necessary.
 *
 * TODO(rginda): Add numeric argument onAck to support partial consumption.
 *
 * @param {*} value The value to send.
 * @param {function()} opt_onAck The optional function to invoke when the
 *   recipient acknowledges receipt.
 */
ExecuteContext.prototype.stdout = function(value, opt_onAck) {
  if (!this.isReadyState('READY')) {
    console.warn('Dropping stdout to closed execute context:', value);
    return;
  }

  this.onStdOut.fire(value, opt_onAck);
};

/**
 * Send stderr from this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdErr handler if necessary.
 *
 * TODO(rginda): Add numeric argument onAck to support partial consumption.
 *
 * @param {*} value The value to send.
 * @param {function()} opt_onAck The optional function to invoke when the
 *   recipient acknowledges receipt.
 */
ExecuteContext.prototype.stderr = function(value, opt_onAck) {
  if (!this.isReadyState('READY')) {
    console.warn('Dropping stderr to closed execute context:', value);
    return;
  }

  this.onStdErr.fire(value, opt_onAck);
};

/**
 * Send stdout to this executable.
 *
 * This is not restricted to string values.  Recipients should filter out
 * non-string values in their onStdIn handler if necessary.
 *
 * TODO(rginda): Add opt_onAck.
 *
 * @param {*} value The value to send.
 */
ExecuteContext.prototype.stdin = function(value) {
  this.assertReady();
  if (this.callee) {
    this.callee.stdin(value);
  } else {
    this.onStdIn.fire(value);
  }
};
<|endoftext|>


<commit_before>'use strict';

var Args = require('./../../helpers/args');
var NodeStore = require('./../../node-store');
var Targets = require('./../../helpers/targets');
var VirtualDOM = require('./../../virtual-dom');

var TIME_KEY = '$time';
var NOW_KEY = '$now';
var FRAME_KEY = '$frame';

var FRAMES = {};

function create(behavior, node) {
    var states = node.statesObject;
    FRAMES[node.uid] = 0;
    return function(time) {
        var now = Date.now();
        var frame = FRAMES[node.uid]++;

        var i;
        var args = [];
        var params = behavior.params || [];
        for (i = 0; i < params.length; i++) {
            var name = params[i];
            if (name === TIME_KEY) {
                args[i] = time;
            }
            else if (name === FRAME_KEY) {
                args[i] = frame;
            }
            else if (name === NOW_KEY) {
                args[i] = now;
            }
            else {
                args[i] = states[name];
            }
        }
        var payload = behavior.action.apply(null, args);
        var targets = Targets.fetch(node.domNode, behavior.selector);
        for (i = 0; i < targets.length; i++) {
            var target = targets[i];
            var targetNode = NodeStore.findNode(VirtualDOM.getUID(target));
            targetNode.eventManager.sendMessage(behavior.name, payload);
        }
    };
}

module.exports = {
    create: create
};
<commit_msg>Fix linting<commit_after>'use strict';

var NodeStore = require('./../../node-store');
var Targets = require('./../../helpers/targets');
var VirtualDOM = require('./../../virtual-dom');

var TIME_KEY = '$time';
var NOW_KEY = '$now';
var FRAME_KEY = '$frame';

var FRAMES = {};

function create(behavior, node) {
    var states = node.statesObject;
    FRAMES[node.uid] = 0;
    return function(time) {
        var now = Date.now();
        var frame = FRAMES[node.uid]++;

        var i;
        var args = [];
        var params = behavior.params || [];
        for (i = 0; i < params.length; i++) {
            var name = params[i];
            if (name === TIME_KEY) {
                args[i] = time;
            }
            else if (name === FRAME_KEY) {
                args[i] = frame;
            }
            else if (name === NOW_KEY) {
                args[i] = now;
            }
            else {
                args[i] = states[name];
            }
        }
        var payload = behavior.action.apply(null, args);
        var targets = Targets.fetch(node.domNode, behavior.selector);
        for (i = 0; i < targets.length; i++) {
            var target = targets[i];
            var targetNode = NodeStore.findNode(VirtualDOM.getUID(target));
            targetNode.eventManager.sendMessage(behavior.name, payload);
        }
    };
}

module.exports = {
    create: create
};
<|endoftext|>


<commit_before>var util = require('../../util');
var assert = require('assert');

function CheckBundle (data){
    data = data || {};
    this._checks = data._checks;
    this._cid = data._cid;
    this._created = data._created;
    this._last_modified = data._last_modified;
    this._last_modified_by = data._last_modified_by;
    this.brokers = data.brokers || [];
    this.config = data.config || {};
    this.display_name = data.display_name;
    this.metrics = data.metrics || [];
    this.notes = data.notes;
    this.period = data.period;
    this.status = data.status;
    this.tags = data.tags || [];
    this.target = data.target;
    this.timeout = data.timeout;
    this.type = data.type;
}

CheckBundle.prototype.updateTags = function(tags){
    var newTags = updateArray('tag',this.tags, tags);
    if(newTags) this.tags = newTags;
    return this.tags;
};

CheckBundle.prototype.updateMetrics = function(metrics){
    var newMetrics = updateArray('metric',this.metrics,metrics);
    var uniqueMetrics = [];
    if(newMetrics){
        var metricNames = {};
        for(var i = newMetrics.length - 1; i >= 0; i--){
            var metric = newMetrics[i];
            if(metricNames[metric.name]) continue;
            metricNames[metric.name] = true;
            uniqueMetrics.push(metric);
        }
    }
    return this.metrics = uniqueMetrics.reverse();
};

CheckBundle.prototype.merge = function(checkBundle){
    var origCheck = JSON.stringify(this);

    // Tags and metrics update separately due to the regex removals
    this.updateTags(checkBundle.tags);
    this.updateMetrics(checkBundle.metrics);
    checkBundle.tags = [];
    checkBundle.metrics = [];

    util.mergeDeep(this, checkBundle);

    var newCheck = JSON.stringify(this);

    if(origCheck !== newCheck) return true;

    return false;
};

var removalRegExp = /^!\/.+\/(i)?/;

CheckBundle.prototype.export = function(){
    var data = JSON.parse(JSON.stringify(this));
    data.tags = removeRegExpFromArray(data.tags);
    data.metrics = removeRegExpFromArray(data.metrics);
    console.log(data);
    return data;
}

function removeRegExpFromArray(arr){
    return arr.filter(function(element){
        return !removalRegExp.test(element);
    });
}

function updateArray(type, orig, updates){
    if(!(orig instanceof Array) || !(updates instanceof Array)) return;

    var add = [];
    // Process removals first, then union in the rest
    for(var i in updates){
        var value = updates[i];
        // Removals are regex prefixed with !
        if(removalRegExp.test(value)){
            var tmp = value.split('/');
            tmp.shift(); // Get rid of !
            var flag = tmp.pop(); // Pull off i flag if present
            var regexp = new RegExp(tmp.join('/'),flag);
            orig = orig.filter(function(element){
                var testElement = (type === 'metric') ? element.name : element;
                return !regexp.test(testElement);
            });
        } else {
            add.push(value);
        }
    }

    return util.unionArray(orig, add);
}

module.exports = CheckBundle;
<commit_msg>Remove extra logging<commit_after>var util = require('../../util');
var assert = require('assert');

function CheckBundle (data){
    data = data || {};
    this._checks = data._checks;
    this._cid = data._cid;
    this._created = data._created;
    this._last_modified = data._last_modified;
    this._last_modified_by = data._last_modified_by;
    this.brokers = data.brokers || [];
    this.config = data.config || {};
    this.display_name = data.display_name;
    this.metrics = data.metrics || [];
    this.notes = data.notes;
    this.period = data.period;
    this.status = data.status;
    this.tags = data.tags || [];
    this.target = data.target;
    this.timeout = data.timeout;
    this.type = data.type;
}

CheckBundle.prototype.updateTags = function(tags){
    var newTags = updateArray('tag',this.tags, tags);
    if(newTags) this.tags = newTags;
    return this.tags;
};

CheckBundle.prototype.updateMetrics = function(metrics){
    var newMetrics = updateArray('metric',this.metrics,metrics);
    var uniqueMetrics = [];
    if(newMetrics){
        var metricNames = {};
        for(var i = newMetrics.length - 1; i >= 0; i--){
            var metric = newMetrics[i];
            if(metricNames[metric.name]) continue;
            metricNames[metric.name] = true;
            uniqueMetrics.push(metric);
        }
    }
    return this.metrics = uniqueMetrics.reverse();
};

CheckBundle.prototype.merge = function(checkBundle){
    var origCheck = JSON.stringify(this);

    // Tags and metrics update separately due to the regex removals
    this.updateTags(checkBundle.tags);
    this.updateMetrics(checkBundle.metrics);
    checkBundle.tags = [];
    checkBundle.metrics = [];

    util.mergeDeep(this, checkBundle);

    var newCheck = JSON.stringify(this);

    if(origCheck !== newCheck) return true;

    return false;
};

var removalRegExp = /^!\/.+\/(i)?/;

CheckBundle.prototype.export = function(){
    var data = JSON.parse(JSON.stringify(this));
    data.tags = removeRegExpFromArray(data.tags);
    data.metrics = removeRegExpFromArray(data.metrics);
    return data;
}

function removeRegExpFromArray(arr){
    return arr.filter(function(element){
        return !removalRegExp.test(element);
    });
}

function updateArray(type, orig, updates){
    if(!(orig instanceof Array) || !(updates instanceof Array)) return;

    var add = [];
    // Process removals first, then union in the rest
    for(var i in updates){
        var value = updates[i];
        // Removals are regex prefixed with !
        if(removalRegExp.test(value)){
            var tmp = value.split('/');
            tmp.shift(); // Get rid of !
            var flag = tmp.pop(); // Pull off i flag if present
            var regexp = new RegExp(tmp.join('/'),flag);
            orig = orig.filter(function(element){
                var testElement = (type === 'metric') ? element.name : element;
                return !regexp.test(testElement);
            });
        } else {
            add.push(value);
        }
    }

    return util.unionArray(orig, add);
}

module.exports = CheckBundle;
<|endoftext|>


<commit_before>var Utils = require("../../utils")
  , util  = require("util")

module.exports = (function() {
  var QueryGenerator = {
    createTableQuery: function(tableName, attributes, options) {
      options = options || {}

      var query       = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)"
        , primaryKeys = []
        , attrStr     = Utils._.map(attributes, function(dataType, attr) {
            if (Utils._.includes(dataType, 'PRIMARY KEY')) {
              primaryKeys.push(attr)
              return Utils.addTicks(attr) + " " + dataType
            } else {
              return Utils.addTicks(attr) + " " + dataType
            }
          }).join(", ")
        , values = {
            table: Utils.addTicks(tableName),
            attributes: attrStr,
            charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "")
          }

      return Utils._.template(query)(values).trim() + ";"
    },

    dropTableQuery: function(tableName, options) {
      options = options || {}

      var query = "DROP TABLE IF EXISTS <%= table %>;"

      return Utils._.template(query)({table: Utils.addTicks(tableName)})
    },

    showTablesQuery: function() {
      return "SELECT name FROM sqlite_master WHERE type='table';"
    },

    selectQuery: function(tableName, options) {
      options = options || {}
      options.table = Utils.addTicks(tableName)
      options.attributes = options.attributes && options.attributes.map(function(attr){
        if(Array.isArray(attr) && attr.length == 2)
          return [attr[0], Utils.addTicks(attr[1])].join(' as ')
        else
          return Utils.addTicks(attr)
      }).join(", ")
      options.attributes = options.attributes || '*'

      var query = "SELECT <%= attributes %> FROM <%= table %>"

      if(options.where) {
        options.where = QueryGenerator.getWhereConditions(options.where)
        query += " WHERE <%= where %>"
      }
      if(options.order) query += " ORDER BY <%= order %>"
      if(options.group) {
        options.group = Utils.addTicks(options.group)
        query += " GROUP BY <%= group %>"
      }
      if(options.limit) {
        if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
        else query += " LIMIT <%= limit %>"
      }

      query += ";"

      return Utils._.template(query)(options)
    },

    insertQuery: function(tableName, attrValueHash) {
      var query = "INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>);"

      var replacements  = {
        table: Utils.addTicks(tableName),
        attributes: Utils._.keys(attrValueHash).map(function(attr){return Utils.addTicks(attr)}).join(","),
        values: Utils._.values(attrValueHash).map(function(value){
          return Utils.escape((value instanceof Date) ? Utils.toSqlDate(value) : value)
        }).join(",")
      }

      return Utils._.template(query)(replacements)
    },

    attributesToSQL: function(attributes) {
      var result = {}

      Utils._.map(attributes, function(dataType, name) {
        if(Utils.isHash(dataType)) {
          var template     = "<%= type %>"
            , replacements = { type: dataType.type }

          if(dataType.hasOwnProperty('allowNull') && !dataType.allowNull && !dataType.primaryKey)
            template += " NOT NULL"

          if(dataType.defaultValue != undefined) {
            template += " DEFAULT <%= defaultValue %>"
            replacements.defaultValue = Utils.escape(dataType.defaultValue)
          }

          if(dataType.unique) template += " UNIQUE"
          if(dataType.primaryKey) template += " PRIMARY KEY"

          result[name] = Utils._.template(template)(replacements)
        } else {
          result[name] = dataType
        }
      })

      return result
    }
  }

  return Utils._.extend(Utils._.clone(require("../query-generator")), QueryGenerator)
})()
<commit_msg>sqlite extends mysql now<commit_after>var Utils = require("../../utils")
  , util  = require("util")

module.exports = (function() {
  var QueryGenerator = {
    createTableQuery: function(tableName, attributes, options) {
      options = options || {}

      var query       = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)"
        , primaryKeys = []
        , attrStr     = Utils._.map(attributes, function(dataType, attr) {
            if (Utils._.includes(dataType, 'PRIMARY KEY')) {
              primaryKeys.push(attr)
              return Utils.addTicks(attr) + " " + dataType
            } else {
              return Utils.addTicks(attr) + " " + dataType
            }
          }).join(", ")
        , values = {
            table: Utils.addTicks(tableName),
            attributes: attrStr,
            charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "")
          }

      return Utils._.template(query)(values).trim() + ";"
    },

    showTablesQuery: function() {
      return "SELECT name FROM sqlite_master WHERE type='table';"
    },

    attributesToSQL: function(attributes) {
      var result = {}

      Utils._.map(attributes, function(dataType, name) {
        if(Utils.isHash(dataType)) {
          var template     = "<%= type %>"
            , replacements = { type: dataType.type }

          if(dataType.hasOwnProperty('allowNull') && !dataType.allowNull && !dataType.primaryKey)
            template += " NOT NULL"

          if(dataType.defaultValue != undefined) {
            template += " DEFAULT <%= defaultValue %>"
            replacements.defaultValue = Utils.escape(dataType.defaultValue)
          }

          if(dataType.unique) template += " UNIQUE"
          if(dataType.primaryKey) template += " PRIMARY KEY"

          result[name] = Utils._.template(template)(replacements)
        } else {
          result[name] = dataType
        }
      })

      return result
    }
  }

  var MySqlQueryGenerator = Utils._.extend(
    Utils._.clone(require("../query-generator")),
    Utils._.clone(require("../mysql/query-generator"))
  )

  return Utils._.extend(MySqlQueryGenerator, QueryGenerator)
})()
<|endoftext|>