<commit_before>/**
 * Copyright (c) 2008
 * Stefan Krumnow
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

if(!ORYX.Plugins)
	ORYX.Plugins = new Object();

/**
 * Supports EPCs by offering a syntax check and export and import ability..
 *
 *
 */
ORYX.Plugins.EPCSupport = Clazz.extend({

	facade: undefined,

	/**
	 * Offers the plugin functionality:
	 *
	 */
	construct: function(facade) {
		this.facade = facade;

		this.facade.offer({
			'name':"Export EPC",
			'functionality': this.exportEPC.bind(this),
			'group': "epc",
			'icon': ORYX.PATH + "images/epc_export.png",
			'description': "Export diagram to EPML",
			'index': 1,
			'minShape': 0,
			'maxShape': 0});

//		this.facade.offer({
//			'name':"Import EPC",
//			'functionality': this.importEPC.bind(this),
//			'group': "epc",
//			'icon': ORYX.PATH + "images/epc_import.png",
//			'description': "Import an EPML file",
//			'index': 2,
//			'minShape': 0,
//			'maxShape': 0});

//		Syntax Check has been migrated to syntaxchecker.js-Framework

//		this.facade.offer({
//			'name':"Check EPC's Syntax",
//			'functionality': this.checkEPC.bind(this),
//			'group': "epc",
//			'icon': ORYX.PATH + "images/epc_check.png",
//			'description': "Perfom an EPC syntax check",
//			'index': 1,
//			'minShape': 0,
//			'maxShape': 0});
	},

	/**
	 * Imports an AML or EPML description
	 */
	importEPC: function(){
		this.openUploadDialog();
	},

	/**
	 * Exports the diagram into an AML or EPML file
	 */
	exportEPC: function(){

		this.facade.raiseEvent({type:'loading.enable', text:'Exporting model'});
		var xmlSerializer = new XMLSerializer();

		// TODO: a Syntax Syntax-Check should be triggered, here.

		// TODO: get process' name
		var resource = "Oryx-EPC";

		// Force to set all resource IDs
		var serializedDOM = DataManager.serializeDOM( this.facade );

		//add namespaces
		serializedDOM = '<?xml version="1.0" encoding="utf-8"?>' +
		'' +
		'' +
		'<link rel="schema.dc" href="http://purl.org/dc/elements/1.1/" />' +
		'<link rel="schema.dcTerms" href="http://purl.org/dc/terms/ " />' +
		'<link rel="schema.b3mn" href="http://b3mn.org" />' +
		'<link rel="schema.oryx" href="http://oryx-editor.org/" />' +
		'<link rel="schema.raziel" href="http://raziel.org/" />' +
		'<base href="' +
		location.href.split("?")[0] +
		'" />' +
		'' +
		serializedDOM +
		'
' + resource + '' +
		'' + resource + '
' +
		'';

		/*
		 * Transform eRDF -> RDF
		 */
		var erdf2rdfXslt = ORYX.PATH + "/lib/extract-rdf.xsl";

		var rdfResultString;
		rdfResult = this.transformString(serializedDOM, erdf2rdfXslt, true);
		if (rdfResult instanceof String) {
			rdfResultString = rdfResult;
			rdfResult = null;
		} else {
			rdfResultString = xmlSerializer.serializeToString(rdfResult);
			if (!rdfResultString.startsWith("<?xml")) {
				rdfResultString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + rdfResultString;
			}
		}

		/*
		 * Transform RDF -> EPML
		 */
		var rdf2epmlXslt = ORYX.PATH + "/xslt/RDF2EPML.xslt";

		var epmlResult = this.transformDOM(rdfResult, rdf2epmlXslt, true);
		var epmlResultString;
		if (epmlResult instanceof String) {
			epmlResultString = epmlResult;
			epmlResult = null;
		} else {
			epmlResultString = xmlSerializer.serializeToString(epmlResult);
			if (!epmlResultString.startsWith("<?xml")) {
				epmlResultString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + epmlResultString;
			}
		}

		/*
		 * Transform EPML -> AML
		 */

// 		Note: This is uncommented due to the fact, that the epml2amlXslt does not work properly
//
//		var epml2amlXslt = ORYX.PATH +  + "/xslt/EPML2AML_2.xslt";
//
//		var amlResultString = this.transformString(epmlResultString, epml2amlXslt, false);
//		if (amlResultString.substr(0, 12) != "Parse Error:") {
//			amlResultString = '<?xml version="1.0" encoding="utf-8"?>\n' +
//				'<!DOCTYPE AML SYSTEM "ARIS-Export.dtd" [\n	<!ENTITY LocaleId.DEde "1031">\n	<!ENTITY Codepage.DEde "1252">\n]>\n' +
//				amlResultString;
//		}

		/*
		 * Show result
		 */

		this.facade.raiseEvent({type:'loading.disable'});

		// At the moment, only EPML is going to be returned.
		this.openDownloadWindow(resource + ".epml", epmlResultString);
    },

	/**
	 * Transforms the given string via xslt.
	 *
	 * @param {String} string
	 * @param {String} xsltPath
	 * @param {Boolean} getDOM
	 */
	transformString: function(string_, xsltPath, getDOM){
		var parser = new DOMParser();
		var parsedDOM = parser.parseFromString(string_,"text/xml");

		return this.transformDOM(parsedDOM, xsltPath, getDOM);
	},

	/**
	 * Transforms the given dom via xslt.
	 *
	 * @param {Object} domContent
	 * @param {String} xsltPath
	 * @param {Boolean} getDOM
	 */
	transformDOM: function(domContent, xsltPath, getDOM){
		if (domContent == null) {
			return new String("Parse Error: \nThe given dom content is null.");
		}
		var result;
		var resultString;
		var xsltProcessor = new XSLTProcessor();
		var xslRef = document.implementation.createDocument("", "", null);
		xslRef.async = false;
		xslRef.load(xsltPath);

		xsltProcessor.importStylesheet(xslRef);
		try {
			result = xsltProcessor.transformToDocument(domContent);
		} catch (error){
			return new String("Parse Error: "+error.name + "\n" + error.message);
		}
		if (getDOM){
			return result;
		}
		resultString = (new XMLSerializer()).serializeToString(result);
		return resultString;
	},

	/**
	 * Opens a upload dialog.
	 *
	 */
	openUploadDialog: function(){

		var form = new Ext.form.FormPanel({
			frame : true,
			defaultType : 'textfield',
		 	waitMsgTarget : true,
		  	labelAlign : 'left',
		  	buttonAlign: 'right',
		  	fileUpload : true,
		  	enctype : 'multipart/form-data',
		  	items : [
		  	{
		    	fieldLabel : 'File',
		    	inputType : 'file'
		  	}]
		});

		var submit =form.addButton({
			text:"Submit",
			handler: function()
			{
				form.form.submit({
		      		url:'./epc-upload',
		      		waitMsg: "Importing...",
		      		success: function(f,a){
						dialog.hide();
						var erdf = a.response.responseText.substring(a.response.responseText.indexOf("content:'")+9, a.response.responseText.indexOf("'}"));
		        		erdf = erdf.replace(/</g, "<");
						erdf = erdf.replace(/>/g, ">");
						alert(erdf);
						var parser = new DOMParser();
						var parsedErdf = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?>'+erdf+'',"text/xml");
						alert(parsedErdf);
						// TODO ..
		      		},
					failure: function(f,a){
						dialog.hide();
						Ext.MessageBox.show({
           					title: 'Error',
          	 				msg: a.response.responseText.substring(a.response.responseText.indexOf("content:'")+9, a.response.responseText.indexOf("'}")),
           					buttons: Ext.MessageBox.OK,
           					icon: Ext.MessageBox.ERROR
       					});
		      		}
		  		});
		  	}
		})

		var dialog = new Ext.Window({
			autoCreate: true,
			title: 'Upload File',
			height: 130,
			width: 400,
			modal:true,
			collapsible:false,
			fixedcenter: true,
			shadow:true,
			proxyDrag: true,
			resizable:false,
			items: [new Ext.form.Label({text: "Select an EPML (.epml) file and import it.", style: 'font-size:12px;'}),form]
		});
		dialog.on('hide', function(){
			dialog.destroy(true);
			delete dialog;
		});
		dialog.show();
	},

	/**
	 * Creates a hidden form element to communicate parameter values
	 * to a php file.
	 *
	 * @param {Object} name  The name of the hidden field
	 * @param {Object} value The value of the hidden field
	 */
	createHiddenElement: function(name, value) {
		var newElement = document.createElement("input");
		newElement.name=name;
		newElement.type="hidden";
		newElement.value = value;
		return newElement
	},

	/**
	 * Returns the file name to the given result-entry.
	 *
	 * @param {String} entry.
	 */
	getFileName: function(entry) {
		var l = entry.length;
		if (l > 5){
			if (entry.substr(l-5, 5) == "(AML)"){
				return entry.substr(0, l-6);
			}
		}
		return entry
	},

	/**
	 * Opens a download window for downloading the given content.
	 *
	 * Creates a submit form to communicate the contents to the
	 * download.php file.
	 *
	 * @param {Object} content The content to be downloaded. If it is a zip
	 *                         file, then this should be an array of contents.
	 * @param {Object} zip     True, if it is a zip file, false otherwise
	 */
	openDownloadWindow: function(file, content) {
		var win = window.open("");
		if (win != null) {
			win.document.open();
			win.document.write("");
			var submitForm = win.document.createElement("form");
			win.document.body.appendChild(submitForm);

			var file = this.getFileName(file);
			submitForm.appendChild( this.createHiddenElement("download", content));
			submitForm.appendChild( this.createHiddenElement("file", file));

			submitForm.method = "POST";
			win.document.write("");
			win.document.close();
			submitForm.action= ORYX.PATH + "/download";
			submitForm.submit();
		}
	},

	loadERDF: function(form){

		Ext.Ajax.request({
			method: "POST",
			url: ModelProperties.app.current_model.access.edit_uri,
			params: {
				subject: openid,
				predicate: predicate
			},
			success: function(response, options) {
				if (typeof success == typeof function(){}) {
					var new_access = Ext.util.JSON.decode(response.responseText);
					// TODO add response validation
					ModelProperties.app.current_model.access.access_rights.push(new_access);

					if (typeof success == typeof function(){}) {
						success(response, options)
					}
				}
			},

			failure: function(response, options) {
				if (typeof failure == typeof function(){}) {
					failure(response, options);
				}
			}
		})

	}

});
<commit_msg>committed current state at importing epc - a method that loads the eRDF string is still missing<commit_after>/**
 * Copyright (c) 2008
 * Stefan Krumnow
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

if(!ORYX.Plugins)
	ORYX.Plugins = new Object();

/**
 * Supports EPCs by offering a syntax check and export and import ability..
 *
 *
 */
