<commit_before>define(["dojo/has", "xstyle/put", "dojo/_base/declare", "dojo/on", "./Editor", "./List", "dojo/_base/sniff"], function(has, put, declare, listen, Editor, List){
	var contentBoxSizing = has("ie") < 8 && !has("quirks");

	return declare([List], {
		columns: null,
		// summary:
		//		This indicates that focus is at the cell level. This may be set to false to cause
		//		focus to be at the row level, which is useful if you want only want row-level
		//		navigation.
		cellNavigation: true,
		column: function(target){
			// summary:
			//		Get the column object by node, or event, or a columnId
			if(typeof target == "string"){
				return this.columns[target];
			}else{
				return this.cell(target).column;
			}
		},
		cell: function(target, columnId){
			// summary:
			//		Get the cell object by node, or event, id, plus a columnId
			if(target.target && target.target.nodeType){
				// event
				target = target.target;
			}
			var element;
			if(target.nodeType){
				var object;
				do{
					if(this._rowIdToObject[target.id]){
						break;
					}
					var colId = target.columnId;
					if(colId){
						columnId = colId;
						element = target;
						break;
					}
					target = target.parentNode;
				}while(target && target != this.domNode);
			}
			if(!element && columnId){
				var row = this.row(target),
					rowElement = row.element;
				if(rowElement){
					var elements = rowElement.getElementsByTagName("td");
					for(var i = 0; i < elements.length; i++){
						if(elements[i].columnId == columnId){
							element = elements[i];
							break;
						}
					}
				}
			}
			if(target != null){
				return {
					row: row || this.row(target),
					column: columnId && this.column(columnId),
					element: element
				};
			}
		},
		_columnsCss: function(rule){
			// This is an attempt at integration with xstyle, will probably change
			rule.fullSelector = function(){
				return this.parent.fullSelector() + " .dgrid-cell";
			};
			for(var i = 0;i < rule.children.length;i++){
				var child = rule.children[i];
				child.field = child.className = child.selector.substring(1);
			}
			return rule.children;
		},
		createRowCells: function(tag, each){
			// summary:
			//		Generates the grid for each row (used by renderHeader and and renderRow)
			var tr, row = put("table.dgrid-row-table[role=presentation]"),
				cellNavigation = this.cellNavigation;
			if(has("ie") < 9 || has("quirks")){
				// this is the only browser that needs a tbody
				var tbody = put(row, "tbody");
			}else{
				var tbody = row;
			}
			var subRows = this.subRows;
			for(var si = 0, sl = subRows.length; si < sl; si++){
				var subRow = subRows[si];
				if(sl == 1 && !has("ie")){
					// shortcut for modern browsers
					tr = tbody;
				}else{
					tr = put(tbody, "tr");
				}
				for(var i = 0, l = subRow.length; i < l; i++){
					// iterate through the columns
					var column = subRow[i];
					var id = column.id;
					var extraClassName = column.className || (column.field && "field-" + column.field);
					var cell = put(tag + ".dgrid-cell.dgrid-cell-padding.column-" + id + (extraClassName ? '.' + extraClassName : ''));
					cell.columnId = id;
					if(contentBoxSizing){
						// The browser (IE7-) does not support box-sizing: border-box, so we emulate it with a padding div
						var innerCell = put(cell, "!dgrid-cell-padding div.dgrid-cell-padding");// remove the dgrid-cell-padding, and create a child with that class
						cell.contents = innerCell;
					}else{
						innerCell = cell;
					}
					var colSpan = column.colSpan;
					if(colSpan){
						cell.colSpan = colSpan;
					}
					var rowSpan = column.rowSpan;
					if(rowSpan){
						cell.rowSpan = rowSpan;
					}
					each(innerCell, column);
					// add the td to the tr at the end for better performance
					tr.appendChild(cell);
				}
			}
			return row;
		},
		left: function(cell, steps){
			return this.cell(this._move(cell, -(steps || 1), "dgrid-cell"));
		},
		right: function(cell, steps){
			return this.cell(this._move(cell, steps || 1, "dgrid-cell"));
		},
		renderRow: function(object, options){
			var row = this.createRowCells("td", function(td, column){
				var data = object;
				// we support the field, get, and formatter properties like the DataGrid
				var renderCell = column.renderCell;
				if(column.get){
					data = column.get(data);
				}else if("field" in column){
					data = data[column.field];
				}
				if(column.formatter){
					data = column.formatter(data);
					td.innerHTML = data;
				}
				if(!column.formatter || renderCell){
					if(column.renderCell){
					// A column can provide a renderCell method to do its own DOM manipulation,
					// event handling, etc.
						data = column.renderCell(object, data, td, options);
					}
					if(data != null){
						td.appendChild(document.createTextNode(data));
					}
				}
			});
			// row gets a wrapper div for a couple reasons:
			//	1. So that one can set a fixed height on rows (heights can't be set on
's AFAICT)
			// 2. So that outline style can be set on a row when it is focused, and Safari's outline style is broken on

			return put("div[role=gridcell]>", row);
		},
		renderHeader: function(headerNode){
			// summary:
			//		Setup the headers for the grid
			var grid = this;
			var columns = this.columns;
			var row = this.createRowCells("th[role=columnheader]", function(th, column){
				column.grid = grid;
				var field = column.field;
				if(field){
					th.field = field;
				}
				// allow for custom header manipulation
				if(column.renderHeaderCell){
					column.renderHeaderCell(th);
				}else if(column.name || column.field){
					th.appendChild(document.createTextNode(column.name || column.field));
				}
				if(column.sortable !== false){
					th.sortable = true;
				}
			});

			//put(headerNode, "div.dgrid-header-columns>", row, ".dgrid-row<+div.dgrid-header-scroll.ui-widget-header");
			//row = put("div.dgrid-row[role=columnheader]>", row);
			headerNode.appendChild(row);
			var lastSortedArrow;
			// if it columns are sortable, resort on clicks
			listen(row, "click", function(event){
				var
					target = event.target,
					field, descending, parentNode;
				do{
					if(target.sortable){
						field = target.field || target.columnId;
						// re-sort
						descending = grid.sortOrder && grid.sortOrder[0].attribute == field && !grid.sortOrder[0].descending;
						if(lastSortedArrow){
							put(lastSortedArrow, "<!dgrid-sort-up!dgrid-sort-down"); // remove the sort classes from parent node
							put(lastSortedArrow, "!"); // destroy the lastSortedArrow node
						}
						lastSortedArrow = put(target.firstChild, "-div.dgrid-sort-arrow.ui-icon[role=presentation]");
						lastSortedArrow.innerHTML = " ";
						put(target, descending ? ".dgrid-sort-down" : ".dgrid-sort-up");
						grid.resize();
						grid.sort(field, descending);
					}
				}while((target = target.parentNode) && target != headerNode);
			});
		},
		styleColumn: function(colId, css){
			// summary:
			//		Changes the column width by creating a dynamic stylesheet

			// now add a rule to style the column
			var styleSheets = document.styleSheets;
			var styleSheet = styleSheets[styleSheets.length - 1];
			var index = (styleSheet.cssRules || styleSheet.rules).length;
			styleSheet.addRule("#" + this.domNode.id + ' .column-' + colId, css);
			return {
				remove: function(){
					styleSheet.deleteRule(index);
				}
			}
		},
		_configColumns: function(prefix, rowColumns){
			// configure the current column
			var subRow = [];
			var isArray = rowColumns instanceof Array;
			for(var columnId in rowColumns){
				var column = rowColumns[columnId];
				if(typeof column == "string"){
					rowColumns[columnId] = column = {name:column};
				}
				if(!isArray && !column.field){
					column.field = columnId;
				}
				columnId = column.id = column.id || (isNaN(columnId) ? columnId : (prefix + columnId));
				if(prefix){
					this.columns[columnId] = column;
				}
				subRow.push(column); // make sure it can be iterated on
			}
			return isArray ? rowColumns : subRow;
		},
		configStructure: function(){
			// configure the columns and subRows
			var subRows = this.subRows;
			if(subRows){
				// we have subRows, but no columns yet, need to create the columns
				this.columns = {};
				for(var i = 0; i < subRows.length; i++){
					subRows[i] = this._configColumns(i + '-', subRows[i]);
				}
			}else{
				this.subRows = [this._configColumns("", this.columns)];
			}
		}
	});
});
<commit_msg>Fix rule addition to work cross-browser<commit_after>define(["dojo/has", "xstyle/put", "dojo/_base/declare", "dojo/on", "./Editor", "./List", "dojo/_base/sniff"], function(has, put, declare, listen, Editor, List){
	var contentBoxSizing = has("ie") < 8 && !has("quirks");

	return declare([List], {
		columns: null,
		// summary:
		//		This indicates that focus is at the cell level. This may be set to false to cause
		//		focus to be at the row level, which is useful if you want only want row-level
		//		navigation.
		cellNavigation: true,
		column: function(target){
			// summary:
			//		Get the column object by node, or event, or a columnId
			if(typeof target == "string"){
				return this.columns[target];
			}else{
				return this.cell(target).column;
			}
		},
		cell: function(target, columnId){
			// summary:
			//		Get the cell object by node, or event, id, plus a columnId
			if(target.target && target.target.nodeType){
				// event
				target = target.target;
			}
			var element;
			if(target.nodeType){
				var object;
				do{
					if(this._rowIdToObject[target.id]){
						break;
					}
					var colId = target.columnId;
					if(colId){
						columnId = colId;
						element = target;
						break;
					}
					target = target.parentNode;
				}while(target && target != this.domNode);
			}
			if(!element && columnId){
				var row = this.row(target),
					rowElement = row.element;
				if(rowElement){
					var elements = rowElement.getElementsByTagName("td");
					for(var i = 0; i < elements.length; i++){
						if(elements[i].columnId == columnId){
							element = elements[i];
							break;
						}
					}
				}
			}
			if(target != null){
				return {
					row: row || this.row(target),
					column: columnId && this.column(columnId),
					element: element
				};
			}
		},
		_columnsCss: function(rule){
			// This is an attempt at integration with xstyle, will probably change
			rule.fullSelector = function(){
				return this.parent.fullSelector() + " .dgrid-cell";
			};
			for(var i = 0;i < rule.children.length;i++){
				var child = rule.children[i];
				child.field = child.className = child.selector.substring(1);
			}
			return rule.children;
		},
		createRowCells: function(tag, each){
			// summary:
			//		Generates the grid for each row (used by renderHeader and and renderRow)
			var tr, row = put("table.dgrid-row-table[role=presentation]"),
				cellNavigation = this.cellNavigation;
			if(has("ie") < 9 || has("quirks")){
				// this is the only browser that needs a tbody
				var tbody = put(row, "tbody");
			}else{
				var tbody = row;
			}
			var subRows = this.subRows;
			for(var si = 0, sl = subRows.length; si < sl; si++){
				var subRow = subRows[si];
				if(sl == 1 && !has("ie")){
					// shortcut for modern browsers
					tr = tbody;
				}else{
					tr = put(tbody, "tr");
				}
				for(var i = 0, l = subRow.length; i < l; i++){
					// iterate through the columns
					var column = subRow[i];
					var id = column.id;
					var extraClassName = column.className || (column.field && "field-" + column.field);
					var cell = put(tag + ".dgrid-cell.dgrid-cell-padding.column-" + id + (extraClassName ? '.' + extraClassName : ''));
					cell.columnId = id;
					if(contentBoxSizing){
						// The browser (IE7-) does not support box-sizing: border-box, so we emulate it with a padding div
						var innerCell = put(cell, "!dgrid-cell-padding div.dgrid-cell-padding");// remove the dgrid-cell-padding, and create a child with that class
						cell.contents = innerCell;
					}else{
						innerCell = cell;
					}
					var colSpan = column.colSpan;
					if(colSpan){
						cell.colSpan = colSpan;
					}
					var rowSpan = column.rowSpan;
					if(rowSpan){
						cell.rowSpan = rowSpan;
					}
					each(innerCell, column);
					// add the td to the tr at the end for better performance
					tr.appendChild(cell);
				}
			}
			return row;
		},
		left: function(cell, steps){
			return this.cell(this._move(cell, -(steps || 1), "dgrid-cell"));
		},
		right: function(cell, steps){
			return this.cell(this._move(cell, steps || 1, "dgrid-cell"));
		},
		renderRow: function(object, options){
			var row = this.createRowCells("td", function(td, column){
				var data = object;
				// we support the field, get, and formatter properties like the DataGrid
				var renderCell = column.renderCell;
				if(column.get){
					data = column.get(data);
				}else if("field" in column){
					data = data[column.field];
				}
				if(column.formatter){
					data = column.formatter(data);
					td.innerHTML = data;
				}
				if(!column.formatter || renderCell){
					if(column.renderCell){
					// A column can provide a renderCell method to do its own DOM manipulation,
					// event handling, etc.
						data = column.renderCell(object, data, td, options);
					}
					if(data != null){
						td.appendChild(document.createTextNode(data));
					}
				}
			});
			// row gets a wrapper div for a couple reasons:
			//	1. So that one can set a fixed height on rows (heights can't be set on
's AFAICT)
			// 2. So that outline style can be set on a row when it is focused, and Safari's outline style is broken on

			return put("div[role=gridcell]>", row);
		},
		renderHeader: function(headerNode){
			// summary:
			//		Setup the headers for the grid
			var grid = this;
			var columns = this.columns;
			var row = this.createRowCells("th[role=columnheader]", function(th, column){
				column.grid = grid;
				var field = column.field;
				if(field){
					th.field = field;
				}
				// allow for custom header manipulation
				if(column.renderHeaderCell){
					column.renderHeaderCell(th);
				}else if(column.name || column.field){
					th.appendChild(document.createTextNode(column.name || column.field));
				}
				if(column.sortable !== false){
					th.sortable = true;
				}
			});

			//put(headerNode, "div.dgrid-header-columns>", row, ".dgrid-row<+div.dgrid-header-scroll.ui-widget-header");
			//row = put("div.dgrid-row[role=columnheader]>", row);
			headerNode.appendChild(row);
			var lastSortedArrow;
			// if it columns are sortable, resort on clicks
			listen(row, "click", function(event){
				var
					target = event.target,
					field, descending, parentNode;
				do{
					if(target.sortable){
						field = target.field || target.columnId;
						// re-sort
						descending = grid.sortOrder && grid.sortOrder[0].attribute == field && !grid.sortOrder[0].descending;
						if(lastSortedArrow){
							put(lastSortedArrow, "<!dgrid-sort-up!dgrid-sort-down"); // remove the sort classes from parent node
							put(lastSortedArrow, "!"); // destroy the lastSortedArrow node
						}
						lastSortedArrow = put(target.firstChild, "-div.dgrid-sort-arrow.ui-icon[role=presentation]");
						lastSortedArrow.innerHTML = " ";
						put(target, descending ? ".dgrid-sort-down" : ".dgrid-sort-up");
						grid.resize();
						grid.sort(field, descending);
					}
				}while((target = target.parentNode) && target != headerNode);
			});
		},
		styleColumn: function(colId, css){
			// summary:
			//		Changes the column width by creating a dynamic stylesheet

			// now add a rule to style the column
			var styleSheets = document.styleSheets;
			var styleSheet = styleSheets[styleSheets.length - 1];
			var index = (styleSheet.cssRules || styleSheet.rules).length;
			var columnSelector = "#" + this.domNode.id + ' .column-' + colId;
			styleSheet.addRule ?
				styleSheet.addRule(columnSelector, css) :
				styleSheet.insertRule(columnSelector + '{' + css + '}', styleSheet.cssRules.length);
			return {
				remove: function(){
					styleSheet.deleteRule(index);
				}
			}
		},
		_configColumns: function(prefix, rowColumns){
			// configure the current column
			var subRow = [];
			var isArray = rowColumns instanceof Array;
			for(var columnId in rowColumns){
				var column = rowColumns[columnId];
				if(typeof column == "string"){
					rowColumns[columnId] = column = {name:column};
				}
				if(!isArray && !column.field){
					column.field = columnId;
				}
				columnId = column.id = column.id || (isNaN(columnId) ? columnId : (prefix + columnId));
				if(prefix){
					this.columns[columnId] = column;
				}
				subRow.push(column); // make sure it can be iterated on
			}
			return isArray ? rowColumns : subRow;
		},
		configStructure: function(){
			// configure the columns and subRows
			var subRows = this.subRows;
			if(subRows){
				// we have subRows, but no columns yet, need to create the columns
				this.columns = {};
				for(var i = 0; i < subRows.length; i++){
					subRows[i] = this._configColumns(i + '-', subRows[i]);
				}
			}else{
				this.subRows = [this._configColumns("", this.columns)];
			}
		}
	});
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');

var Users = require('../models/Users');
var Groups = require('../models/Groups');
var Messages = require('../models/Messages');

var contextML = require('../modules/contextML');
var Auth = require('../config/auth');

router.get('/', function (req, res) {
	res.send('You Made It!');
});

router.use(function (req, res, next) {
	if(req.query.token && req.query.fbid) {
		var FB_URL = "https://graph.facebook.com/me?";
		request.get(FB_URL + 'access_token=' + req.query.token, function (error, response, body) {
			if(error) {
				res.send({ status : 500, err : err});
			}
			var responseData = JSON.parse(body);
			if(responseData.id != req.query.fbid) {
				res.send({ status : 400, err : "Not Authorized"});
			}
			Users.count({ 'facebook.id' : responseData.id }, function(err, count) {
				if(error) {
					res.send({ status : 500, err : err}); return;
				}
				console.log(count);
				if(count == 1) {
					next();
					return;
				} else {
					var user = new Users();
						user.fname = responseData.first_name;
						user.lname = responseData.last_name;
						user.facebook.id = responseData.id;

					user.save(function (err) {
						if(err) {
							res.send({ status : 500, err : err}); return;
						}
						next();
						return;
					});
				}
			});
		});
	} else {
		res.send({ status : 400, err : "No Access Token or User ID Passed"});
	}
});
// ===========
// User Routes
// ===========
router.route('/users')
	.get(function (req, res) {
		Users.find({}, 'fname lname email', function(err, users) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : users });
		});
	});