ORYX.Plugins.EPCSupport = Clazz.extend({

	facade: undefined,

	/**
	 * Offers the plugin functionality:
	 *
	 */
	construct: function(facade) {
		this.facade = facade;

		this.facade.offer({
			'name':"Export EPC",
			'functionality': this.exportEPC.bind(this),
			'group': "epc",
			'icon': ORYX.PATH + "images/epc_export.png",
			'description': "Export diagram to EPML",
			'index': 1,
			'minShape': 0,
			'maxShape': 0});

//		this.facade.offer({
//			'name':"Import EPC",
//			'functionality': this.importEPC.bind(this),
//			'group': "epc",
//			'icon': ORYX.PATH + "images/epc_import.png",
//			'description': "Import an EPML file",
//			'index': 2,
//			'minShape': 0,
//			'maxShape': 0});

//		Syntax Check has been migrated to syntaxchecker.js-Framework

//		this.facade.offer({
//			'name':"Check EPC's Syntax",
//			'functionality': this.checkEPC.bind(this),
//			'group': "epc",
//			'icon': ORYX.PATH + "images/epc_check.png",
//			'description': "Perfom an EPC syntax check",
//			'index': 1,
//			'minShape': 0,
//			'maxShape': 0});
	},

	/**
	 * Imports an AML or EPML description
	 */
	importEPC: function(){
		this.openUploadDialog();
	},

	/**
	 * Exports the diagram into an AML or EPML file
	 */
	exportEPC: function(){

		this.facade.raiseEvent({type:'loading.enable', text:'Exporting model'});
		var xmlSerializer = new XMLSerializer();

		// TODO: a Syntax Syntax-Check should be triggered, here.

		// TODO: get process' name
		var resource = "Oryx-EPC";

		// Force to set all resource IDs
		var serializedDOM = DataManager.serializeDOM( this.facade );

		//add namespaces
		serializedDOM = '<?xml version="1.0" encoding="utf-8"?>' +
		'' +
		'' +
		'<link rel="schema.dc" href="http://purl.org/dc/elements/1.1/" />' +
		'<link rel="schema.dcTerms" href="http://purl.org/dc/terms/ " />' +
		'<link rel="schema.b3mn" href="http://b3mn.org" />' +
		'<link rel="schema.oryx" href="http://oryx-editor.org/" />' +
		'<link rel="schema.raziel" href="http://raziel.org/" />' +
		'<base href="' +
		location.href.split("?")[0] +
		'" />' +
		'' +
		serializedDOM +
		'
' + resource + '' +
		'' + resource + '
' +
		'';

		/*
		 * Transform eRDF -> RDF
		 */
		var erdf2rdfXslt = ORYX.PATH + "/lib/extract-rdf.xsl";

		var rdfResultString;
		rdfResult = this.transformString(serializedDOM, erdf2rdfXslt, true);
		if (rdfResult instanceof String) {
			rdfResultString = rdfResult;
			rdfResult = null;
		} else {
			rdfResultString = xmlSerializer.serializeToString(rdfResult);
			if (!rdfResultString.startsWith("<?xml")) {
				rdfResultString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + rdfResultString;
			}
		}

		/*
		 * Transform RDF -> EPML
		 */
		var rdf2epmlXslt = ORYX.PATH + "/xslt/RDF2EPML.xslt";

		var epmlResult = this.transformDOM(rdfResult, rdf2epmlXslt, true);
		var epmlResultString;
		if (epmlResult instanceof String) {
			epmlResultString = epmlResult;
			epmlResult = null;
		} else {
			epmlResultString = xmlSerializer.serializeToString(epmlResult);
			if (!epmlResultString.startsWith("<?xml")) {
				epmlResultString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + epmlResultString;
			}
		}

		/*
		 * Transform EPML -> AML
		 */

// 		Note: This is uncommented due to the fact, that the epml2amlXslt does not work properly
//
//		var epml2amlXslt = ORYX.PATH +  + "/xslt/EPML2AML_2.xslt";
//
//		var amlResultString = this.transformString(epmlResultString, epml2amlXslt, false);
//		if (amlResultString.substr(0, 12) != "Parse Error:") {
//			amlResultString = '<?xml version="1.0" encoding="utf-8"?>\n' +
//				'<!DOCTYPE AML SYSTEM "ARIS-Export.dtd" [\n	<!ENTITY LocaleId.DEde "1031">\n	<!ENTITY Codepage.DEde "1252">\n]>\n' +
//				amlResultString;
//		}

		/*
		 * Show result
		 */

		this.facade.raiseEvent({type:'loading.disable'});

		// At the moment, only EPML is going to be returned.
		this.openDownloadWindow(resource + ".epml", epmlResultString);
    },

	/**
	 * Transforms the given string via xslt.
	 *
	 * @param {String} string
	 * @param {String} xsltPath
	 * @param {Boolean} getDOM
	 */
	transformString: function(string_, xsltPath, getDOM){
		var parser = new DOMParser();
		var parsedDOM = parser.parseFromString(string_,"text/xml");

		return this.transformDOM(parsedDOM, xsltPath, getDOM);
	},

	/**
	 * Transforms the given dom via xslt.
	 *
	 * @param {Object} domContent
	 * @param {String} xsltPath
	 * @param {Boolean} getDOM
	 */
	transformDOM: function(domContent, xsltPath, getDOM){
		if (domContent == null) {
			return new String("Parse Error: \nThe given dom content is null.");
		}
		var result;
		var resultString;
		var xsltProcessor = new XSLTProcessor();
		var xslRef = document.implementation.createDocument("", "", null);
		xslRef.async = false;
		xslRef.load(xsltPath);

		xsltProcessor.importStylesheet(xslRef);
		try {
			result = xsltProcessor.transformToDocument(domContent);
		} catch (error){
			return new String("Parse Error: "+error.name + "\n" + error.message);
		}
		if (getDOM){
			return result;
		}
		resultString = (new XMLSerializer()).serializeToString(result);
		return resultString;
	},

	/**
	 * Opens a upload dialog.
	 *
	 */
	openUploadDialog: function(){

		var form = new Ext.form.FormPanel({
			frame : true,
			defaultType : 'textfield',
		 	waitMsgTarget : true,
		  	labelAlign : 'left',
		  	buttonAlign: 'right',
		  	fileUpload : true,
		  	enctype : 'multipart/form-data',
		  	items : [
		  	{
		    	fieldLabel : 'File',
		    	inputType : 'file'
		  	}]
		});

		var submit =form.addButton({
			text:"Submit",
			handler: function()
			{
				form.form.submit({
		      		url: ORYX.PATH + '/epc-upload',
		      		waitMsg: "Importing...",
		      		success: function(f,a){
						dialog.hide();
						var erdf = a.response.responseText.substring(a.response.responseText.indexOf("content:'")+9, a.response.responseText.indexOf("'}"));
		        		erdf = erdf.replace(/</g, "<");
						erdf = erdf.replace(/>/g, ">");
						//var parser = new DOMParser();
						//var parsedErdf = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?>'+erdf+'',"text/xml");
						alert(erdf);
						// TODO ..
		      		},
					failure: function(f,a){
						dialog.hide();
						Ext.MessageBox.show({
           					title: 'Error',
          	 				msg: a.response.responseText.substring(a.response.responseText.indexOf("content:'")+9, a.response.responseText.indexOf("'}")),
           					buttons: Ext.MessageBox.OK,
           					icon: Ext.MessageBox.ERROR
       					});
		      		}
		  		});
		  	}
		})

		var dialog = new Ext.Window({
			autoCreate: true,
			title: 'Upload File',
			height: 130,
			width: 400,
			modal:true,
			collapsible:false,
			fixedcenter: true,
			shadow:true,
			proxyDrag: true,
			resizable:false,
			items: [new Ext.form.Label({text: "Select an EPML (.epml) file and import it.", style: 'font-size:12px;'}),form]
		});
		dialog.on('hide', function(){
			dialog.destroy(true);
			delete dialog;
		});
		dialog.show();
	},

	/**
	 * Creates a hidden form element to communicate parameter values
	 * to a php file.
	 *
	 * @param {Object} name  The name of the hidden field
	 * @param {Object} value The value of the hidden field
	 */
	createHiddenElement: function(name, value) {
		var newElement = document.createElement("input");
		newElement.name=name;
		newElement.type="hidden";
		newElement.value = value;
		return newElement
	},

	/**
	 * Returns the file name to the given result-entry.
	 *
	 * @param {String} entry.
	 */
	getFileName: function(entry) {
		var l = entry.length;
		if (l > 5){
			if (entry.substr(l-5, 5) == "(AML)"){
				return entry.substr(0, l-6);
			}
		}
		return entry
	},

	/**
	 * Opens a download window for downloading the given content.
	 *
	 * Creates a submit form to communicate the contents to the
	 * download.php file.
	 *
	 * @param {Object} content The content to be downloaded. If it is a zip
	 *                         file, then this should be an array of contents.
	 * @param {Object} zip     True, if it is a zip file, false otherwise
	 */
	openDownloadWindow: function(file, content) {
		var win = window.open("");
		if (win != null) {
			win.document.open();
			win.document.write("");
			var submitForm = win.document.createElement("form");
			win.document.body.appendChild(submitForm);

			var file = this.getFileName(file);
			submitForm.appendChild( this.createHiddenElement("download", content));
			submitForm.appendChild( this.createHiddenElement("file", file));

			submitForm.method = "POST";
			win.document.write("");
			win.document.close();
			submitForm.action= ORYX.PATH + "/download";
			submitForm.submit();
		}
	},

	loadERDF: function(form){

		Ext.Ajax.request({
			method: "POST",
			url: ModelProperties.app.current_model.access.edit_uri,
			params: {
				subject: openid,
				predicate: predicate
			},
			success: function(response, options) {
				if (typeof success == typeof function(){}) {
					var new_access = Ext.util.JSON.decode(response.responseText);
					// TODO add response validation
					ModelProperties.app.current_model.access.access_rights.push(new_access);

					if (typeof success == typeof function(){}) {
						success(response, options)
					}
				}
			},

			failure: function(response, options) {
				if (typeof failure == typeof function(){}) {
					failure(response, options);
				}
			}
		})

	}

});
<|endoftext|>


<commit_before>(function ($) {

  $(function () {
    window.app.userId = $.cookie('app-user-id');
    var userId = window.app.userId;
    const ajaxSender = require('../common/ajax-promise-helper');
    const sanitizer = require('../common/sanitizer');

    $('.app-login-user-name').text(userId);

    //記事を読み込む
    drawTimeline();

    //記事を投稿する
    $('#app-article-post-btn').click(function () {
      const $textarea = $('#app-article-post-txt');
      let contents = $textarea.val();
      if (!contents) {
        return;
      }
      let param = {
        userId: window.app.userId,
        contents: contents
      };
      ajaxSender.post('/api/article/create', param).then(function (response) {
        $.bootstrapGrowl('書き込みに成功しました', {
          type: 'success'
        });
        console.log(response);
        $textarea.val('');
        drawTimeline();
      }).catch(function (error) {
        console.log(error)
      });

    });

    function drawTimeline() {
      let $timeline = $('#app-timeline');
      ajaxSender.get('/api/article/timeline/' + userId)
        .then((articles)=> {
          console.log(articles);
          $timeline.empty();
          articles.forEach((article)=> {
            var d = new Date(article.postDate);
            //TODO XSS handling
            var dom = `

${sanitizer.sanitize(article.contents)}

posted by ${article.userId}${d.toDateString()}

`;
            $timeline.append($(dom));
          });
        }).catch((error)=> {
        console.log(error);
      });

    }

  });

})(window.jQuery);<commit_msg>sanitizerを使うようにしたのでコメント除去<commit_after>(function ($) {

  $(function () {
    window.app.userId = $.cookie('app-user-id');
    var userId = window.app.userId;
    const ajaxSender = require('../common/ajax-promise-helper');
    const sanitizer = require('../common/sanitizer');

    $('.app-login-user-name').text(userId);

    //記事を読み込む
    drawTimeline();

    //記事を投稿する
    $('#app-article-post-btn').click(function () {
      const $textarea = $('#app-article-post-txt');
      let contents = $textarea.val();
      if (!contents) {
        return;
      }
      let param = {
        userId: window.app.userId,
        contents: contents
      };
      ajaxSender.post('/api/article/create', param).then(function (response) {
        $.bootstrapGrowl('書き込みに成功しました', {
          type: 'success'
        });
        console.log(response);
        $textarea.val('');
        drawTimeline();
      }).catch(function (error) {
        console.log(error)
      });

    });

    function drawTimeline() {
      let $timeline = $('#app-timeline');
      ajaxSender.get('/api/article/timeline/' + userId)
        .then((articles)=> {
          console.log(articles);
          $timeline.empty();
          articles.forEach((article)=> {
            var d = new Date(article.postDate);
            var dom = `

${sanitizer.sanitize(article.contents)}

posted by ${article.userId}${d.toDateString()}

`;
            $timeline.append($(dom));
          });
        }).catch((error)=> {
        console.log(error);
      });

    }

  });

})(window.jQuery);<|endoftext|>


<commit_before>/**
 * The List is an abstract for other list elements
  @extends JazzeeElement
 */
function List(){}
List.prototype = new JazzeeElement();
List.prototype.constructor = List;

/**
 * Add a list manager to the options block
 */
List.prototype.elementProperties = function(){
  var element = this;
  var div = JazzeeElement.prototype.elementProperties.call(this);
  div.append(this.newListItemsButton());
  div.append(this.editListItemButton());
  div.append(this.manageListItemsButton());

  return div;
};

/**
 * Add new list items button
 * @return {jQuery}
 */
List.prototype.newListItemsButton = function(){
  var elementClass = this;
  var obj = new FormObject();
  var field = obj.newField({name: 'legend', value: 'New List Items'});
  var element = field.newElement('Textarea', 'text');
  element.label = 'New Items';
  element.instructions = 'One new item per line';
  var dialog = this.page.displayForm(obj);
  $('form', dialog).bind('submit',function(e){
    var values = $('textarea[name="text"]', this).val().split("\n");
    for(var i = 0;i<values.length; i++){
      elementClass.newListItem(values[i]);
    }
    dialog.dialog("destroy").remove();
    elementClass.workspace();
    return false;
  });//end submit
  var button = $('<button>').html('Add List Items').bind('click',function(){
    $('.qtip').qtip('api').hide();
    dialog.dialog('open');
  }).button({
    icons: {
      primary: 'ui-icon-plus'
    }
  });
  return button;
};

/**
 * Manage List Items button
 * @return {jQuery}
 */