router.route('/user/:user_id')
	.get(function(req, res) {
		Users.findById(req.params.user_id, 'fname lname email', function(err, user) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : user });
		});
	});

// ===========
// ME ENDPOINT
// ===========

router.route('/me')
	.get(function(req, res) {
		Users.findById(req.body.user_id)
			.exec(function(err, me){
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : me });
			});
	});

// ============
// Group Routes
// ============

router.route('/groups/create')
	.post(function(req, res) {
		var group = new Group();
			group.name = req.body.name;
			group.users = [];
			group.users.push(req.body.user_id);
			group.loc = req.body.loc;

		group.save(function(err) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : group, msg : "New Group Created" });
		})
	});

router.route('/group/:group_id')
	.get(function(req, res) {
		Groups.findById(req.params.group_id)
			.populate('users', '_id fname lname email')
			.exec(function(err, group) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : group });
			});
	});

router.route('/group/:group_id/add')
	.put(function(req, res) {
		Groups.findById(req.params.group_id)
			.populate('users', '_id fname lname email')
			.exec(function(err, group) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				group.users.push(req.body.user_id);
				group.save(function(err) {
					if(err) {
						res.send({ status : 500, err : err });
					}
					res.json({ status : 200, response : group, msg : "New User Added" });
				})
			});
	});