List.prototype.manageListItemsButton = function(){
  var elementClass = this;

  var button = $('<button>').html('Manage Items').bind('click',function(){
    $('.qtip').qtip('api').hide();
    var div = elementClass.page.createDialog();
    var activeList = $('
').addClass('active connectedSortable').addClass('container');
    var inactiveList = $('
').addClass('inactive connectedSortable').addClass('container');
    for(var i = 0; i< elementClass.listItems.length; i++){
      var item = elementClass.listItems[i];
      if(item.isActive){
        activeList.append($('
').html(item.value).data('item', item).addClass('ui-state-default'));
      } else {
        inactiveList.append($('
').html(item.value).data('item', item).addClass('ui-state-default'));
      }
    }
    var activeDiv = $('
').html('
Active Items
').append(activeList).addClass('yui-u first');
    div.append(activeDiv);
    div.append($('
').html('
Inactive Items
').append(inactiveList).addClass('yui-u'));

    $('ul',div).sortable({connectWith: '.connectedSortable'});

    var text = $('').attr('href','#').html(' (sort desc) ').bind('click',function(){
      $('li',activeList).sort(function(a,b){
        return a.innerHTML.toUpperCase() < b.innerHTML.toUpperCase() ? 1 : -1;
      }).appendTo(activeList);
      return false;
    });
    $('h5',activeDiv).append(text);

    var text = $('').attr('href','#').html(' (sort asc) ').bind('click',function(){
      $('li',activeList).sort(function(a,b){
        return a.innerHTML.toUpperCase() > b.innerHTML.toUpperCase() ? 1 : -1;
      }).appendTo(activeList);
      return false;
    });
    $('h5',activeDiv).append(text);

    var button = $('<button>').html('Save').bind('click',function(){
      var orderedItems = [];
      $('ul.active li', div).each(function(i){
        var item = $(this).data('item');
        item.weight = i+1;
        item.isActive = true;
        orderedItems.push(item);
      });

      $('ul.inactive li', div).each(function(i){
        var item = $(this).data('item');
        item.weight = i+100;
        item.isActive = false;
        orderedItems.push(item);
      });

      elementClass.markModified();
      elementClass.listItems = orderedItems;
      div.dialog("destroy").remove();
      elementClass.workspace();
      return false;
    }).button({
      icons: {
        primary: 'ui-icon-disk'
      }
    });
    div.append(button);

    div.dialog('open');
  }).button({
    icons: {
      primary: 'ui-icon-arrow-1-nw'
    }
  });
  return button;
};

/**
 * Edit List Item button
 * @return {jQuery}
 */
List.prototype.editListItemButton = function(){
  var elementClass = this;
  var ul = $('
');
  for(var i = 0; i < this.listItems.length; i++){
    var item = this.listItems[i];
    if(item.isActive){
      var a = $('').attr('href','#').html(item.value).data('item', item).bind('click', function(e){
        $('.qtip').qtip('api').hide();
        var item = $(e.target).data('item');
        var obj = new FormObject();
        var field = obj.newField({name: 'legend', value: 'Edit Item'});
        var element = field.newElement('TextInput', 'value');
        element.label = 'Item Value';
        element.required = true;
        element.value = item.value;
        var element = field.newElement('TextInput', 'name');
        element.label = 'Item Name';
        element.required = false;
        element.format = 'Only letters, numbers and underscore are allowed.';
        element.value = item.name;
        var dialog = elementClass.page.displayForm(obj);
        elementClass.page.pageBuilder.addNameTest($('input[name="name"]', dialog));
        $('form', dialog).bind('submit',function(e){
          item.value = $('input[name="value"]', this).val();
          item.name = $('input[name="name"]', this).val();
          elementClass.workspace();
          dialog.dialog("destroy").remove();
          elementClass.markModified();
          return false;
        });//end submit
        dialog.dialog('open');
        return false;
      });
      ul.append($('
').append(a));
    }
  }
  var button = $('<button>').html('Edit List Item');
  button.button({
    icons: {
      primary: 'ui-icon-pencil',
      secondary: 'ui-icon-carat-1-s'
    }
  });
    button.qtip({
    position: {
      my: 'top-left',
      at: 'bottom-left'
    },
    show: {
      event: 'click'
    },
    hide: {
      event: 'unfocus click mouseleave',
      delay: 500,
      fixed: true
    },
    content: {
      text: ul,
      title: {
        text: 'Choose an item to edit',
        button: true
      }
    }
  });
  return button;
};

/**
 * Add a new New item for the list
 * @param {String} value the items text
 */
List.prototype.newListItem = function(value){
  var itemId = 'new-list-item' + this.page.pageBuilder.getUniqueId();
  var item = {id: itemId, value: value, name: null, isActive: true, weight: this.listItems.length+1};
  this.addListItem(item);
  this.markModified();
  return item;
};

/**
 * Add a new item to the list
 * @param {String} value the items text
 */
List.prototype.addListItem = function(item){
  this.listItems.push(item);
  return item;
};

<commit_msg>Identify empty list items with a -blank- marker string so they can be edited.<commit_after>/**
 * The List is an abstract for other list elements
  @extends JazzeeElement
 */
function List(){}
List.prototype = new JazzeeElement();
List.prototype.constructor = List;

/**
 * Add a list manager to the options block
 */
List.prototype.elementProperties = function(){
  var element = this;
  var div = JazzeeElement.prototype.elementProperties.call(this);
  div.append(this.newListItemsButton());
  div.append(this.editListItemButton());
  div.append(this.manageListItemsButton());

  return div;
};

/**
 * Add new list items button
 * @return {jQuery}
 */
List.prototype.newListItemsButton = function(){
  var elementClass = this;
  var obj = new FormObject();
  var field = obj.newField({name: 'legend', value: 'New List Items'});
  var element = field.newElement('Textarea', 'text');
  element.label = 'New Items';
  element.instructions = 'One new item per line';
  var dialog = this.page.displayForm(obj);
  $('form', dialog).bind('submit',function(e){
    var values = $('textarea[name="text"]', this).val().split("\n");
    for(var i = 0;i<values.length; i++){
      elementClass.newListItem(values[i]);
    }
    dialog.dialog("destroy").remove();
    elementClass.workspace();
    return false;
  });//end submit
  var button = $('<button>').html('Add List Items').bind('click',function(){
    $('.qtip').qtip('api').hide();
    dialog.dialog('open');
  }).button({
    icons: {
      primary: 'ui-icon-plus'
    }
  });
  return button;
};

/**
 * Manage List Items button
 * @return {jQuery}
 */
List.prototype.manageListItemsButton = function(){
  var elementClass = this;

  var button = $('<button>').html('Manage Items').bind('click',function(){
    $('.qtip').qtip('api').hide();
    var div = elementClass.page.createDialog();
    var activeList = $('
').addClass('active connectedSortable').addClass('container');
    var inactiveList = $('
').addClass('inactive connectedSortable').addClass('container');
    for(var i = 0; i< elementClass.listItems.length; i++){
      var item = elementClass.listItems[i];
      var value = ($.trim(item.value).length > 0)?item.value:'[blank]';
      if(item.isActive){
        activeList.append($('
').html(value).data('item', item).addClass('ui-state-default'));
      } else {
        inactiveList.append($('
').html(value).data('item', item).addClass('ui-state-default'));
      }
    }
    var activeDiv = $('
').html('
Active Items
').append(activeList).addClass('yui-u first');
    div.append(activeDiv);
    div.append($('
').html('
Inactive Items
').append(inactiveList).addClass('yui-u'));

    $('ul',div).sortable({connectWith: '.connectedSortable'});

    var text = $('').attr('href','#').html(' (sort desc) ').bind('click',function(){
      $('li',activeList).sort(function(a,b){
        return a.innerHTML.toUpperCase() < b.innerHTML.toUpperCase() ? 1 : -1;
      }).appendTo(activeList);
      return false;
    });
    $('h5',activeDiv).append(text);

    var text = $('').attr('href','#').html(' (sort asc) ').bind('click',function(){
      $('li',activeList).sort(function(a,b){
        return a.innerHTML.toUpperCase() > b.innerHTML.toUpperCase() ? 1 : -1;
      }).appendTo(activeList);
      return false;
    });
    $('h5',activeDiv).append(text);

    var button = $('<button>').html('Save').bind('click',function(){
      var orderedItems = [];
      $('ul.active li', div).each(function(i){
        var item = $(this).data('item');
        item.weight = i+1;
        item.isActive = true;
        orderedItems.push(item);
      });

      $('ul.inactive li', div).each(function(i){
        var item = $(this).data('item');
        item.weight = i+100;
        item.isActive = false;
        orderedItems.push(item);
      });

      elementClass.markModified();
      elementClass.listItems = orderedItems;
      div.dialog("destroy").remove();
      elementClass.workspace();
      return false;
    }).button({
      icons: {
        primary: 'ui-icon-disk'
      }
    });
    div.append(button);

    div.dialog('open');
  }).button({
    icons: {
      primary: 'ui-icon-arrow-1-nw'
    }
  });
  return button;
};

/**
 * Edit List Item button
 * @return {jQuery}
 */
List.prototype.editListItemButton = function(){
  var elementClass = this;
  var ul = $('
');
  for(var i = 0; i < this.listItems.length; i++){
    var item = this.listItems[i];
    if(item.isActive){
      var value = ($.trim(item.value).length > 0)?item.value:'[blank]';
      var a = $('').attr('href','#').html(value).data('item', item).bind('click', function(e){
        $('.qtip').qtip('api').hide();
        var item = $(e.target).data('item');
        var obj = new FormObject();
        var field = obj.newField({name: 'legend', value: 'Edit Item'});
        var element = field.newElement('TextInput', 'value');
        element.label = 'Item Value';
        element.required = true;
        element.value = item.value;
        var element = field.newElement('TextInput', 'name');
        element.label = 'Item Name';
        element.required = false;
        element.format = 'Only letters, numbers and underscore are allowed.';
        element.value = item.name;
        var dialog = elementClass.page.displayForm(obj);
        elementClass.page.pageBuilder.addNameTest($('input[name="name"]', dialog));
        $('form', dialog).bind('submit',function(e){
          item.value = $('input[name="value"]', this).val();
          item.name = $('input[name="name"]', this).val();
          elementClass.workspace();
          dialog.dialog("destroy").remove();
          elementClass.markModified();
          return false;
        });//end submit
        dialog.dialog('open');
        return false;
      });
      ul.append($('
').append(a));
    }
  }
  var button = $('<button>').html('Edit List Item');
  button.button({
    icons: {
      primary: 'ui-icon-pencil',
      secondary: 'ui-icon-carat-1-s'
    }
  });
    button.qtip({
    position: {
      my: 'top-left',
      at: 'bottom-left'
    },
    show: {
      event: 'click'
    },
    hide: {
      event: 'unfocus click mouseleave',
      delay: 500,
      fixed: true
    },
    content: {
      text: ul,
      title: {
        text: 'Choose an item to edit',
        button: true
      }
    }
  });
  return button;
};

/**
 * Add a new New item for the list
 * @param {String} value the items text
 */
List.prototype.newListItem = function(value){
  var itemId = 'new-list-item' + this.page.pageBuilder.getUniqueId();
  var item = {id: itemId, value: value, name: null, isActive: true, weight: this.listItems.length+1};
  this.addListItem(item);
  this.markModified();
  return item;
};

/**
 * Add a new item to the list
 * @param {String} value the items text
 */
List.prototype.addListItem = function(item){
  this.listItems.push(item);
  return item;
};

<|endoftext|>


<commit_before>import * as utils from "./utils.js";
import Circle from "./Circle.js";

import debounce from "lodash-es/debounce";

class HeroAnimation {
  constructor(canvas, container, heroParams) {
    if (typeof canvas.getContext !== "function") {
      console.warn("the thingy bob doesn't support canvas. Bailing out.");
      return;
    }

    this.canvas = canvas;
    this.container = container;
    this.params = heroParams;
    this.resizeCanvas = debounce(this.resizeCanvas, 150);

    this.initHeader();
    this.initAnimation();

    if (!("ontouchstart" in window)) {
      this.container.addEventListener("mousemove", this.mouseMove.bind(this));
      this.container.addEventListener("mouseout", this.mouseOut.bind(this));
      window.addEventListener("resize", this.resizeCanvas.bind(this));
    } else {
      noTouchAnim();
    }

    window.addEventListener("scroll", this.scrollCheck.bind(this));
  }

  initHeader() {
    if (this.container.clientWidth < this.params.gridSize) return;

    this.params.points = [];
    this.params.width = this.container.clientWidth || this.params.width;
    this.params.height = this.container.clientHeight || this.params.height;
    this.canvas.width = this.params.width;
    this.canvas.height = this.params.height;
    this.params.target = {
      x: this.params.width * 2,
      y: this.params.height * 2
    };

    this.params.ctx = this.canvas.getContext("2d");

    const pointsLimiter = utils.calcPointsLimiter(
      this.params.width,
      this.params.height
    );

    for (
      let x = -this.params.gridSize;
      x < this.params.width;
      x = x + this.params.width / pointsLimiter
    ) {
      for (
        let y = 0;
        y < this.params.height;
        y = y + this.params.height / pointsLimiter
      ) {
        const px = utils.getRandomArbitrary(x, x + this.params.gridSize);
        const py = utils.getRandomArbitrary(y, y + this.params.gridSize);

        if (py < this.params.height - this.params.gridSize / 2) {
          const p = {
            x: px,
            originX: px,
            y: py,
            originY: py
          };
          this.params.points.push(p);
        }
      }
    }

    // for each point find the 5 closest points
    this.params.points.map(p1 => {
      let closest = [];
      this.params.points.map(p2 => {
        if (!(p1 == p2)) {
          let placed = false;

          for (let k = 0; k < 5; k++) {
            if (!placed) {
              if (closest[k] == undefined) {
                closest[k] = p2;
                placed = true;
              }
            }
          }

          for (let k = 0; k < 5; k++) {
            if (!placed) {
              if (
                utils.getDistance(p1, p2) < utils.getDistance(p1, closest[k])
              ) {
                closest[k] = p2;
                placed = true;
              }
            }
          }
        }
      });

      p1.closest = closest;
    });

    this.params.points.map(point => {
      point.circle = new Circle(
        point,
        2 + Math.random() * 2.5,
        "94, 161, 184",
        this.params.ctx
      );
    });

    this.initAnimation();
  }

  initAnimation() {
    this.animate();
    this.params.points.map(point => {
      utils.shiftPoint(point);
    });
  }

  scrollCheck() {
    if (this.container.getBoundingClientRect().bottom < 0) {
      this.params.animateHeader = false;
    } else {
      this.params.animateHeader = true;
    }
  }

  mouseOut() {
    this.params.target.x = this.container.clientHeight * 2;
    this.params.target.y = this.container.clientHeight * 2;
  }

  mouseMove(e) {
    let posy = 0;
    let posx = (posy = 0);

    posx = e.pageX;
    posy = e.pageY - this.container.offsetTop;

    this.params.target.x = posx;
    this.params.target.y = posy;
  }

  noTouchAnim() {
    let posy = 0;
    let posx = (posy = 0);

    posx = params.container.clientWidth / 1.5;
    posy = params.container.clientHeight / 1.5;

    this.params.target.x = posx;
    this.params.target.y = posy;
  }

  resizeCanvas() {
    this.initHeader(this.canvas, this.container);
  }

  animate() {
    if (this.params.animateHeader) {
      this.params.ctx.clearRect(0, 0, this.params.width, this.params.height);

      this.params.points.map(point => {
        const distance = Math.abs(utils.getDistance(this.params.target, point));

        if (distance <= this.params.fadeBubble) {
          point.active = 0.3;
          point.circle.active = 0.75;
        } else if (distance <= this.params.fadeBubble * 2) {
          point.active = 0.1;
          point.circle.active = 0.3;
        } else if (distance <= this.params.fadeBubble * 3) {
          point.active = 0.04;
          point.circle.active = 0.1;
        } else {
          point.active = 0.04;
          point.circle.active = 0.04;
        }

        utils.drawLines(point, this.params.ctx);
        point.circle.draw();
      });
    }

    requestAnimationFrame(this.animate.bind(this));
  }
}

export default HeroAnimation;
<commit_msg>fix(homepage): fixes broken hamburger menu<commit_after>import * as utils from "./utils.js";
import Circle from "./Circle.js";

import debounce from "lodash-es/debounce";

class HeroAnimation {
  constructor(canvas, container, heroParams) {
    if (typeof canvas.getContext !== "function") {
      console.warn("the thingy bob doesn't support canvas. Bailing out.");
      return;
    }

    this.canvas = canvas;
    this.container = container;
    this.params = heroParams;
    this.resizeCanvas = debounce(this.resizeCanvas, 150);

    this.initHeader();
    this.initAnimation();

    if (!("ontouchstart" in window)) {
      this.container.addEventListener("mousemove", this.mouseMove.bind(this));
      this.container.addEventListener("mouseout", this.mouseOut.bind(this));
      window.addEventListener("resize", this.resizeCanvas.bind(this));
    } else {
      this.noTouchAnim();
    }

    window.addEventListener("scroll", this.scrollCheck.bind(this));
  }

  initHeader() {
    if (this.container.clientWidth < this.params.gridSize) return;

    this.params.points = [];
    this.params.width = this.container.clientWidth || this.params.width;
    this.params.height = this.container.clientHeight || this.params.height;
    this.canvas.width = this.params.width;
    this.canvas.height = this.params.height;
    this.params.target = {
      x: this.params.width * 2,
      y: this.params.height * 2
    };

    this.params.ctx = this.canvas.getContext("2d");

    const pointsLimiter = utils.calcPointsLimiter(
      this.params.width,
      this.params.height
    );

    for (
      let x = -this.params.gridSize;
      x < this.params.width;
      x = x + this.params.width / pointsLimiter
    ) {
      for (
        let y = 0;
        y < this.params.height;
        y = y + this.params.height / pointsLimiter
      ) {
        const px = utils.getRandomArbitrary(x, x + this.params.gridSize);
        const py = utils.getRandomArbitrary(y, y + this.params.gridSize);

        if (py < this.params.height - this.params.gridSize / 2) {
          const p = {
            x: px,
            originX: px,
            y: py,
            originY: py
          };
          this.params.points.push(p);
        }
      }
    }

    // for each point find the 5 closest points
    this.params.points.map(p1 => {
      let closest = [];
      this.params.points.map(p2 => {
        if (!(p1 == p2)) {
          let placed = false;

          for (let k = 0; k < 5; k++) {
            if (!placed) {
              if (closest[k] == undefined) {
                closest[k] = p2;
                placed = true;
              }
            }
          }

          for (let k = 0; k < 5; k++) {
            if (!placed) {
              if (
                utils.getDistance(p1, p2) < utils.getDistance(p1, closest[k])
              ) {
                closest[k] = p2;
                placed = true;
              }
            }
          }
        }
      });

      p1.closest = closest;
    });

    this.params.points.map(point => {
      point.circle = new Circle(
        point,
        2 + Math.random() * 2.5,
        "94, 161, 184",
        this.params.ctx
      );
    });

    this.initAnimation();
  }

  initAnimation() {
    this.animate();
    this.params.points.map(point => {
      utils.shiftPoint(point);
    });
  }

  scrollCheck() {
    if (this.container.getBoundingClientRect().bottom < 0) {
      this.params.animateHeader = false;
    } else {
      this.params.animateHeader = true;
    }
  }

  mouseOut() {
    this.params.target.x = this.container.clientHeight * 2;
    this.params.target.y = this.container.clientHeight * 2;
  }

  mouseMove(e) {
    let posy = 0;
    let posx = (posy = 0);

    posx = e.pageX;
    posy = e.pageY - this.container.offsetTop;

    this.params.target.x = posx;
    this.params.target.y = posy;
  }

  noTouchAnim() {
    let posy = 0;
    let posx = (posy = 0);

    posx = this.container.clientWidth / 1.5;
    posy = this.container.clientHeight / 1.5;

    this.params.target.x = posx;
    this.params.target.y = posy;
  }

  resizeCanvas() {
    this.initHeader(this.canvas, this.container);
  }

  animate() {
    if (this.params.animateHeader) {
      this.params.ctx.clearRect(0, 0, this.params.width, this.params.height);

      this.params.points.map(point => {
        const distance = Math.abs(utils.getDistance(this.params.target, point));

        if (distance <= this.params.fadeBubble) {
          point.active = 0.3;
          point.circle.active = 0.75;
        } else if (distance <= this.params.fadeBubble * 2) {
          point.active = 0.1;
          point.circle.active = 0.3;
        } else if (distance <= this.params.fadeBubble * 3) {
          point.active = 0.04;
          point.circle.active = 0.1;
        } else {
          point.active = 0.04;
          point.circle.active = 0.04;
        }

        utils.drawLines(point, this.params.ctx);
        point.circle.draw();
      });
    }

    requestAnimationFrame(this.animate.bind(this));
  }
}

export default HeroAnimation;
<|endoftext|>


<commit_before>(function (routeConfig) {

  'use strict';

  routeConfig.init = function (app) {

    // *** routes *** //
    const routes = require('../routes/index');
    const restaurants = require('../routes/restaurants');
    const login = require('../routes/login');
    const signup = require('../routes/signup');
    const cookieSession = require('cookie-session');
    const knex = require('../db/knex')

    // *** register routes *** //
    app.use(cookieSession({
      name: 'session',
      keys: [process.env.SECRET_KEY1, process.env.SECRET_KEY2]
    }));

    app.use(function(req, res, next) {
      req.renderObj = {};
      if (req.session.user) {
        knex('users').where('id', req.session.user.id).then((data) => {
          if (data.length > 0) {
            req.renderObj.user = data[0];
          }else {
            req.renderObj.user = undefined;
          }
        });
        next();
      } else {
        next()
      }
    });

    app.use('/', routes);
    app.use('/restaurants', restaurants);
    app.use('/login', login);
    app.use('/signup', signup);

  };

})(module.exports);
<commit_msg>fixed config<commit_after>(function (routeConfig) {

  'use strict';

  routeConfig.init = function (app) {

    // *** routes *** //
    const routes = require('../routes/index');
    const restaurants = require('../routes/restaurants');
    const login = require('../routes/login');
    const signup = require('../routes/signup');
    const cookieSession = require('cookie-session');
    const knex = require('../db/knex')

    // *** register routes *** //
    app.use(cookieSession({
      name: 'session',
      keys: [process.env.SECRET_KEY1, process.env.SECRET_KEY2]
    }));

    app.use(function(req, res, next) {
      req.renderObj = {};
      if (req.session.user) {
        knex('users').where('id', req.session.user.id).then((data) => {
          if (data.length > 0) {
            req.renderObj.user = data[0];
          }else {
            req.renderObj.user = undefined;
          }
          next();
        });
      } else {
        next()
      }
    });

    app.use('/', routes);
    app.use('/restaurants', restaurants);
    app.use('/login', login);
    app.use('/signup', signup);

  };

})(module.exports);
<|endoftext|>


<commit_before>var debug = require('debug')('wol:leaderboard');

/* interpret packet and structure match object for easier use */
module.exports = function parse(game, match) {
    debug('game: %s, idno: %d processing', game, match.idno);

    /* fail if we're somehow missing players */
    if (!match.players || match.players.length < 1) return;

    /* if we have ra stats normalize packet then carry on  */
    if (game == 'ra' || game == 'am') {
        match = require(global.cwd + '/lib/games/lib/ra').normalize(match);
    }

    match.winners = [];
    match.losers = [];

    match.players.forEach(function(player, i) {
        /* typically Computer */
        if (!player.nam) {
            player.nam = 'computer';
            return;
        }

        /* lowercase all usernames */
        player.nam = player.nam.toLowerCase();

        /* remove spectators */
        if (player.spc && player.spc > 0) {
            delete match.players[i];
            return;
        }

        player.__gains = {};

        /* evaluate completions */
        if (player.cmp) {
            switch (player.cmp) {
                case 2:
                    player.__gains.disconnects = 1;
                    match.losers.push({
                        index: i,
                        name: player.nam,
                        gains: player.__gains,
                    });
                break;

                case 256:
                    player.__gains.wins = 1;
                    match.winners.push({
                        index: i,
                        name: player.nam,
                        gains: player.__gains,
                    });
                break;

                case 512:
                case 528:
                    player.__gains.losses = 1;
                    match.losers.push({
                        index: i,
                        name: player.nam,
                        gains: player.__gains,
                    });
                break;
            }
        }

        /* remove unused info */
        delete player.ipa; /* could be tunnel or p2p (unreliable) */
        delete player.addr; /* same reason but for ra1 */
        delete player.ser; /* serials are not used on CnCNet */
    });

    // delete match.buffer; /* only used for additional parsing */
    // delete match.client; /* ununsed information about the client */

    return match;
};
<commit_msg>cleaning up match obj<commit_after>var debug = require('debug')('wol:leaderboard');

/* interpret packet and structure match object for easier use */
module.exports = function parse(game, match) {
    /* fail if we're somehow missing players */
    if (!match.players || match.players.length < 1) return;

    /* if we have ra stats normalize packet then carry on  */
    if (game == 'ra' || game == 'am') {
        match = require(global.cwd + '/lib/games/lib/ra').normalize(match);
    }

    match.players.forEach(function(player, i) {
        /* typically Computer */
        if (!player.nam) {
            player.nam = 'computer';
            return;
        }

        /* lowercase all usernames */
        player.name = player.nam = player.nam.toLowerCase();

        /* remove spectators */
        if (player.spc && player.spc > 0) {
            delete match.players[i];
            return;
        }

        player.won = 0;
        player.loss = 0;
        player.disconnected = 0;

        /* evaluate completions */
        if (player.cmp) {
            switch (player.cmp) {
                case 2:
                    player.loss = 1;
                    player.disconnected = 1;
                break;

                case 256:
                    player.won = 1;
                break;

                case 512:
                case 528:
                    player.loss = 1;
                break;
            }
        }

        /* remove unused info */
        delete player.ipa; /* could be tunnel or p2p (unreliable) */
        delete player.addr; /* same reason but for ra1 */
        delete player.ser; /* serials are not used on CnCNet */
    });

    // delete match.buffer; /* only used for additional parsing */
    // delete match.client; /* ununsed information about the client */

    return match;
};
<|endoftext|>


<commit_before>// Axis
// ---- x
// |
// | y

// Setup the scene
let setupStage = () => {
    stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight,
    });

    layer = new Konva.Layer();

    legendLayer = new Konva.Layer();

    hgGroup = new Konva.Group({
        draggable: true,
        dragBoundFunc: pos => {
            let yPos = pos.y > 0 ? 0 : pos.y;

            yPos = yPos < -hgBack.getHeight() + window.innerHeight ? -hgBack.getHeight() + window.innerHeight : yPos;

            return {
                x: 0,
                y: yPos,
            };
        },
    });

    hgBack = new Konva.Rect({
        x: 0,
        y: 0,
        width: window.innerWidth - 100,
        height: window.innerHeight,
    });

    blockGroup = new Konva.Group({
        draggable: true,
        dragBoundFunc: pos => {
            let yPos = pos.y > 0 ? 0 : pos.y;

            yPos = yPos < -blockBack.getHeight() + window.innerHeight ? -blockBack.getHeight() + window.innerHeight : yPos;

            return {
                x: 0,
                y: yPos,
            };
        },
    });

    blockBack = new Konva.Rect({
        x: window.innerWidth - 100,
        y: 0,
        width: 100,
        height: window.innerHeight,
    });

    hgGroup.add(hgBack);

    blockGroup.add(blockBack);

    layer.add(hgGroup);
    layer.add(blockGroup);

    stage.add(layer);
    stage.add(legendLayer);
};

// Return the color of the event
let getEventColor = event => {
    let color = '#555555';

    if (event.Famous) {
        color = '#00ffff';
    } else if (event.Witness) {
        color = '#5555ff';
    } else if (event.Consensus) {
        color = '#00ff00';
    } else if (event.Body.Index === -1) {
        color = '#ff0000';
    }

    return color;
};

// Draw the event, the associated index text
// and set the borderLine (stroke) if it contains a Tx
let drawEvent = event => {
    // The event circle
    event.circle = new Konva.Circle({
        x: event.x,
        y: event.y,
        radius: 10,
        fill: getEventColor(event),
    });

    // The event index
    event.text = new Konva.Text({
        x: event.x - 5,
        y: event.y - 5,
        text: event.Body.Index === -1 ? '' : '' + event.Body.Index,
        fontSize: 12,
        fontFamily: 'Calibri',
        fill: 'black',
    });

    // If its root, draw the NodeId text
    if (event.Body.Index === -1) {
        let nodeId = new Konva.Text({
            x: event.x - xInterval / 2,
            y: 50,
            text: event.EventId.replace('Root', ''),
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'black',
        });

        hgGroup.add(nodeId);
    }

    // Set the border line if it contains a transaction
    if (event.Body.Transactions.length) {
        event.circle.setStroke('#000000');
        event.circle.setStrokeWidth(3);
    }

    hgGroup.add(event.circle);
    hgGroup.add(event.text);

    hgGroup.setY(_.min([0, hgGroup.getY(), -event.y + window.innerHeight - 100]));
};

// Draw the links between an event and its parents
let drawEventLinks = event => {
    _.each(event.ParentEvents, parentEvent => {
        let arrow = new Konva.Arrow({
            points: [
                parentEvent.x,
                parentEvent.y,
                event.x,
                event.y,
            ],
            pointerLength: 5,
            pointerWidth: 5,
            fill: 'black',
            stroke: 'black',
            strokeWidth: 1,
        });

        hgGroup.add(arrow);

        arrow.moveToBottom();
    });
};

// Draw the round separators
let drawRoundLines = rounds => {
    // Dirty tmp fix for events that are in the first and second round
    if (rounds.length >= 2) {
        rounds[1].Events = _.fromPairs(_.differenceBy(_.toPairs(rounds[1].Events), _.toPairs(rounds[0].Events), ([rId, round]) => rId));
    }

    _(rounds)
        .each((round, rId) => {
            // Dont draw existing round
            if (rId <= actualRound) {
                return;
            }

            let roundEvents = [];

            _.forIn(round.Events, (event, reId) => {
                roundEvents.push(_.find(events, ([eId, e]) => eId === reId))
            });

            let [eId, ev] = _.minBy(roundEvents, ([eId, ev]) => ev.y);

            let line = new Konva.Line({
                points: [
                    0,
                    ev.y - yInterval / 2,
                    (_.keys(participants).length + 1) * xInterval,
                    ev.y - yInterval / 2,
                ],
                stroke: 'white',
                strokeWidth: 2,
            });

            let txt = new Konva.Text({
                x: (_.keys(participants).length + 1) * xInterval,
                y: ev.y - yInterval / 2 - 6,
                text: '' + rId,
                fontSize: 12,
                fontFamily: 'Calibri',
                fill: 'black',
            });

            hgGroup.add(line);
            hgGroup.add(txt);
        });

    actualRound = rounds.length - 1;
};

let drawBlocks = blocks => {
    _.each(blocks, (block, bId) => {
        if (bId <= actualBlock) {
            return
        }

        let b = new Konva.Rect({
            x: window.innerWidth - 80,
            y: 20 + yInterval + (yInterval * bId),
            height: 20,
            width: 60,
            fill: '#999999',
            stroke: '#000000',
            strokeWidth: 1,
        });

        let txt = new Konva.Text({
            x: window.innerWidth - 60,
            y: 20 + yInterval + (yInterval * bId) + 5,
            text: '' + bId + ' (' + block.Body.Transactions.length + ')',
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'black',
        });

        blockGroup.add(b, txt);

        blockGroup.setY(_.min([0, blockGroup.getY(), -(40 + yInterval + (yInterval * bId) + 5) + window.innerHeight]));
    })

    actualBlock = blocks.length - 1;

    blockBack.setHeight((50 + yInterval + (yInterval * actualBlock + 1)));
};

// Main draw function
let draw = (evs, rounds, blocks) => {
    _.each(evs, ([eId, event]) => {
        drawEvent(event);

        if (event.ParentEvents.length === 0) {
            return;
        }

        drawEventLinks(event);
    });

    drawRoundLines(rounds);

    drawBlocks(blocks)

    layer.draw();

    let maxY = _.maxBy(events, ([eId, event]) => event.y)[1].y;

    hgBack.setHeight(100 + maxY);
};

// Draw the legend
let drawLegend = () => {
    let legends = [
        {
            name: 'Root',
            color: getEventColor({ Body: { Index: -1 } }),
        },
        {
            name: 'Consensus',
            color: getEventColor({ Consensus: true }),
        },
        {
            name: 'Famous',
            color: getEventColor({ Famous: true }),
        },
        {
            name: 'Witness',
            color: getEventColor({ Witness: true }),
        },
        {
            name: 'Normal',
            color: getEventColor({ Body: {} }),
        },
        {
            name: 'Transaction',
            color: '#999999',
        },
    ];

    _.each(legends, (legend, i) => {
        let circle = new Konva.Circle({
            x: 15 + (i * 100),
            y: 20,
            radius: 10,
            fill: legend.color,
        });

        if (legend.name === 'Transaction') {
            circle.setStroke('black');
            circle.setStrokeWidth(3);
        }

        let text = new Konva.Text({
            x: 30 + (i * 100),
            y: 15,
            text: legend.name,
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'black',
        });

        legendLayer.add(circle, text);
    });

    let background = new Konva.Rect({
        x: 0,
        y: 0,
        height: 40,
        width: window.innerWidth,
        fill: '#999999',
        stroke: '#000000',
        strokeWidth: 1,
    });

    legendLayer.add(background);
    background.moveToBottom();

    legendLayer.draw();

};
<commit_msg>Better graph text contrast<commit_after>// Axis
// ---- x
// |
// | y

// Setup the scene
let setupStage = () => {
    stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight,
    });

    layer = new Konva.Layer();

    legendLayer = new Konva.Layer();

    hgGroup = new Konva.Group({
        draggable: true,
        dragBoundFunc: pos => {
            let yPos = pos.y > 0 ? 0 : pos.y;

            yPos = yPos < -hgBack.getHeight() + window.innerHeight ? -hgBack.getHeight() + window.innerHeight : yPos;

            return {
                x: 0,
                y: yPos,
            };
        },
    });

    hgBack = new Konva.Rect({
        x: 0,
        y: 0,
        width: window.innerWidth - 100,
        height: window.innerHeight,
    });

    blockGroup = new Konva.Group({
        draggable: true,
        dragBoundFunc: pos => {
            let yPos = pos.y > 0 ? 0 : pos.y;

            yPos = yPos < -blockBack.getHeight() + window.innerHeight ? -blockBack.getHeight() + window.innerHeight : yPos;

            return {
                x: 0,
                y: yPos,
            };
        },
    });

    blockBack = new Konva.Rect({
        x: window.innerWidth - 100,
        y: 0,
        width: 100,
        height: window.innerHeight,
    });

    hgGroup.add(hgBack);

    blockGroup.add(blockBack);

    layer.add(hgGroup);
    layer.add(blockGroup);

    stage.add(layer);
    stage.add(legendLayer);
};

// Return the color of the event
let getEventColor = event => {
    let color = '#555555';

    if (event.Famous) {
        color = '#00ffff';
    } else if (event.Witness) {
        color = '#5555ff';
    } else if (event.Consensus) {
        color = '#00ff00';
    } else if (event.Body.Index === -1) {
        color = '#ff0000';
    }

    return color;
};

// Draw the event, the associated index text
// and set the borderLine (stroke) if it contains a Tx
let drawEvent = event => {
    // The event circle
    event.circle = new Konva.Circle({
        x: event.x,
        y: event.y,
        radius: 10,
        fill: getEventColor(event),
    });

    // The event index
    event.text = new Konva.Text({
        x: event.x + 15,
        y: event.y - 5,
        text: event.Body.Index === -1 ? '' : '' + event.Body.Index,
        fontSize: 12,
        fontFamily: 'Calibri',
        fill: 'white',
    });

    // If its root, draw the NodeId text
    if (event.Body.Index === -1) {
        let nodeId = new Konva.Text({
            x: event.x - xInterval / 2,
            y: 50,
            text: event.EventId.replace('Root', ''),
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'white',
        });

        hgGroup.add(nodeId);
    }

    // Set the border line if it contains a transaction
    if (event.Body.Transactions.length) {
        event.circle.setStroke('#000000');
        event.circle.setStrokeWidth(3);
    }

    hgGroup.add(event.circle);
    hgGroup.add(event.text);

    hgGroup.setY(_.min([0, hgGroup.getY(), -event.y + window.innerHeight - 100]));
};

// Draw the links between an event and its parents
let drawEventLinks = event => {
    _.each(event.ParentEvents, parentEvent => {
        let arrow = new Konva.Arrow({
            points: [
                parentEvent.x,
                parentEvent.y,
                event.x,
                event.y,
            ],
            pointerLength: 5,
            pointerWidth: 5,
            fill: 'black',
            stroke: 'black',
            strokeWidth: 1,
        });

        hgGroup.add(arrow);

        arrow.moveToBottom();
    });
};

// Draw the round separators
let drawRoundLines = rounds => {
    // Dirty tmp fix for events that are in the first and second round
    if (rounds.length >= 2) {
        rounds[1].Events = _.fromPairs(_.differenceBy(_.toPairs(rounds[1].Events), _.toPairs(rounds[0].Events), ([rId, round]) => rId));
    }

    _(rounds)
        .each((round, rId) => {
            // Dont draw existing round
            if (rId <= actualRound) {
                return;
            }

            let roundEvents = [];

            _.forIn(round.Events, (event, reId) => {
                roundEvents.push(_.find(events, ([eId, e]) => eId === reId))
            });

            let [eId, ev] = _.minBy(roundEvents, ([eId, ev]) => ev.y);

            let line = new Konva.Line({
                points: [
                    0,
                    ev.y - yInterval / 2,
                    (_.keys(participants).length + 1) * xInterval,
                    ev.y - yInterval / 2,
                ],
                stroke: 'white',
                strokeWidth: 2,
            });

            let txt = new Konva.Text({
                x: 5 + (_.keys(participants).length + 1) * xInterval,
                y: ev.y - yInterval / 2 - 6,
                text: '' + rId,
                fontSize: 12,
                fontFamily: 'Calibri',
                fill: 'white',
            });

            hgGroup.add(line);
            hgGroup.add(txt);
        });

    actualRound = rounds.length - 1;
};

let drawBlocks = blocks => {
    _.each(blocks, (block, bId) => {
        if (bId <= actualBlock) {
            return
        }

        let b = new Konva.Rect({
            x: window.innerWidth - 80,
            y: 20 + yInterval + (yInterval * bId),
            height: 20,
            width: 60,
            fill: '#999999',
            stroke: '#000000',
            strokeWidth: 1,
        });

        let txt = new Konva.Text({
            x: window.innerWidth - 60,
            y: 20 + yInterval + (yInterval * bId) + 5,
            text: '' + bId + ' (' + block.Body.Transactions.length + ')',
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'black',
        });

        blockGroup.add(b, txt);

        blockGroup.setY(_.min([0, blockGroup.getY(), -(40 + yInterval + (yInterval * bId) + 5) + window.innerHeight]));
    })

    actualBlock = blocks.length - 1;

    blockBack.setHeight((50 + yInterval + (yInterval * actualBlock + 1)));
};

// Main draw function
let draw = (evs, rounds, blocks) => {
    _.each(evs, ([eId, event]) => {
        drawEvent(event);

        if (event.ParentEvents.length === 0) {
            return;
        }

        drawEventLinks(event);
    });

    drawRoundLines(rounds);

    drawBlocks(blocks)

    layer.draw();

    let maxY = _.maxBy(events, ([eId, event]) => event.y)[1].y;

    hgBack.setHeight(100 + maxY);
};

// Draw the legend
let drawLegend = () => {
    let legends = [
        {
            name: 'Root',
            color: getEventColor({ Body: { Index: -1 } }),
        },
        {
            name: 'Consensus',
            color: getEventColor({ Consensus: true }),
        },
        {
            name: 'Famous',
            color: getEventColor({ Famous: true }),
        },
        {
            name: 'Witness',
            color: getEventColor({ Witness: true }),
        },
        {
            name: 'Normal',
            color: getEventColor({ Body: {} }),
        },
        {
            name: 'Transaction',
            color: '#999999',
        },
    ];

    _.each(legends, (legend, i) => {
        let circle = new Konva.Circle({
            x: 15 + (i * 100),
            y: 20,
            radius: 10,
            fill: legend.color,
        });

        if (legend.name === 'Transaction') {
            circle.setStroke('black');
            circle.setStrokeWidth(3);
        }

        let text = new Konva.Text({
            x: 30 + (i * 100),
            y: 15,
            text: legend.name,
            fontSize: 12,
            fontFamily: 'Calibri',
            fill: 'black',
        });

        legendLayer.add(circle, text);
    });

    let background = new Konva.Rect({
        x: 0,
        y: 0,
        height: 40,
        width: window.innerWidth,
        fill: '#999999',
        stroke: '#000000',
        strokeWidth: 1,
    });

    legendLayer.add(background);
    background.moveToBottom();

    legendLayer.draw();

};
<|endoftext|>


<commit_before>const Polyglot = require('node-polyglot');
const Locale = require('locale/index');

const ACTIVE_LOCALE = window.ACTIVE_LOCALE || 'en';
const polyglot = new Polyglot({
  locale: ACTIVE_LOCALE, // Needed for pluralize behaviour
  phrases: Locale[ACTIVE_LOCALE]
});
window._t = polyglot.t.bind(polyglot);

const $ = require('jquery');
const _ = require('underscore');
const UserModel = require('dashboard/data/user-model');
const OrganizationModel = require('dashboard/data/organization-model');
const ConfigModel = require('dashboard/data/config-model');
const DashboardHeaderView = require('dashboard/components/dashboard-header-view');
const SupportView = require('dashboard/components/support-view');
const HeaderViewModel = require('./views/organization/header-view-model');
const LocalStorage = require('dashboard/helpers/local-storage');
// const AvatarSelector = require('dashboard/components/avatar-selector/avatar-selector-view');
const FlashMessageModel = require('dashboard/data/flash-message-model');
const FlashMessageView = require('dashboard/components/flash-message/flash-message-view');
const TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
const OrganizationUsersView = require('dashboard/views/organization/organization-users/organization-users-view');
const IconPickerView = require('./icon-picker/organization-icon-picker-view');

// var OrganizationUserForm = require('./organization_user_form');
// var OrganizationUserQuota = require('./organization_user_quota');
// var DeleteOrganizationUser = require('./delete_org_user_view');
// var DeleteOrganization = require('../common/delete_organization_view');
// var ColorPickerView = require('./color_picker_view');
// var RegenerateKeysDialog = require('../keys/regenerate_keys_dialog_view');
// var GroupsRouter = require('./groups_admin/router');
// var GroupsMainView = require('./groups_admin/groups_main_view');
// var OrganizationNotificationView = require('./organization_notification/organization_notification_view');

const DOMAIN_REGEXP = /^[a-zA-Z0-9*][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$/;

const configModel = new ConfigModel(
  _.defaults(
    {
      base_url: window.user_data.base_url
    },
    window.config
  )
);

if (window.trackJs) {
  window.trackJs.configure({
    userId: window.user_data.username
  });
}

/**
 *  Entry point for the new organization, bootstraps all
 *  dependency models and application.
 */

$(function () {
  var organization_user_data = window.organization_user_data;
  var organization_data = window.organization_data;

  const currentUser = new UserModel(window.user_data, { configModel });
  var organizationUser;
  var organization;
  var organizationUsers;

  if (organization_user_data) {
    organizationUser = new UserModel(organization_user_data, { configModel });
  }

  if (organization_data) {
    organization = new OrganizationModel(organization_data, { configModel });
    organizationUsers = organization.users;
  }

  const headerView = new DashboardHeaderView({
    el: $('#header'), // pre-rendered in DOM by Rails app
    model: currentUser,
    currentUserUrl: currentUser.viewUrl(),
    viewModel: new HeaderViewModel(),
    localStorage: new LocalStorage(),
    configModel
  });
  headerView.render();

  var flashMessageModel = new FlashMessageModel();
  var flashMessageView = new FlashMessageView({
    model: flashMessageModel
  });
  flashMessageView.render();
  flashMessageView.$el.insertAfter(headerView.$el);

  var supportView = new SupportView({
    el: $('#support-banner'),
    userModel: currentUser
  });
  supportView.render();

  // Avatar
  // TODO: This is in the profile view
  // if (this.$('.js-avatarSelector').length > 0) {
  //   var avatarSelector = new AvatarSelector({
  //     el: this.$('.js-avatarSelector'),
  //     renderModel: new cdb.core.Model({
  //       inputName: this.$('.js-fileAvatar').attr('name'),
  //       name: currentUser.organization.get('name'),
  //       avatar_url: currentUser.organization.get('avatar_url'),
  //       id: currentUser.get('id')
  //     }),
  //     avatarAcceptedExtensions: window.avatar_valid_extensions
  //   });

  //   avatarSelector.render();
  // }

  // Tooltips
  $('[data-title]').each(function (i, el) {
    new TipsyTooltipView({ // eslint-disable-line
      el: el,
      title: function () {
        return $(this).attr('data-title');
      }
    });
  });

  // Color picker
  // if (this.$('.js-colorPicker').length > 0) {
  //   new ColorPickerView({
  //     el: this.$('.js-colorPicker'),
  //     color: this.$('.js-colorPicker').data('color')
  //   }).bind('colorChosen', function (color) {
  //     this.$('.js-colorInput').val(color);
  //   }, this);
  // }

  // Icon picker
  if (this.$('.js-iconPicker').length > 0) {
    this.icon_picker_view = new IconPickerView({
      el: this.$('.js-iconPicker'),
      orgId: currentUser.organization.get('id')
    });
  }

  // Domain whitelisting
  if ($('.js-domains').length > 0) {
    $('.js-domainsList').tagit({
      allowSpaces: false,
      singleField: true,
      singleFieldNode: this.$('.js-whitelist'),
      fieldName: this.$('.js-whitelist').attr('name'),
      tagLimit: 10,
      readOnly: false,
      onBlur: function () {
        self.$('.js-domains').removeClass('is-focus');

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else {
          $('.js-placeholder').show();
        }

        if ($('.tagit-new').length > 0) {
          $('.tagit-new input').val('');
        }
      },
      onFocus: function () {
        self.$('.js-domains').addClass('is-focus');

        $('.js-placeholder').hide();
      },
      beforeTagAdded: function (ev, ui) {
        if (!DOMAIN_REGEXP.test(ui.tagLabel)) {
          return false;
        }

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      },
      afterTagAdded: function (ev, ui) {
        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      }
    });
  }

  // Organization user form
  // if (organizationUser) {
  //   this.organization_user_form = new OrganizationUserForm({
  //     el: this.$('.js-organizationUserForm'),
  //     model: organizationUser
  //   });
  // }

  // User quota main view
  // if (organizationUser) {
  //   this.organization_user_quota = new OrganizationUserQuota({
  //     el: this.$('.js-userQuota'),
  //     model: organizationUser
  //   });
  // }

  // Organization users list
  // if ($('.js-orgUsersList').length === 1) {
  //   this.organizationUsersView = new OrganizationUsersView({
  //     el: this.$('.js-orgUsersList'),
  //     organization: organization,
  //     organizationUsers: organizationUsers,
  //     currentUser: currentUser
  //   });

  //   this.organizationUsersView.render();
  // }

  // User deletion
  // if (this.$('.js-deleteAccount').length > 0 && window.authenticity_token) {
  //   this.$('.js-deleteAccount').click(function (ev) {
  //     if (ev) {
  //       ev.preventDefault();
  //     }
  //     new DeleteOrganizationUser({
  //       organizationUser: organizationUser,
  //       authenticityToken: window.authenticity_token,
  //       clean_on_hide: false
  //     }).appendToBody();
  //   });
  // }

  // Organization deletion
  // if (this.$('.js-deleteOrganization').length > 0 && window.authenticity_token) {
  //   this.$('.js-deleteOrganization').click(function (ev) {
  //     if (ev) {
  //       ev.preventDefault();
  //     }
  //     new DeleteOrganization({
  //       authenticityToken: window.authenticity_token,
  //       clean_on_hide: true,
  //       user: currentUser
  //     }).appendToBody();
  //   });
  // }

  // Notifications
  // if (this.$('.js-OrganizationNotification').length > 0) {
  //   var authenticityToken = $('[name=authenticity_token][value]').get(0).value;

  //   this.organization_notification_view = new OrganizationNotificationView({
  //     el: this.$('.js-OrganizationNotification'),
  //     authenticityToken: authenticityToken
  //   });
  //   this.organization_notification_view.render();
  // }

  // API keys
  // var regenerateApiKeyHandler = function (ev, scope, form_action) {
  //   if (ev) ev.preventDefault();
  //   var authenticity_token = $('[name=authenticity_token][value]').get(0).value;
  //   var dlg = new RegenerateKeysDialog({
  //     type: 'api',
  //     scope: scope,
  //     form_action: form_action,
  //     authenticity_token: authenticity_token
  //   });

  //   dlg.appendToBody();
  // };

  var toggleUserQuotas = function () {
    var viewer = $('.js-userViewerOption:checked').val();
    if (viewer === 'true') {
      $('.user-quotas').hide();
      $('.js-org-admin-row').hide();
      $('#org_admin').prop('checked', false);
    } else {
      $('.user-quotas').show();
      $('.js-org-admin-row').show();
    }
  };

  toggleUserQuotas();

  $('.js-userViewerOption').bind('change', function (ev) {
    toggleUserQuotas();
  });

  $('.js-regenerateOrgUsersApiKey').bind('click', function (ev) {
    var current_username = $(this).attr('data-current_username');

    // regenerateApiKeyHandler(ev, 'organization', '/u/' + current_username + '/organization/regenerate_api_keys');
  });

  $('.js-regenerateOrgUserApiKey').bind('click', function (ev) {
    var username = $(this).attr('data-username');
    var current_username = $(this).attr('data-current_username');

    // regenerateApiKeyHandler(ev, 'organization_user', '/u/' + current_username + '/organization/users/' + username + '/regenerate_api_key');
  });

  var $groups = $('.js-groups-content');
  // if ($groups) {
  //   if (!currentUser.isOrgAdmin()) {
  //     window.location = currentUser.viewUrl().accountProfile();
  //     return false;
  //   }

  //   var groups = new cdb.admin.OrganizationGroups([], {
  //     organization: currentUser.organization
  //   });
  //   var router = new GroupsRouter({
  //     rootUrl: currentUser.viewUrl().organization().groups(),
  //     flashMessageModel: flashMessageModel,
  //     groups: groups,
  //     user: currentUser
  //   });

  //   var groupsMainView = new GroupsMainView({
  //     el: $groups,
  //     groups: groups,
  //     router: router,
  //     user: currentUser
  //   });
  //   groupsMainView.render();
  //   window.groups = groupsMainView;

  //   router.enableAfterMainView();
  // }
});
<commit_msg>Remove unused color picker<commit_after>const Polyglot = require('node-polyglot');
const Locale = require('locale/index');

const ACTIVE_LOCALE = window.ACTIVE_LOCALE || 'en';
const polyglot = new Polyglot({
  locale: ACTIVE_LOCALE, // Needed for pluralize behaviour
  phrases: Locale[ACTIVE_LOCALE]
});
window._t = polyglot.t.bind(polyglot);

const $ = require('jquery');
const _ = require('underscore');
const UserModel = require('dashboard/data/user-model');
const OrganizationModel = require('dashboard/data/organization-model');
const ConfigModel = require('dashboard/data/config-model');
const DashboardHeaderView = require('dashboard/components/dashboard-header-view');
const SupportView = require('dashboard/components/support-view');
const HeaderViewModel = require('./views/organization/header-view-model');
const LocalStorage = require('dashboard/helpers/local-storage');
// const AvatarSelector = require('dashboard/components/avatar-selector/avatar-selector-view');
const FlashMessageModel = require('dashboard/data/flash-message-model');
const FlashMessageView = require('dashboard/components/flash-message/flash-message-view');
const TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
const OrganizationUsersView = require('dashboard/views/organization/organization-users/organization-users-view');
const IconPickerView = require('./icon-picker/organization-icon-picker-view');

// var OrganizationUserForm = require('./organization_user_form');
// var OrganizationUserQuota = require('./organization_user_quota');
// var DeleteOrganizationUser = require('./delete_org_user_view');
// var DeleteOrganization = require('../common/delete_organization_view');
// var ColorPickerView = require('./color_picker_view');
// var RegenerateKeysDialog = require('../keys/regenerate_keys_dialog_view');
// var GroupsRouter = require('./groups_admin/router');
// var GroupsMainView = require('./groups_admin/groups_main_view');
// var OrganizationNotificationView = require('./organization_notification/organization_notification_view');

const DOMAIN_REGEXP = /^[a-zA-Z0-9*][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$/;

const configModel = new ConfigModel(
  _.defaults(
    {
      base_url: window.user_data.base_url
    },
    window.config
  )
);

if (window.trackJs) {
  window.trackJs.configure({
    userId: window.user_data.username
  });
}

/**
 *  Entry point for the new organization, bootstraps all
 *  dependency models and application.
 */

$(function () {
  var organization_user_data = window.organization_user_data;
  var organization_data = window.organization_data;

  const currentUser = new UserModel(window.user_data, { configModel });
  var organizationUser;
  var organization;
  var organizationUsers;

  if (organization_user_data) {
    organizationUser = new UserModel(organization_user_data, { configModel });
  }

  if (organization_data) {
    organization = new OrganizationModel(organization_data, { configModel });
    organizationUsers = organization.users;
  }

  const headerView = new DashboardHeaderView({
    el: $('#header'), // pre-rendered in DOM by Rails app
    model: currentUser,
    currentUserUrl: currentUser.viewUrl(),
    viewModel: new HeaderViewModel(),
    localStorage: new LocalStorage(),
    configModel
  });
  headerView.render();

  var flashMessageModel = new FlashMessageModel();
  var flashMessageView = new FlashMessageView({
    model: flashMessageModel
  });
  flashMessageView.render();
  flashMessageView.$el.insertAfter(headerView.$el);

  var supportView = new SupportView({
    el: $('#support-banner'),
    userModel: currentUser
  });
  supportView.render();

  // Avatar
  // TODO: This is in the profile view
  // if (this.$('.js-avatarSelector').length > 0) {
  //   var avatarSelector = new AvatarSelector({
  //     el: this.$('.js-avatarSelector'),
  //     renderModel: new cdb.core.Model({
  //       inputName: this.$('.js-fileAvatar').attr('name'),
  //       name: currentUser.organization.get('name'),
  //       avatar_url: currentUser.organization.get('avatar_url'),
  //       id: currentUser.get('id')
  //     }),
  //     avatarAcceptedExtensions: window.avatar_valid_extensions
  //   });

  //   avatarSelector.render();
  // }

  // Tooltips
  $('[data-title]').each(function (i, el) {
    new TipsyTooltipView({ // eslint-disable-line
      el: el,
      title: function () {
        return $(this).attr('data-title');
      }
    });
  });

  // Icon picker
  if (this.$('.js-iconPicker').length > 0) {
    this.icon_picker_view = new IconPickerView({
      el: this.$('.js-iconPicker'),
      orgId: currentUser.organization.get('id')
    });
  }

  // Domain whitelisting
  if ($('.js-domains').length > 0) {
    $('.js-domainsList').tagit({
      allowSpaces: false,
      singleField: true,
      singleFieldNode: this.$('.js-whitelist'),
      fieldName: this.$('.js-whitelist').attr('name'),
      tagLimit: 10,
      readOnly: false,
      onBlur: function () {
        self.$('.js-domains').removeClass('is-focus');

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else {
          $('.js-placeholder').show();
        }

        if ($('.tagit-new').length > 0) {
          $('.tagit-new input').val('');
        }
      },
      onFocus: function () {
        self.$('.js-domains').addClass('is-focus');

        $('.js-placeholder').hide();
      },
      beforeTagAdded: function (ev, ui) {
        if (!DOMAIN_REGEXP.test(ui.tagLabel)) {
          return false;
        }

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      },
      afterTagAdded: function (ev, ui) {
        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      }
    });
  }

  // Organization user form
  // if (organizationUser) {
  //   this.organization_user_form = new OrganizationUserForm({
  //     el: this.$('.js-organizationUserForm'),
  //     model: organizationUser
  //   });
  // }

  // User quota main view
  // if (organizationUser) {
  //   this.organization_user_quota = new OrganizationUserQuota({
  //     el: this.$('.js-userQuota'),
  //     model: organizationUser
  //   });
  // }

  // Organization users list
  // if ($('.js-orgUsersList').length === 1) {
  //   this.organizationUsersView = new OrganizationUsersView({
  //     el: this.$('.js-orgUsersList'),
  //     organization: organization,
  //     organizationUsers: organizationUsers,
  //     currentUser: currentUser
  //   });

  //   this.organizationUsersView.render();
  // }

  // User deletion
  // if (this.$('.js-deleteAccount').length > 0 && window.authenticity_token) {
  //   this.$('.js-deleteAccount').click(function (ev) {
  //     if (ev) {
  //       ev.preventDefault();
  //     }
  //     new DeleteOrganizationUser({
  //       organizationUser: organizationUser,
  //       authenticityToken: window.authenticity_token,
  //       clean_on_hide: false
  //     }).appendToBody();
  //   });
  // }

  // Organization deletion
  // if (this.$('.js-deleteOrganization').length > 0 && window.authenticity_token) {
  //   this.$('.js-deleteOrganization').click(function (ev) {
  //     if (ev) {
  //       ev.preventDefault();
  //     }
  //     new DeleteOrganization({
  //       authenticityToken: window.authenticity_token,
  //       clean_on_hide: true,
  //       user: currentUser
  //     }).appendToBody();
  //   });
  // }

  // Notifications
  // if (this.$('.js-OrganizationNotification').length > 0) {
  //   var authenticityToken = $('[name=authenticity_token][value]').get(0).value;

  //   this.organization_notification_view = new OrganizationNotificationView({
  //     el: this.$('.js-OrganizationNotification'),
  //     authenticityToken: authenticityToken
  //   });
  //   this.organization_notification_view.render();
  // }

  // API keys
  // var regenerateApiKeyHandler = function (ev, scope, form_action) {
  //   if (ev) ev.preventDefault();
  //   var authenticity_token = $('[name=authenticity_token][value]').get(0).value;
  //   var dlg = new RegenerateKeysDialog({
  //     type: 'api',
  //     scope: scope,
  //     form_action: form_action,
  //     authenticity_token: authenticity_token
  //   });

  //   dlg.appendToBody();
  // };

  var toggleUserQuotas = function () {
    var viewer = $('.js-userViewerOption:checked').val();
    if (viewer === 'true') {
      $('.user-quotas').hide();
      $('.js-org-admin-row').hide();
      $('#org_admin').prop('checked', false);
    } else {
      $('.user-quotas').show();
      $('.js-org-admin-row').show();
    }
  };

  toggleUserQuotas();

  $('.js-userViewerOption').bind('change', function (ev) {
    toggleUserQuotas();
  });

  $('.js-regenerateOrgUsersApiKey').bind('click', function (ev) {
    var current_username = $(this).attr('data-current_username');

    // regenerateApiKeyHandler(ev, 'organization', '/u/' + current_username + '/organization/regenerate_api_keys');
  });

  $('.js-regenerateOrgUserApiKey').bind('click', function (ev) {
    var username = $(this).attr('data-username');
    var current_username = $(this).attr('data-current_username');

    // regenerateApiKeyHandler(ev, 'organization_user', '/u/' + current_username + '/organization/users/' + username + '/regenerate_api_key');
  });

  var $groups = $('.js-groups-content');
  // if ($groups) {
  //   if (!currentUser.isOrgAdmin()) {
  //     window.location = currentUser.viewUrl().accountProfile();
  //     return false;
  //   }

  //   var groups = new cdb.admin.OrganizationGroups([], {
  //     organization: currentUser.organization
  //   });
  //   var router = new GroupsRouter({
  //     rootUrl: currentUser.viewUrl().organization().groups(),
  //     flashMessageModel: flashMessageModel,
  //     groups: groups,
  //     user: currentUser
  //   });

  //   var groupsMainView = new GroupsMainView({
  //     el: $groups,
  //     groups: groups,
  //     router: router,
  //     user: currentUser
  //   });
  //   groupsMainView.render();
  //   window.groups = groupsMainView;

  //   router.enableAfterMainView();
  // }
});
<|endoftext|>


<commit_before>'use strict'

const service = require('feathers-mongoose')
const participant = require('./participant-model')
const hooks = require('./hooks')
const globalFilters = require('../../filters')

module.exports = function () {
  const app = this

  const options = {
    Model: participant,
    paginate: {
      default: 5,
      max: 25
    }
  }

  // Initialize our service with any options it requires
  app.use('/participants', service(options))

  // Get our initialize service to that we can bind hooks
  const participantService = app.service('/participants')

  // Set up our before hooks
  participantService.before(hooks.before)

  // Set up our after hooks
  participantService.after(hooks.after)

  participantService.filter(globalFilters.decryptParticipantFilter)
}
<commit_msg>removed paging from participant model<commit_after>'use strict'

const service = require('feathers-mongoose')
const participant = require('./participant-model')
const hooks = require('./hooks')
const globalFilters = require('../../filters')

module.exports = function () {
  const app = this

  const options = {
    Model: participant
  }

  // Initialize our service with any options it requires
  app.use('/participants', service(options))

  // Get our initialize service to that we can bind hooks
  const participantService = app.service('/participants')

  // Set up our before hooks
  participantService.before(hooks.before)

  // Set up our after hooks
  participantService.after(hooks.after)

  participantService.filter(globalFilters.decryptParticipantFilter)
}
<|endoftext|>