// ===============
// Messages Routes
// ===============

router.route('/messages/:group_id/create')
	.post(function(req, res) {
		Users.find({'facebook.id' : req.query.fbid}, function(err, user){
			if(err) {
				res.send({ status : 500, err : err});
			}
			console.log(user);
			console.log(req.query);
			var newMsg = new Messages();
				newMsg.msg = req.query.msg;
				newMsg.priority = req.query.priority || 2;
				newMsg.groupID = req.params.group_id;
				newMsg.fromUserID = user._id;
				newMsg.tags = req.query.tags;
				newMsg.locs = req.query.locs;
				newMsg.dateCreated = Date.now();
				newMsg.state = false;
			console.log(newMsg);
			newMsg.save(function(err) {
				if(err) {
					res.send({ status : 500, err : err });
				} else {
					console.log(newMsg);
					res.json({ status : 200, response : newMsg });
				}
			})
		});
	});

router.route('/messages/:group_id')
	.get(function(req, res) {
		Messages.find({ groupID : req.params.group_id, state : false })
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msgs) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : msgs });
			});
	});

router.route('/messages/archive/:group_id')
	.get(function(req, res) {
		Messages.find({ groupID : req.params.group_id, state : true })
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msgs) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : msgs });
			});
	});

router.route('/message/:msg_id')
	.get(function(req, res) {
		Messages.findById(req.params.msg_id)
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msg){
				if(err) {
					res.send({ status : 500, err : err});
				}
				res.json({ status : 200, response : msg });
			});
	});

router.route('/message/:msg_id/complete')
	.put(function(req, res) {
		Messages.findById(req.params.msg_id, function(err, msg){
			if(err) {
				res.send({ status : 500, err : err});
			}
			msg.state = true;
			msg.dateFinished = Date.now();

			msg.save(function(err) {
				if(err) {
					res.send({ status : 500, err : err});
				}
				res.json({ status : 200, response : msg, msg : "Task Completed" });
			})
		});
	});

// ================
// ContextML Routes
// ================
// ?msg=milk
router.route('/contextml/tags')
	.get(function(req, res) {
		var message = req.param('msg');
		if(!message) {
			res.send({ status : 204, err : "No Content" });
		}
		contextML.getTags(message, function(err, tag) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : tag });
		});
	})
	.put(function(req, res) {
		var message = req.body.msg;
		var tag = req.body.tag;
		contextML.trainClassifier(message, tag, function (err) {
			if(err) {
				res.send({ status : 500, err :err});
			}
			res.json({ status : 200, response : "Trained with new data" });
		})
	});

module.exports = router;<commit_msg>chnged to url params fix<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');

var Users = require('../models/Users');
var Groups = require('../models/Groups');
var Messages = require('../models/Messages');

var contextML = require('../modules/contextML');
var Auth = require('../config/auth');

router.get('/', function (req, res) {
	res.send('You Made It!');
});

router.use(function (req, res, next) {
	if(req.query.token && req.query.fbid) {
		var FB_URL = "https://graph.facebook.com/me?";
		request.get(FB_URL + 'access_token=' + req.query.token, function (error, response, body) {
			if(error) {
				res.send({ status : 500, err : err});
			}
			var responseData = JSON.parse(body);
			if(responseData.id != req.query.fbid) {
				res.send({ status : 400, err : "Not Authorized"});
			}
			Users.count({ 'facebook.id' : responseData.id }, function(err, count) {
				if(error) {
					res.send({ status : 500, err : err}); return;
				}
				if(count == 1) {
					next();
					return;
				} else {
					var user = new Users();
						user.fname = responseData.first_name;
						user.lname = responseData.last_name;
						user.facebook.id = responseData.id;

					user.save(function (err) {
						if(err) {
							res.send({ status : 500, err : err}); return;
						}
						next();
						return;
					});
				}
			});
		});
	} else {
		res.send({ status : 400, err : "No Access Token or User ID Passed"});
	}
});
// ===========
// User Routes
// ===========
router.route('/users')
	.get(function (req, res) {
		Users.find({}, 'fname lname email', function(err, users) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : users });
		});
	});

router.route('/user/:user_id')
	.get(function(req, res) {
		Users.findById(req.params.user_id, 'fname lname email', function(err, user) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : user });
		});
	});

// ===========
// ME ENDPOINT
// ===========

router.route('/me')
	.get(function(req, res) {
		Users.findById(req.body.user_id)
			.exec(function(err, me){
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : me });
			});
	});

// ============
// Group Routes
// ============

router.route('/groups/create')
	.post(function(req, res) {
		var group = new Group();
			group.name = req.body.name;
			group.users = [];
			group.users.push(req.body.user_id);
			group.loc = req.body.loc;

		group.save(function(err) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : group, msg : "New Group Created" });
		})
	});

router.route('/group/:group_id')
	.get(function(req, res) {
		Groups.findById(req.params.group_id)
			.populate('users', '_id fname lname email')
			.exec(function(err, group) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : group });
			});
	});

router.route('/group/:group_id/add')
	.put(function(req, res) {
		Groups.findById(req.params.group_id)
			.populate('users', '_id fname lname email')
			.exec(function(err, group) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				group.users.push(req.body.user_id);
				group.save(function(err) {
					if(err) {
						res.send({ status : 500, err : err });
					}
					res.json({ status : 200, response : group, msg : "New User Added" });
				})
			});
	});

// ===============
// Messages Routes
// ===============

router.route('/messages/:group_id/create')
	.post(function(req, res) {
		Users.findOne({'facebook.id' : req.query.fbid}, function(err, user){
			if(err) {
				res.send({ status : 500, err : err});
			}
			console.log(user);
			console.log(req.query);
			var newMsg = new Messages();
				newMsg.msg = req.query.msg;
				newMsg.priority = req.query.priority || 2;
				newMsg.groupID = req.params.group_id;
				newMsg.fromUserID = user._id;
				newMsg.tags = req.query.tags;
				newMsg.locs = req.query.locs;
				newMsg.dateCreated = Date.now();
				newMsg.state = false;
			console.log(newMsg);
			newMsg.save(function(err) {
				if(err) {
					res.send({ status : 500, err : err });
				} else {
					console.log(newMsg);
					res.json({ status : 200, response : newMsg });
				}
			})
		});
	});

router.route('/messages/:group_id')
	.get(function(req, res) {
		Messages.find({ groupID : req.params.group_id, state : false })
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msgs) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : msgs });
			});
	});

router.route('/messages/archive/:group_id')
	.get(function(req, res) {
		Messages.find({ groupID : req.params.group_id, state : true })
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msgs) {
				if(err) {
					res.send({ status : 500, err : err });
				}
				res.json({ status : 200, response : msgs });
			});
	});

router.route('/message/:msg_id')
	.get(function(req, res) {
		Messages.findById(req.params.msg_id)
			.populate('groupID')
			.populate('fromUserID', 'fname lname _id email')
			.exec(function(err, msg){
				if(err) {
					res.send({ status : 500, err : err});
				}
				res.json({ status : 200, response : msg });
			});
	});

router.route('/message/:msg_id/complete')
	.put(function(req, res) {
		Messages.findById(req.params.msg_id, function(err, msg){
			if(err) {
				res.send({ status : 500, err : err});
			}
			msg.state = true;
			msg.dateFinished = Date.now();

			msg.save(function(err) {
				if(err) {
					res.send({ status : 500, err : err});
				}
				res.json({ status : 200, response : msg, msg : "Task Completed" });
			})
		});
	});

// ================
// ContextML Routes
// ================
// ?msg=milk
router.route('/contextml/tags')
	.get(function(req, res) {
		var message = req.param('msg');
		if(!message) {
			res.send({ status : 204, err : "No Content" });
		}
		contextML.getTags(message, function(err, tag) {
			if(err) {
				res.send({ status : 500, err : err });
			}
			res.json({ status : 200, response : tag });
		});
	})
	.put(function(req, res) {
		var message = req.body.msg;
		var tag = req.body.tag;
		contextML.trainClassifier(message, tag, function (err) {
			if(err) {
				res.send({ status : 500, err :err});
			}
			res.json({ status : 200, response : "Trained with new data" });
		})
	});

module.exports = router;<|endoftext|>


<commit_before>/* eslint max-lines: 0 */
import React, { Component } from "react";
import classNames from "classnames";
import manager from "../middleware/ChannelManager";
import { StaticSearch } from "../addons/StaticSearch";
import _ from "lodash";

const helper = require("../middleware/helper");

export default class DataList extends Component {
	constructor(props) {
		super(props);

		this.state = {
			data: props.data,
			selected: null
		};

		this.type = this.props.multipleSelect ? "Terms" : "Term";
		this.urlParams = helper.URLParams.get(this.props.componentId, props.multipleSelect);
		this.customQuery = this.customQuery.bind(this);
		this.renderObjectList = this.renderObjectList.bind(this);
		this.renderStringList = this.renderStringList.bind(this);
		this.filterBySearch = this.filterBySearch.bind(this);
	}

	componentWillMount() {
		this.setQueryInfo();
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	componentWillReceiveProps(nextProps) {
		this.setState({
			data: nextProps.data
		});
		if (this.props.defaultSelected !== nextProps.defaultSelected) {
			this.changeValue(nextProps.defaultSelected);
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.reset();
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId, props.multipleSelect);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(defaultValue) {
				if (this.props.multipleSelect) {
					if (Array.isArray(defaultValue)) {
						let selected = [];
						defaultValue.forEach(item => {
							this.state.data.some(record => {
								if (record.label ? record.label === item : record === item) {
									selected.push(record);
									return true;
								}
							});
						});
						// when defaultSelected is updated, the selected values should be set without depending on their previous state
						this.setState({
							selected
						}, () => {
							this.defaultSelected = selected;
							this.executeQuery(selected);
						});
					} else {
						console.error(`${this.props.componentId} - defaultSelected should be an array`);
					}
				} else {
					this.state.data.some(record => {
						if (record.label ? record.label === defaultValue : record === defaultValue) {
							this.handleChange(record);
							return true;
						}
					});
				}
			} else if (defaultValue === null) {
				if (this.props.multipleSelect) {
					this.handleCheckboxChange(null);
				} else {
					this.handleChange(null);
				}
			}
		}
	}

	// set the query type and input data
	setQueryInfo() {
		const obj = {
			key: this.props.componentId,
			value: {
				queryType: this.type,
				inputData: this.props.appbaseField,
				customQuery: this.props.customQuery ? this.props.customQuery : this.customQuery,
				reactiveId: this.context.reactiveId,
				showFilter: this.props.showFilter,
				filterLabel: this.props.filterLabel ? this.props.filterLabel : this.props.componentId,
				component: this.props.component,
				defaultSelected: this.urlParams !== null ? this.urlParams : this.props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	customQuery(record) {
		if (record) {
			const listQuery= {
				[this.type]: {
					[this.props.appbaseField]: record
				}
			};
			return this.props.multipleSelect ? (record.length ? listQuery : null) : listQuery;
		}
		return null;
	}

	reset() {
		this.setState({
			selected: this.props.multipleSelect ? [] : ""
		});

		const obj = {
			key: this.props.componentId,
			value: null
		};

		if (this.props.onValueChange) {
			this.props.onValueChange(null);
		}

		helper.URLParams.update(this.props.componentId, null, this.props.URLParams);
		helper.selectedSensor.set(obj, true);
	}

	handleChange(record) {
		let value = record;

		if (typeof this.state.data[0] === "object") {
			value = record.value;
		}

		this.setState({
			selected: value
		}, () => {
			this.defaultSelected = value;
		});

		this.executeQuery(value);
	}

	handleCheckboxChange(record) {
		let { selected, data } = this.state;
		let value = record;

		if (typeof data[0] === "object") {
			value = record.value;
		}

		if (selected && selected.length) {
			const index = selected.indexOf(value);

			if (index >= 0) {
				selected.splice(index, 1);
			} else {
				selected.push(value);
			}
		} else {
			selected = [value];
		}

		this.setState({
			selected: selected
		}, () => {
			this.defaultSelected = selected;
		});

		this.executeQuery(selected);
	}

	executeQuery(value) {
		const obj = {
			key: this.props.componentId,
			value
		};

		if (this.props.onValueChange) {
			this.props.onValueChange(value);
		}

		const selectedValue = typeof value === "string" ? ( value.trim() ? value : null ) : value;
		helper.URLParams.update(this.props.componentId, selectedValue, this.props.URLParams);
		helper.selectedSensor.set(obj, true);
	}

	renderObjectList() {
		const { data, selected } = this.state;
		let list;

		if (data) {
			if (this.props.multipleSelect) {
				const cx = classNames({
					"rbc-checkbox-active": this.props.showCheckbox,
					"rbc-checkbox-inactive": !this.props.showCheckbox
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected && selected === record.value ? "rbc-list-item-active" : ""}`} key={`${record.label}-${i}`}>
						<input
							type="checkbox"
							className="rbc-checkbox-item"
							checked={selected && selected.indexOf(record.value) >= 0}
							onChange={() => this.handleCheckboxChange(record)}
							id={`${record.label}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record.label}-${i}`}>{record.label}

				));
			} else {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected && selected === record.value ? "rbc-list-item-active" : ""}`} key={`${record.label}-${i}`}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selected && selected === record.value}
							onChange={() => this.handleChange(record)}
							id={`${record.label}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record.label}-${i}`}>{record.label}

				));
			}
		}
		return list;
	}

	renderStringList() {
		const { data, selected } = this.state;
		let list;

		if (data) {
			if (this.props.multipleSelect) {
				const cx = classNames({
					"rbc-checkbox-active": this.props.showCheckbox,
					"rbc-checkbox-inactive": !this.props.showCheckbox
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected === record ? "rbc-list-item-active" : ""}`} key={`${record}-${i}`}>
						<input
							type="checkbox"
							className="rbc-checkbox-item"
							checked={selected && selected.indexOf(record) >= 0}
							onChange={() =>  this.handleCheckboxChange(record)}
							id={`${record}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record}-${i}`}>{record}

				));
			} else {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected === record ? "rbc-list-item-active" : ""}`} key={`${record}-${i}`}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selected === record}
							onChange={() => this.handleChange(record)}
							id={`${record}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record}-${i}`}>{record}

				));
			}
		}
		return list;
	}

	filterBySearch(value) {
		if (value && value.trim() !== "") {
			let data = null;
			if (typeof this.props.data[0] === "object") {
				data = this.props.data.filter(item => item.label.toLowerCase().indexOf(value.toLowerCase()) > -1);
			} else {
				data = this.props.data.filter(item => item.toLowerCase().indexOf(value.toLowerCase()) > -1);
			}
			this.setState({
				data
			});
		} else if (value.trim() === "") {
			this.setState({
				data: this.props.data
			});
		}
	}

	render() {
		let listComponent = null,
			title = null;

		if (this.props.data.length === 0) {
			return null;
		} else {
			if (typeof this.props.data[0] === "object") {
				listComponent = this.renderObjectList();
			} else {
				listComponent = this.renderStringList();
			}
		}

		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-placeholder-active": this.props.placeholder,
			"rbc-placeholder-inactive": !this.props.placeholder,
			"rbc-singledatalist": !this.props.multipleSelect,
			"rbc-multidatalist": this.props.multipleSelect,
			"rbc-initialloader-active": this.props.initialLoader,
			"rbc-initialloader-inactive": !this.props.initialLoader
		});

		return (
			<div className={`rbc col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.componentStyle}>
				{title}
				{
					this.props.showSearch
						? (<StaticSearch
							placeholder={this.props.placeholder}
							changeCallback={this.filterBySearch}
						/>)
						: null
				}

					{listComponent}

		);
	}
}

DataList.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	appbaseField: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	showSearch: React.PropTypes.bool,
	placeholder: React.PropTypes.string,
	data: React.PropTypes.array,
	defaultSelected: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.array
	]),
	multipleSelect: React.PropTypes.bool,
	customQuery: React.PropTypes.func,
	componentStyle: React.PropTypes.object,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	showRadio: React.PropTypes.bool,
	showCheckbox: React.PropTypes.bool
};

// Default props value
DataList.defaultProps = {
	title: null,
	showSearch: false,
	placeholder: "Search",
	componentStyle: {},
	URLParams: false,
	multipleSelect: false,
	showFilter: true,
	showRadio: true,
	showCheckbox: true
};

DataList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};
<commit_msg>Fix SingleDataList defaultSelected logic<commit_after>/* eslint max-lines: 0 */
import React, { Component } from "react";
import classNames from "classnames";
import manager from "../middleware/ChannelManager";
import { StaticSearch } from "../addons/StaticSearch";
import _ from "lodash";

const helper = require("../middleware/helper");

export default class DataList extends Component {
	constructor(props) {
		super(props);

		this.state = {
			data: props.data,
			selected: null
		};

		this.type = this.props.multipleSelect ? "Terms" : "Term";
		this.urlParams = helper.URLParams.get(this.props.componentId, props.multipleSelect);
		this.customQuery = this.customQuery.bind(this);
		this.renderObjectList = this.renderObjectList.bind(this);
		this.renderStringList = this.renderStringList.bind(this);
		this.filterBySearch = this.filterBySearch.bind(this);
	}

	componentWillMount() {
		this.setQueryInfo();
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	componentWillReceiveProps(nextProps) {
		this.setState({
			data: nextProps.data
		});
		if (this.props.defaultSelected !== nextProps.defaultSelected) {
			this.changeValue(nextProps.defaultSelected);
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.reset();
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId, props.multipleSelect);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(defaultValue) {
				if (this.props.multipleSelect) {
					if (Array.isArray(defaultValue)) {
						let selected = [];
						defaultValue.forEach(item => {
							this.state.data.some(record => {
								if (record.label ? record.label === item : record === item) {
									selected.push(record);
									return true;
								}
							});
						});
						// when defaultSelected is updated, the selected values should be set without depending on their previous state
						this.setState({
							selected
						}, () => {
							this.defaultSelected = selected;
							this.executeQuery(selected);
						});
					} else {
						console.error(`${this.props.componentId} - defaultSelected should be an array`);
					}
				} else {
					this.state.data.some(record => {
						if (record.label ? record.label === defaultValue : record === defaultValue) {
							setTimeout(() => {
								this.handleChange(record);
							}, 100);
							return true;
						}
					});
				}
			} else if (defaultValue === null) {
				if (this.props.multipleSelect) {
					this.handleCheckboxChange(null);
				} else {
					this.handleChange(null);
				}
			}
		}
	}

	// set the query type and input data
	setQueryInfo() {
		const obj = {
			key: this.props.componentId,
			value: {
				queryType: this.type,
				inputData: this.props.appbaseField,
				customQuery: this.props.customQuery ? this.props.customQuery : this.customQuery,
				reactiveId: this.context.reactiveId,
				showFilter: this.props.showFilter,
				filterLabel: this.props.filterLabel ? this.props.filterLabel : this.props.componentId,
				component: this.props.component,
				defaultSelected: this.urlParams !== null ? this.urlParams : this.props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	customQuery(record) {
		if (record) {
			const listQuery= {
				[this.type]: {
					[this.props.appbaseField]: record
				}
			};
			return this.props.multipleSelect ? (record.length ? listQuery : null) : listQuery;
		}
		return null;
	}

	reset() {
		this.setState({
			selected: this.props.multipleSelect ? [] : ""
		});

		const obj = {
			key: this.props.componentId,
			value: null
		};

		if (this.props.onValueChange) {
			this.props.onValueChange(null);
		}

		helper.URLParams.update(this.props.componentId, null, this.props.URLParams);
		helper.selectedSensor.set(obj, true);
	}

	handleChange(record) {
		let value = record;

		if (typeof this.state.data[0] === "object") {
			value = record.value;
		}

		this.setState({
			selected: value
		}, () => {
			this.defaultSelected = value;
		});

		this.executeQuery(value);
	}

	handleCheckboxChange(record) {
		let { selected, data } = this.state;
		let value = record;

		if (typeof data[0] === "object") {
			value = record.value;
		}

		if (selected && selected.length) {
			const index = selected.indexOf(value);

			if (index >= 0) {
				selected.splice(index, 1);
			} else {
				selected.push(value);
			}
		} else {
			selected = [value];
		}

		this.setState({
			selected: selected
		}, () => {
			this.defaultSelected = selected;
		});

		this.executeQuery(selected);
	}

	executeQuery(value) {
		const obj = {
			key: this.props.componentId,
			value
		};

		if (this.props.onValueChange) {
			this.props.onValueChange(value);
		}

		const selectedValue = typeof value === "string" ? ( value.trim() ? value : null ) : value;
		helper.URLParams.update(this.props.componentId, selectedValue, this.props.URLParams);
		helper.selectedSensor.set(obj, true);
	}

	renderObjectList() {
		const { data, selected } = this.state;
		let list;

		if (data) {
			if (this.props.multipleSelect) {
				const cx = classNames({
					"rbc-checkbox-active": this.props.showCheckbox,
					"rbc-checkbox-inactive": !this.props.showCheckbox
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected && selected === record.value ? "rbc-list-item-active" : ""}`} key={`${record.label}-${i}`}>
						<input
							type="checkbox"
							className="rbc-checkbox-item"
							checked={selected && selected.indexOf(record.value) >= 0}
							onChange={() => this.handleCheckboxChange(record)}
							id={`${record.label}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record.label}-${i}`}>{record.label}

				));
			} else {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected && selected === record.value ? "rbc-list-item-active" : ""}`} key={`${record.label}-${i}`}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selected && selected === record.value}
							onChange={() => this.handleChange(record)}
							id={`${record.label}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record.label}-${i}`}>{record.label}

				));
			}
		}
		return list;
	}

	renderStringList() {
		const { data, selected } = this.state;
		let list;

		if (data) {
			if (this.props.multipleSelect) {
				const cx = classNames({
					"rbc-checkbox-active": this.props.showCheckbox,
					"rbc-checkbox-inactive": !this.props.showCheckbox
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected === record ? "rbc-list-item-active" : ""}`} key={`${record}-${i}`}>
						<input
							type="checkbox"
							className="rbc-checkbox-item"
							checked={selected && selected.indexOf(record) >= 0}
							onChange={() =>  this.handleCheckboxChange(record)}
							id={`${record}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record}-${i}`}>{record}

				));
			} else {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio
				});
				list = data.map((record, i) => (
					<div className={`rbc-list-item row ${cx} ${selected === record ? "rbc-list-item-active" : ""}`} key={`${record}-${i}`}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selected === record}
							onChange={() => this.handleChange(record)}
							id={`${record}-${i}`}
						/>
						<label className="rbc-label" htmlFor={`${record}-${i}`}>{record}

				));
			}
		}
		return list;
	}

	filterBySearch(value) {
		if (value && value.trim() !== "") {
			let data = null;
			if (typeof this.props.data[0] === "object") {
				data = this.props.data.filter(item => item.label.toLowerCase().indexOf(value.toLowerCase()) > -1);
			} else {
				data = this.props.data.filter(item => item.toLowerCase().indexOf(value.toLowerCase()) > -1);
			}
			this.setState({
				data
			});
		} else if (value.trim() === "") {
			this.setState({
				data: this.props.data
			});
		}
	}

	render() {
		let listComponent = null,
			title = null;

		if (this.props.data.length === 0) {
			return null;
		} else {
			if (typeof this.props.data[0] === "object") {
				listComponent = this.renderObjectList();
			} else {
				listComponent = this.renderStringList();
			}
		}

		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-placeholder-active": this.props.placeholder,
			"rbc-placeholder-inactive": !this.props.placeholder,
			"rbc-singledatalist": !this.props.multipleSelect,
			"rbc-multidatalist": this.props.multipleSelect,
			"rbc-initialloader-active": this.props.initialLoader,
			"rbc-initialloader-inactive": !this.props.initialLoader
		});

		return (
			<div className={`rbc col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.componentStyle}>
				{title}
				{
					this.props.showSearch
						? (<StaticSearch
							placeholder={this.props.placeholder}
							changeCallback={this.filterBySearch}
						/>)
						: null
				}

					{listComponent}

		);
	}
}

DataList.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	appbaseField: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	showSearch: React.PropTypes.bool,
	placeholder: React.PropTypes.string,
	data: React.PropTypes.array,
	defaultSelected: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.array
	]),
	multipleSelect: React.PropTypes.bool,
	customQuery: React.PropTypes.func,
	componentStyle: React.PropTypes.object,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	showRadio: React.PropTypes.bool,
	showCheckbox: React.PropTypes.bool
};

// Default props value
DataList.defaultProps = {
	title: null,
	showSearch: false,
	placeholder: "Search",
	componentStyle: {},
	URLParams: false,
	multipleSelect: false,
	showFilter: true,
	showRadio: true,
	showCheckbox: true
};

DataList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.map', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/map', {
    templateUrl: 'map/map.html',
    controller: 'MapController'
  });
}])

.controller('MapController', function($scope) {

  $scope.circle = {};
  $scope.circle.doClick = function () {

// start scale and transition example

      var w = 500;
      var h = 100;
      var dataset = [
              {
                x: 5,
                y: 20,
                r: 10,
                color:"red"
              },
              {
                x: 480,
                y: 90,
                r: 20,
                color:"blue"
              },
              {
                x: 250,
                y: 50,
                r: 15,
                color:"yellow"
              },
              {
                x: 100,
                y: 33,
                r: 7,
                color:"steelblue"
              },
              {
                x: 330,
                y: 95,
                r: 18,
                color:"green"
              },
              {
                x: 410,
                y: 12,
                r: 19,
                color:"purple"
              },
              {
                x: 475,
                y: 44,
                r: 25,
                color:"orange"
              },
              {
                x: 25,
                y: 67,
                r: 12,
                color:"brown"
              },
              {
                x: 85,
                y: 21,
                r: 5,
                color:"pink"
              },
              {
                x: 220,
                y: 88,
                r: 3,
                color:"turquoise"
              }
              ];

        var xScale = d3.scale.linear()
                   .domain([0, d3.max(dataset, function(d) { return d.x; })])
                   .range([0, w]);

        var yScale = d3.scale.linear()
                   .domain([0, d3.max(dataset, function(d) { return d.y; })])
                   .range([0, h]);

        //Create SVG element
        var svg = d3.select("#main")
              .append("svg")
              .attr("width", w)
              .attr("height", h);

            svg.selectAll("circle")
           .data(dataset)
           .enter()
           .append("circle")
           .attr("cx", w / 2)
           .attr("cy", h / 2)
           .attr("r", 1)
           .attr("fill", function(d){
             return d.color;
           })
           .transition()
           .duration(5000)
           .attr("cx", function(d) {
            return xScale(d.x);
           })
           .attr("r", function(d) {
             return d.r;
           })
           .attr("cy", function(d) {
             return yScale(d.y);
           })
           .attr("fill", function(d){
              return d.color;
           });
      };

});
<commit_msg>made the circle object a var<commit_after>'use strict';

angular.module('myApp.map', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/map', {
    templateUrl: 'map/map.html',
    controller: 'MapController'
  });
}])

.controller('MapController', function($scope) {

  var circle = {};

  $scope.circle = function doClick () {

// start scale and transition example

      var w = 500;
      var h = 100;
      var dataset = [
              {
                x: 5,
                y: 20,
                r: 10,
                color:"red"
              },
              {
                x: 480,
                y: 90,
                r: 20,
                color:"blue"
              },
              {
                x: 250,
                y: 50,
                r: 15,
                color:"yellow"
              },
              {
                x: 100,
                y: 33,
                r: 7,
                color:"steelblue"
              },
              {
                x: 330,
                y: 95,
                r: 18,
                color:"green"
              },
              {
                x: 410,
                y: 12,
                r: 19,
                color:"purple"
              },
              {
                x: 475,
                y: 44,
                r: 25,
                color:"orange"
              },
              {
                x: 25,
                y: 67,
                r: 12,
                color:"brown"
              },
              {
                x: 85,
                y: 21,
                r: 5,
                color:"pink"
              },
              {
                x: 220,
                y: 88,
                r: 3,
                color:"turquoise"
              }
              ];

        var xScale = d3.scale.linear()
                   .domain([0, d3.max(dataset, function(d) { return d.x; })])
                   .range([0, w]);

        var yScale = d3.scale.linear()
                   .domain([0, d3.max(dataset, function(d) { return d.y; })])
                   .range([0, h]);

        //Create SVG element
        var svg = d3.select("#main")
              .append("svg")
              .attr("width", w)
              .attr("height", h);

            svg.selectAll("circle")
           .data(dataset)
           .enter()
           .append("circle")
           .attr("cx", w / 2)
           .attr("cy", h / 2)
           .attr("r", 1)
           .attr("fill", function(d){
             return d.color;
           })
           .transition()
           .duration(5000)
           .attr("cx", function(d) {
            return xScale(d.x);
           })
           .attr("r", function(d) {
             return d.r;
           })
           .attr("cy", function(d) {
             return yScale(d.y);
           })
           .attr("fill", function(d){
              return d.color;
           });
      };

});
<|endoftext|>


<commit_before>import History from '../plugins/history'

// Needs:
// __show()
// __hide()
// Calling this.showPromiseResolve, this.hidePromiseResolve
// avoid backbutton with setting noShowingHistory
export default {
  props: {
    value: Boolean
  },
  data () {
    return {
      showing: false
    }
  },
  watch: {
    value (val) {
      if (this.disable && val) {
        this.$emit('input', false)
        return
      }

      this.$nextTick(() => {
        if (this.value !== this.showing) {
          this[val ? 'show' : 'hide']()
        }
      })
    }
  },
  methods: {
    toggle (evt) {
      if (!this.disable) {
        return this[this.showing ? 'hide' : 'show'](evt)
      }
    },
    show (evt) {
      if (this.disable) {
        return Promise.reject(new Error())
      }

      if (this.showing) {
        return this.showPromise || Promise.resolve(evt)
      }

      if (this.hidePromise) {
        this.hidePromiseReject()
      }

      this.showing = true
      if (this.value === false) {
        this.$emit('input', true)
      }

      if (this.$options.modelToggle === void 0 || this.$options.modelToggle.history) {
        this.__historyEntry = {
          handler: this.hide
        }
        History.add(this.__historyEntry)
      }

      if (!this.__show) {
        this.$emit('show')
        return Promise.resolve(evt)
      }

      this.showPromise = new Promise((resolve, reject) => {
        this.showPromiseResolve = () => {
          this.showPromise = null
          this.$emit('show')
          resolve(evt)
        }
        this.showPromiseReject = () => {
          this.showPromise = null
          reject(new Error())
        }
      })

      this.__show(evt)
      return this.showPromise || Promise.resolve(evt)
    },
    hide (evt) {
      if (this.disable) {
        return Promise.reject(new Error())
      }

      if (!this.showing) {
        return this.hidePromise || Promise.resolve()
      }

      if (this.showPromise) {
        this.showPromiseReject()
      }

      this.showing = false
      if (this.value === true) {
        this.$emit('input', false)
      }

      if (this.__historyEntry) {
        History.remove(this.__historyEntry)
        this.__historyEntry = null
      }

      if (!this.__hide) {
        this.$emit('hide')
        return Promise.resolve()
      }

      this.hidePromise = new Promise((resolve, reject) => {
        this.hidePromiseResolve = () => {
          this.hidePromise = null
          this.$emit('hide')
          resolve()
        }
        this.hidePromiseReject = () => {
          this.hidePromise = null
          reject(new Error())
        }
      })

      this.__hide(evt)
      return this.hidePromise || Promise.resolve()
    }
  },
  beforeDestroy () {
    if (this.showing) {
      this.showPromise && this.showPromiseReject()
      this.hidePromise && this.hidePromiseReject()
      this.$emit('input', false)
      this.__hide && this.__hide()
    }
  }
}
<commit_msg>Resolve hidePromise with evt (#1191)<commit_after>import History from '../plugins/history'

// Needs:
// __show()
// __hide()
// Calling this.showPromiseResolve, this.hidePromiseResolve
// avoid backbutton with setting noShowingHistory
export default {
  props: {
    value: Boolean
  },
  data () {
    return {
      showing: false
    }
  },
  watch: {
    value (val) {
      if (this.disable && val) {
        this.$emit('input', false)
        return
      }

      this.$nextTick(() => {
        if (this.value !== this.showing) {
          this[val ? 'show' : 'hide']()
        }
      })
    }
  },
  methods: {
    toggle (evt) {
      if (!this.disable) {
        return this[this.showing ? 'hide' : 'show'](evt)
      }
    },
    show (evt) {
      if (this.disable) {
        return Promise.reject(new Error())
      }

      if (this.showing) {
        return this.showPromise || Promise.resolve(evt)
      }

      if (this.hidePromise) {
        this.hidePromiseReject()
      }

      this.showing = true
      if (this.value === false) {
        this.$emit('input', true)
      }

      if (this.$options.modelToggle === void 0 || this.$options.modelToggle.history) {
        this.__historyEntry = {
          handler: this.hide
        }
        History.add(this.__historyEntry)
      }

      if (!this.__show) {
        this.$emit('show')
        return Promise.resolve(evt)
      }

      this.showPromise = new Promise((resolve, reject) => {
        this.showPromiseResolve = () => {
          this.showPromise = null
          this.$emit('show')
          resolve(evt)
        }
        this.showPromiseReject = () => {
          this.showPromise = null
          reject(new Error())
        }
      })

      this.__show(evt)
      return this.showPromise || Promise.resolve(evt)
    },
    hide (evt) {
      if (this.disable) {
        return Promise.reject(new Error())
      }

      if (!this.showing) {
        return this.hidePromise || Promise.resolve(evt)
      }

      if (this.showPromise) {
        this.showPromiseReject()
      }

      this.showing = false
      if (this.value === true) {
        this.$emit('input', false)
      }

      if (this.__historyEntry) {
        History.remove(this.__historyEntry)
        this.__historyEntry = null
      }

      if (!this.__hide) {
        this.$emit('hide')
        return Promise.resolve()
      }

      this.hidePromise = new Promise((resolve, reject) => {
        this.hidePromiseResolve = () => {
          this.hidePromise = null
          this.$emit('hide')
          resolve()
        }
        this.hidePromiseReject = () => {
          this.hidePromise = null
          reject(new Error())
        }
      })

      this.__hide(evt)
      return this.hidePromise || Promise.resolve(evt)
    }
  },
  beforeDestroy () {
    if (this.showing) {
      this.showPromise && this.showPromiseReject()
      this.hidePromise && this.hidePromiseReject()
      this.$emit('input', false)
      this.__hide && this.__hide()
    }
  }
}
<|endoftext|>


<commit_before>var jenkinsapi = require('jenkins-api'),
    async = require('async');

module.exports = function () {
    var self = this,
        jenkins,
        requestBuilds = function (callback) {
            jenkins.job_info(self.configuration.job, function(error, data) {
                callback(data.builds);
            });
        },
        requestBuild = function (build, callback) {
            jenkins.build_info(self.configuration.job, build.number, function(error, data) {
                callback(error, simplifyBuild(data));
            });
        },
        queryBuilds = function (callback) {
            requestBuilds(function (body) {
                async.map(body, requestBuild, function (error, results) {
                    callback(results);
                });
            });
        },
        parseDate = function (dateAsString) {
            return new Date(dateAsString);
        },
        getStatus = function (result) {
            if (result === 'FAILURE') return "Red";
            if (result === 'SUCCESS') return "Green";
            if (result === 'UNSTABLE') return "Green";
            if (result === 'NOT_BUILT') return "Blue";
            if (result === 'ABORTED') return "Gray";
            if (result === null) return "Blue";

            return null;
        },
        getStatusText = function (result) {
            if (result === 'FAILURE') return "Failure";
            if (result === 'SUCCESS') return "Success";
            if (result === 'UNSTABLE') return "Unstable";
            if (result === 'NOT_BUILT') return "Running";
            if (result === 'ABORTED') return "Aborted";
            if (result === null) return "Running";

            return null;
        },
        getRequestedFor = function (build) {
            if(build.actions) {
                for (var i = 0; i < build.actions.length; i++) {
                    var action = build.actions[i];
                    if (action.causes) {
                        for (var i = 0; i < action.causes.length; i++) {
                            var cause = build.actions[i].causes[i];
                            if(cause && cause.userName) {
                                return cause.userName;
                            }
                        };
                    }
                };
            }

            return "Unknown";
        },
        simplifyBuild = function (res) {
            return {
                id: self.configuration.job + '|' + res.id,
                project: self.configuration.job,
                number: res.number,
                isRunning: res.building,
                startedAt: parseDate(res.timestamp),
                finishedAt: parseDate(res.timestamp + res.duration),
                requestedFor: getRequestedFor(res),
                status: getStatus(res.result),
                statusText: getStatusText(res.result),
                reason: "Build",
                hasErrors: false,
                hasWarnings: res.result == 'UNSTABLE'
            };
        };

    self.configure = function (config) {
        self.configuration = config;

        jenkins = jenkinsapi.init(self.configuration.url);
    };

    self.check = function (callback) {
        queryBuilds(callback);
    };
};<commit_msg>Fixed build errors.<commit_after>var jenkinsapi = require('jenkins-api'),
    async = require('async');

module.exports = function () {
    var self = this,
        jenkins,
        requestBuilds = function (callback) {
            jenkins.job_info(self.configuration.job, function(error, data) {
                callback(data.builds);
            });
        },
        requestBuild = function (build, callback) {
            jenkins.build_info(self.configuration.job, build.number, function(error, data) {
                callback(error, simplifyBuild(data));
            });
        },
        queryBuilds = function (callback) {
            requestBuilds(function (body) {
                async.map(body, requestBuild, function (error, results) {
                    callback(results);
                });
            });
        },
        parseDate = function (dateAsString) {
            return new Date(dateAsString);
        },
        getStatus = function (result) {
            if (result === 'FAILURE') return "Red";
            if (result === 'SUCCESS') return "Green";
            if (result === 'UNSTABLE') return "Green";
            if (result === 'NOT_BUILT') return "Blue";
            if (result === 'ABORTED') return "Gray";
            if (result === null) return "Blue";

            return null;
        },
        getStatusText = function (result) {
            if (result === 'FAILURE') return "Failure";
            if (result === 'SUCCESS') return "Success";
            if (result === 'UNSTABLE') return "Unstable";
            if (result === 'NOT_BUILT') return "Running";
            if (result === 'ABORTED') return "Aborted";
            if (result === null) return "Running";

            return null;
        },
        getRequestedFor = function (build) {
            if(build.actions) {
                for (var i = 0; i < build.actions.length; i++) {
                    var action = build.actions[i];
                    if (action.causes) {
                        for (var j = 0; j < action.causes.length; j++) {
                            var cause = action.causes[j];
                            if(cause && cause.userName) {
                                return cause.userName;
                            }
                        }
                    }
                }
            }

            return "Unknown";
        },
        simplifyBuild = function (res) {
            return {
                id: self.configuration.job + '|' + res.id,
                project: self.configuration.job,
                number: res.number,
                isRunning: res.building,
                startedAt: parseDate(res.timestamp),
                finishedAt: parseDate(res.timestamp + res.duration),
                requestedFor: getRequestedFor(res),
                status: getStatus(res.result),
                statusText: getStatusText(res.result),
                reason: "Build",
                hasErrors: false,
                hasWarnings: res.result == 'UNSTABLE'
            };
        };

    self.configure = function (config) {
        self.configuration = config;

        jenkins = jenkinsapi.init(self.configuration.url);
    };

    self.check = function (callback) {
        queryBuilds(callback);
    };
};<|endoftext|>


<commit_before>export default {
  data () {
    return {
      obj_height: null,
      parallax: null,
      parallax_dist: null,
      bottom: null,
      top: null,
      scroll_top: null,
      window_height: null,
      window_bottom: null
    }
  },

  mounted () {
    this.$vuetify.load.call(this, this.init)
  },

  beforeDestroy () {
    document.removeEventListener('scroll', this.translate)
    document.removeEventListener('resize', this.translate)
  },

  methods: {
    listeners () {
      document.addEventListener('scroll', this.translate)
      document.addEventListener('resize', this.translate)
    },

    translate () {
      this.calcDimensions()

      let percent_scrolled = (
        (this.window_bottom - this.top) / (this.height + this.window_height)
      )

      this.parallax = Math.round(this.parallax_dist * percent_scrolled)

      if (this.translated) {
        this.translated()
      }
    },

    calcDimensions () {
      this.obj_height = this.objHeight()
      this.parallax_dist = this.obj_height - this.height
      this.top = this.elOffsetTop()
      this.bottom = this.top + this.height
      this.scroll_top = window.pageYOffset
      this.window_height = window.innerHeight
      this.window_bottom = this.scroll_top + this.window_height
    }
  }
}<commit_msg>bug fix for click events<commit_after>export default {
  data () {
    return {
      obj_height: null,
      parallax: null,
      parallax_dist: null,
      bottom: null,
      top: null,
      scroll_top: null,
      window_height: null,
      window_bottom: null
    }
  },

  mounted () {
    this.$vuetify.load.call(this, this.init)
  },

  beforeDestroy () {
    document.removeEventListener('scroll', this.translate, false)
    document.removeEventListener('resize', this.translate, false)
  },

  methods: {
    listeners () {
      document.addEventListener('scroll', this.translate, false)
      document.addEventListener('resize', this.translate, false)
    },

    translate () {
      this.calcDimensions()

      let percent_scrolled = (
        (this.window_bottom - this.top) / (this.height + this.window_height)
      )

      this.parallax = Math.round(this.parallax_dist * percent_scrolled)

      if (this.translated) {
        this.translated()
      }
    },

    calcDimensions () {
      this.obj_height = this.objHeight()
      this.parallax_dist = this.obj_height - this.height
      this.top = this.elOffsetTop()
      this.bottom = this.top + this.height
      this.scroll_top = window.pageYOffset
      this.window_height = window.innerHeight
      this.window_bottom = this.scroll_top + this.window_height
    }
  }
}<|endoftext|>


<commit_before>/*
    Copyright (c) 2016 eyeOS

    This file is part of Open365.

    Open365 is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    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';
define(['./urlConfig'], function (urlConfig) {

	function getConfigs(settingsMap) {
		var key;
		for (key in window.settingsStatic) {
			settingsMap[key] = window.settingsStatic[key];
		}

		for (key in urlConfig) {
			settingsMap[key] = urlConfig[key];
		}
		return settingsMap;
	}

	angular.module('settings', [])
		.constant('SETTINGS', getConfigs({
			'LOGIN_URL': '/applogin',
			'PRINCIPAL_SERVICE_URL': '/principalService/v1',
			'ENVIRONMENT': 'release', //develop or release
			'PEOPLE_GROUPS_ENABLED': true,
			'FILES_SERVER_URL': '/files/v1',
			'LOADING_APP_SHOW_IN_WINDOW': true
		}));

	var settings = getConfigs({
		'VDI_RESIZE_TIMEOUT': 100,
		'VDI_RECONNECTION_RETRY_TIME': 1000,
		'VDI_RECONNECTION_FREEZE_TIME': 4000,
		'VDI_RECONNECTION_CANCEL_TIME': 6000000,
		'VDI_RECONNECTION_FREEZE': false,
		'VDI_MAX_RESOLUTION_WIDTH': 1920,
		'VDI_MAX_RESOLUTION_HEIGHT': 1080,
		'VDI_FULL_DESKTOP_EXECUTION': '<<EXECUTION_SCRIPT_ROUTE>>', // Not needed with windows. It cannot be empty.
		'SPICE_CLIENT_PATH': '/bower_components/spice-web-client/',
		'SUPPORT_HIGH_DPI': false,
		'CONNECT_TO_BUS': true,
		'CONNECT_TO_CHAT': true,
		'CHAT_HOST': 'localhost',
		'EYETHEME_NAME': 'eyeos-cloud',
		'FALLBACK_PLATFORM_LANG': 'en',
		'SHOULD_GROUP_DESKTOP_ICONS': false,
		'EYETHEME_SASS_MODE': 'server', // client or server
		'LOADING_TIMEOUT': 120000,
		'MINIMUM_LATENCY': 2, //index of the minimum good latency of the LATENCY_SCALE
		'LATENCY_TIMEOUT': 2000, // in ms
		'LATENCY_SCALE': [200, 150, 100, 50], //worst to best in ms
		'LATENCY_PING_INTERVAL': 1000, // in ms
		'LATENCY_HISTORY_SIZE': 10, // Pings to keep to do the average
		'LATENCY_PINGS_TO_TRUNCATE': 1,
		'EYEOS_EXTENSION_INSTALLED_MARK': 'eyeos-extension-is-installed',
		'PRESENCE_SERVICE_URL': '/relay/presence/v1/userEvent/ping',
		'PRESENCE_PING_INTERVAL': 30000, // milliseconds
		'WINDOW_MANAGER_STRATEGY': 'auto', // ventus|popup|auto
		'DESKTOP_MODE_RECOVER_WINDOW': false,
		'POPUP_WINDOW_TOPBAR_ACTIVE': true,
		'DETACH_WINDOW_ACTIVE': true,
		'WINDOW_RESIZE_READY_MAX_RETRIES': 2, // Native Popup maximum retries to check values integrity
		'WINDOW_OFFSET_DETECTOR_MOVETO_MAX_RETRIES': 5,
		'WINDOW_OFFSET_DETECTOR_WAITFOR_MAX_RETRIES': 10,
		'POPUP_WINDOW_RESIZED_RETRIES': 5,
		'POPUP_WINDOW_CLOSED_DETECT_RETRIES': 5,
		'POPUP_WINDOW_DEBUG_LOG': false,
		'SEAMLESS_DESKTOP_INTEGRATION': true,
		'FEEDBACK_ACTIVE': true,
		'FAQ_ACTIVE': true,
		'FORUM_ACTIVE': true,
		'BLOG_ACTIVE': true,
		'VDI_FOCUS_INTEGRATION': false,
		'VIDEOCHAT_SERVER_DOCKERIZED': false,
		'CHANGE_PASSWORD_ACTIVE': true,
		'SHOW_VIDEOCONFERENCE': true,
		'ENABLE_USER_SEARCH': true,
		'SUSPENDED_MAX_TIME_AWAY': 60000, //milliseconds
		'CHECK_SUSPENDED_INTERVAL': 5000, //milliseconds
		'CHECK_ACTIVITY_INTERVAL': 600000, //milliseconds
		'EYEOS_DISABLE_ANALYTICS': false,
		'URL_SUPPORT': "http://support.open365.io/index.php/",
		'URL_FORUM': "/forum",
		'URL_ABOUT': "http://open365.io",
		'URL_BLOG': "http://blog.open365.io",
		'LOCALIZATION_DOWNLOAD_CLIENT_ACTIVE': false,
		'URL_DOWNLOAD_CLIENT': "https://open365.io/download.html"
	});

	return settings;
});
<commit_msg>Activate dockerized videochat<commit_after>/*
    Copyright (c) 2016 eyeOS

    This file is part of Open365.

    Open365 is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    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';
define(['./urlConfig'], function (urlConfig) {

	function getConfigs(settingsMap) {
		var key;
		for (key in window.settingsStatic) {
			settingsMap[key] = window.settingsStatic[key];
		}

		for (key in urlConfig) {
			settingsMap[key] = urlConfig[key];
		}
		return settingsMap;
	}

	angular.module('settings', [])
		.constant('SETTINGS', getConfigs({
			'LOGIN_URL': '/applogin',
			'PRINCIPAL_SERVICE_URL': '/principalService/v1',
			'ENVIRONMENT': 'release', //develop or release
			'PEOPLE_GROUPS_ENABLED': true,
			'FILES_SERVER_URL': '/files/v1',
			'LOADING_APP_SHOW_IN_WINDOW': true
		}));

	var settings = getConfigs({
		'VDI_RESIZE_TIMEOUT': 100,
		'VDI_RECONNECTION_RETRY_TIME': 1000,
		'VDI_RECONNECTION_FREEZE_TIME': 4000,
		'VDI_RECONNECTION_CANCEL_TIME': 6000000,
		'VDI_RECONNECTION_FREEZE': false,
		'VDI_MAX_RESOLUTION_WIDTH': 1920,
		'VDI_MAX_RESOLUTION_HEIGHT': 1080,
		'VDI_FULL_DESKTOP_EXECUTION': '<<EXECUTION_SCRIPT_ROUTE>>', // Not needed with windows. It cannot be empty.
		'SPICE_CLIENT_PATH': '/bower_components/spice-web-client/',
		'SUPPORT_HIGH_DPI': false,
		'CONNECT_TO_BUS': true,
		'CONNECT_TO_CHAT': true,
		'CHAT_HOST': 'localhost',
		'EYETHEME_NAME': 'eyeos-cloud',
		'FALLBACK_PLATFORM_LANG': 'en',
		'SHOULD_GROUP_DESKTOP_ICONS': false,
		'EYETHEME_SASS_MODE': 'server', // client or server
		'LOADING_TIMEOUT': 120000,
		'MINIMUM_LATENCY': 2, //index of the minimum good latency of the LATENCY_SCALE
		'LATENCY_TIMEOUT': 2000, // in ms
		'LATENCY_SCALE': [200, 150, 100, 50], //worst to best in ms
		'LATENCY_PING_INTERVAL': 1000, // in ms
		'LATENCY_HISTORY_SIZE': 10, // Pings to keep to do the average
		'LATENCY_PINGS_TO_TRUNCATE': 1,
		'EYEOS_EXTENSION_INSTALLED_MARK': 'eyeos-extension-is-installed',
		'PRESENCE_SERVICE_URL': '/relay/presence/v1/userEvent/ping',
		'PRESENCE_PING_INTERVAL': 30000, // milliseconds
		'WINDOW_MANAGER_STRATEGY': 'auto', // ventus|popup|auto
		'DESKTOP_MODE_RECOVER_WINDOW': false,
		'POPUP_WINDOW_TOPBAR_ACTIVE': true,
		'DETACH_WINDOW_ACTIVE': true,
		'WINDOW_RESIZE_READY_MAX_RETRIES': 2, // Native Popup maximum retries to check values integrity
		'WINDOW_OFFSET_DETECTOR_MOVETO_MAX_RETRIES': 5,
		'WINDOW_OFFSET_DETECTOR_WAITFOR_MAX_RETRIES': 10,
		'POPUP_WINDOW_RESIZED_RETRIES': 5,
		'POPUP_WINDOW_CLOSED_DETECT_RETRIES': 5,
		'POPUP_WINDOW_DEBUG_LOG': false,
		'SEAMLESS_DESKTOP_INTEGRATION': true,
		'FEEDBACK_ACTIVE': true,
		'FAQ_ACTIVE': true,
		'FORUM_ACTIVE': true,
		'BLOG_ACTIVE': true,
		'VDI_FOCUS_INTEGRATION': false,
		'VIDEOCHAT_SERVER_DOCKERIZED': true,
		'CHANGE_PASSWORD_ACTIVE': true,
		'SHOW_VIDEOCONFERENCE': true,
		'ENABLE_USER_SEARCH': true,
		'SUSPENDED_MAX_TIME_AWAY': 60000, //milliseconds
		'CHECK_SUSPENDED_INTERVAL': 5000, //milliseconds
		'CHECK_ACTIVITY_INTERVAL': 600000, //milliseconds
		'EYEOS_DISABLE_ANALYTICS': false,
		'URL_SUPPORT': "http://support.open365.io/index.php/",
		'URL_FORUM': "/forum",
		'URL_ABOUT': "http://open365.io",
		'URL_BLOG': "http://blog.open365.io",
		'LOCALIZATION_DOWNLOAD_CLIENT_ACTIVE': false,
		'URL_DOWNLOAD_CLIENT': "https://open365.io/download.html"
	});

	return settings;
});
<|endoftext|>