<commit_before>/**
 * Created by nuintun on 2015/11/20.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('../../util');
var Vue = require('../../vue/vue');
var Terminal = require('../../terminal');

const EMPTYPROJECT = {
  name: '',
  path: '',
  env: [],
  command: [],
  empty: true
};

require('../project-configure');

/**
 * clone project
 * @param projects
 * @param index
 * @returns {*}
 */
function clone(projects, index){
  return util.clone(projects[index] || EMPTYPROJECT);
}

/**
 * srcoll
 * @param xterm
 */
function scroll(xterm){
  var parent = xterm.element.parentNode;

  if (parent) {
    var viewHeight = xterm.element.parentNode.clientHeight;

    if (viewHeight < xterm.y * 18) {
      xterm.children[xterm.y].scrollIntoView();
    }
  }
}

module.exports = Vue.component('app-main', {
  template: fs.readFileSync(path.join(__dirname, 'app-main.html')).toString(),
  props: {
    activeIndex: {
      type: Number,
      twoWay: true,
      required: true
    },
    projects: {
      type: Array,
      twoWay: true,
      required: true
    },
    unique: {
      type: Object,
      required: true
    }
  },
  data: function (){
    var project = clone(this.projects, this.activeIndex);

    return {
      showSetting: false,
      expandCommand: false,
      project: project,
      command: project.command.slice(0, 3),
      moreCommand: project.command.slice(3)
    };
  },
  watch: {
    projects: function (){
      this.project = clone(this.projects, this.activeIndex);
    },
    activeIndex: function (){
      this.project = clone(this.projects, this.activeIndex);
    },
    project: function (){
      this.command = this.project.command.slice(0, 3);
      this.moreCommand = this.project.command.slice(3);
    }
  },
  methods: {
    exec: function (name, command){
      var xtermNode = this.$els.terminal;
      var runtime = window.AppRuntime[this.project.name];

      var test = [
        '\u001b[92m\'use strict\'\u001b[39m\u001b[90m;\u001b[39m',
        '\u001b[90m/*jshint browser:true */\u001b[39m',
        '',
        '\u001b[32mvar\u001b[39m \u001b[37mTerminal\u001b[39m \u001b[93m=\u001b[39m \u001b[37mrequire\u001b[39m\u001b[90m(\u001b[39m\u001b[92m\'./term\'\u001b[39m\u001b[90m)\u001b[39m',
        '  \u001b[32m,\u001b[39m \u001b[37mthrough\u001b[39m \u001b[93m=\u001b[39m \u001b[37mrequire\u001b[39m\u001b[90m(\u001b[39m\u001b[92m\'through\'\u001b[39m\u001b[90m)\u001b[39m',
        '  \u001b[90m;\u001b[39m',
        '',
        '\u001b[37mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[37mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37mcols\u001b[39m\u001b[32m,\u001b[39m \u001b[37mrows\u001b[39m\u001b[32m,\u001b[39m \u001b[37mhandler\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '  \u001b[32mvar\u001b[39m \u001b[37mterm\u001b[39m \u001b[93m=\u001b[39m \u001b[31mnew\u001b[39m \u001b[37mTerminal\u001b[39m\u001b[90m(\u001b[39m\u001b[37mcols\u001b[39m\u001b[32m,\u001b[39m \u001b[37mrows\u001b[39m\u001b[32m,\u001b[39m \u001b[37mhandler\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mopen\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  ',
        '  \u001b[32mvar\u001b[39m \u001b[37mhypernal\u001b[39m \u001b[93m=\u001b[39m \u001b[37mthrough\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m\u001b[32m.\u001b[39m\u001b[37mbind\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[90m)\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mappendTo\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37melem\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '    \u001b[94mif\u001b[39m \u001b[90m(\u001b[39m\u001b[94mtypeof\u001b[39m \u001b[37melem\u001b[39m \u001b[93m===\u001b[39m \u001b[92m\'string\'\u001b[39m\u001b[90m)\u001b[39m \u001b[37melem\u001b[39m \u001b[93m=\u001b[39m \u001b[37mdocument\u001b[39m\u001b[32m.\u001b[39m\u001b[37mquerySelector\u001b[39m\u001b[90m(\u001b[39m\u001b[37melem\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '    \u001b[37melem\u001b[39m\u001b[32m.\u001b[39m\u001b[37mappendChild\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37melement\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '    \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37melement\u001b[39m\u001b[32m.\u001b[39m\u001b[37mstyle\u001b[39m\u001b[32m.\u001b[39m\u001b[37mposition\u001b[39m \u001b[93m=\u001b[39m \u001b[92m\'relative\'\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwriteln\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37mline\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '    \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwriteln\u001b[39m\u001b[90m(\u001b[39m\u001b[37mline\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m \u001b[93m=\u001b[39m \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m\u001b[32m.\u001b[39m\u001b[37mbind\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[31mreturn\u001b[39m \u001b[37mhypernal\u001b[39m\u001b[90m;\u001b[39m',
        '\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        new Date().toISOString(),
        ''
      ].join('\r\n');

      if (!runtime) {
        var xterm = new Terminal({
          debug: true,
          bgColor: 'transparent',
          fgColor: 'inherit'
        });

        xterm.open();
        xtermNode.appendChild(xterm.element);

        xterm.write(test);
        scroll(xterm);

        window.xterm = xterm;

        window.AppRuntime[this.project.name] = {
          name: name,
          command: command,
          xterm: xterm
        }
      } else {
        runtime.xterm.write(test);
        scroll(runtime.xterm);
      }
    },
    setting: function (){
      this.showSetting = true;
    },
    remove: function (){
      // remove project
      this.projects.splice(this.activeIndex, 1);

      // change active
      this.activeIndex = 0;

      // save configure
      this.$dispatch('save-configure');
    }
  },
  events: {
    'setting-toggle': function (state){
      this.showSetting = state;
    },
    edit: function (project){
      this.projects.$set(this.activeIndex, project);
      this.$dispatch('save-configure');
    }
  },
  created: function (){
    var context = this;

    document.addEventListener('click', function (event){
      var target = event.target;
      var trigger = context.$els.expandTrigger;

      context.expandCommand = trigger && trigger.contains(target);
    }, false);
  }
});
<commit_msg>update files<commit_after>/**
 * Created by nuintun on 2015/11/20.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('../../util');
var Vue = require('../../vue/vue');
var Terminal = require('../../terminal');

const EMPTYPROJECT = {
  name: '',
  path: '',
  env: [],
  command: [],
  empty: true
};

require('../project-configure');

/**
 * clone project
 * @param projects
 * @param index
 * @returns {*}
 */
function clone(projects, index){
  return util.clone(projects[index] || EMPTYPROJECT);
}

/**
 * srcoll
 * @param xterm
 */
function scroll(xterm){
  var parent = xterm.element.parentNode;

  if (parent) {
    var viewHeight = xterm.element.parentNode.clientHeight;

    if (viewHeight < xterm.y * 18) {
      xterm.children[xterm.y].scrollIntoView();
    }
  }
}

module.exports = Vue.component('app-main', {
  template: fs.readFileSync(path.join(__dirname, 'app-main.html')).toString(),
  props: {
    activeIndex: {
      type: Number,
      twoWay: true,
      required: true
    },
    projects: {
      type: Array,
      twoWay: true,
      required: true
    },
    unique: {
      type: Object,
      required: true
    }
  },
  data: function (){
    var project = clone(this.projects, this.activeIndex);

    return {
      showSetting: false,
      expandCommand: false,
      project: project,
      command: project.command.slice(0, 3),
      moreCommand: project.command.slice(3)
    };
  },
  watch: {
    projects: function (){
      this.project = clone(this.projects, this.activeIndex);
    },
    activeIndex: function (){
      this.project = clone(this.projects, this.activeIndex);
    },
    project: function (){
      this.command = this.project.command.slice(0, 3);
      this.moreCommand = this.project.command.slice(3);
    }
  },
  methods: {
    exec: function (name, command){
      var xtermNode = this.$els.terminal;
      var runtime = window.AppRuntime[this.project.name];

      var test = [
        '\u001b[92m\'use strict\'\u001b[39m\u001b[90m;\u001b[39m',
        '\u001b[90m/*jshint browser:true */\u001b[39m',
        '',
        '\u001b[32mvar\u001b[39m \u001b[37mTerminal\u001b[39m \u001b[93m=\u001b[39m \u001b[37mrequire\u001b[39m\u001b[90m(\u001b[39m\u001b[92m\'./term\'\u001b[39m\u001b[90m)\u001b[39m',
        '  \u001b[32m,\u001b[39m \u001b[37mthrough\u001b[39m \u001b[93m=\u001b[39m \u001b[37mrequire\u001b[39m\u001b[90m(\u001b[39m\u001b[92m\'through\'\u001b[39m\u001b[90m)\u001b[39m',
        '  \u001b[90m;\u001b[39m',
        '',
        '\u001b[37mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[37mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37mcols\u001b[39m\u001b[32m,\u001b[39m \u001b[37mrows\u001b[39m\u001b[32m,\u001b[39m \u001b[37mhandler\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '  \u001b[32mvar\u001b[39m \u001b[37mterm\u001b[39m \u001b[93m=\u001b[39m \u001b[31mnew\u001b[39m \u001b[37mTerminal\u001b[39m\u001b[90m(\u001b[39m\u001b[37mcols\u001b[39m\u001b[32m,\u001b[39m \u001b[37mrows\u001b[39m\u001b[32m,\u001b[39m \u001b[37mhandler\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mopen\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  ',
        '  \u001b[32mvar\u001b[39m \u001b[37mhypernal\u001b[39m \u001b[93m=\u001b[39m \u001b[37mthrough\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m\u001b[32m.\u001b[39m\u001b[37mbind\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[90m)\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mappendTo\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37melem\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '    \u001b[94mif\u001b[39m \u001b[90m(\u001b[39m\u001b[94mtypeof\u001b[39m \u001b[37melem\u001b[39m \u001b[93m===\u001b[39m \u001b[92m\'string\'\u001b[39m\u001b[90m)\u001b[39m \u001b[37melem\u001b[39m \u001b[93m=\u001b[39m \u001b[37mdocument\u001b[39m\u001b[32m.\u001b[39m\u001b[37mquerySelector\u001b[39m\u001b[90m(\u001b[39m\u001b[37melem\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '    \u001b[37melem\u001b[39m\u001b[32m.\u001b[39m\u001b[37mappendChild\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37melement\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '    \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37melement\u001b[39m\u001b[32m.\u001b[39m\u001b[37mstyle\u001b[39m\u001b[32m.\u001b[39m\u001b[37mposition\u001b[39m \u001b[93m=\u001b[39m \u001b[92m\'relative\'\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwriteln\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[37mline\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m',
        '    \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwriteln\u001b[39m\u001b[90m(\u001b[39m\u001b[37mline\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '  \u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[37mhypernal\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m \u001b[93m=\u001b[39m \u001b[37mterm\u001b[39m\u001b[32m.\u001b[39m\u001b[37mwrite\u001b[39m\u001b[32m.\u001b[39m\u001b[37mbind\u001b[39m\u001b[90m(\u001b[39m\u001b[37mterm\u001b[39m\u001b[90m)\u001b[39m\u001b[90m;\u001b[39m',
        '',
        '  \u001b[31mreturn\u001b[39m \u001b[37mhypernal\u001b[39m\u001b[90m;\u001b[39m',
        '\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m',
        new Date().toISOString(),
      ].join('\r\n');

      if (!runtime) {
        var xterm = new Terminal({
          debug: true,
          bgColor: 'transparent',
          fgColor: 'inherit'
        });

        xterm.open();
        xtermNode.appendChild(xterm.element);

        xterm.write(test);
        scroll(xterm);

        window.xterm = xterm;

        window.AppRuntime[this.project.name] = {
          name: name,
          command: command,
          xterm: xterm
        }
      } else {
        runtime.xterm.write(test);
        scroll(runtime.xterm);
      }
    },
    setting: function (){
      this.showSetting = true;
    },
    remove: function (){
      // remove project
      this.projects.splice(this.activeIndex, 1);

      // change active
      this.activeIndex = 0;

      // save configure
      this.$dispatch('save-configure');
    }
  },
  events: {
    'setting-toggle': function (state){
      this.showSetting = state;
    },
    edit: function (project){
      this.projects.$set(this.activeIndex, project);
      this.$dispatch('save-configure');
    }
  },
  created: function (){
    var context = this;

    document.addEventListener('click', function (event){
      var target = event.target;
      var trigger = context.$els.expandTrigger;

      context.expandCommand = trigger && trigger.contains(target);
    }, false);
  }
});
<|endoftext|>


<commit_before>"use strict";

plugin.consumes = [
    "connect.static",
    "connect",
    "preview.handler",
    "connect.render",
    "connect.render.ejs"
];
plugin.provides = ["api", "passport"];

module.exports = plugin;

var fs = require("fs");
var assert = require("assert");
var async = require("async");
var join = require("path").join;
var extend = require("util")._extend;
var resolve = require("path").resolve;
var basename = require("path").basename;
var frontdoor = require("frontdoor");

function plugin(options, imports, register) {
    var previewHandler = imports["preview.handler"];
    var statics = imports["connect.static"];

    assert(options.workspaceDir, "Option 'workspaceDir' is required");
    assert(options.options, "Option 'options' is required");

    // serve index.html
    statics.addStatics([{
        path: __dirname + "/www",
        mount: "/"
    }]);

    statics.addStatics([{
        path: __dirname + "/../../configs",
        mount: "/configs"
    }]);

    statics.addStatics([{
        path: __dirname + "/../../test/resources",
        mount: "/test"
    }]);

    var api = frontdoor();
    imports.connect.use(api);

    api.get("/", function(req, res, next) {
        res.writeHead(302, { "Location": options.sdk ? "/ide.html" : "/static/places.html" });
        res.end();
    });

    api.get("/ide.html", {
        params: {
            workspacetype: {
                source: "query",
                optional: true
            },
            devel: {
                source: "query",
                optional: true
            },
            collab: {
                type: "number",
                optional: true,
                source: "query"
            },
            nocollab: {
                type: "number",
                optional: true,
                source: "query"
            },
            debug: {
                optional: true,
                source: "query"
            },
            packed: {
                source: "query",
                type: "number",
                optional: true
            },
            token: {
                source: "query",
                optional: true
            },
            w: {
                source: "query",
                optional: true
            },
        }
    }, function(req, res, next) {
        var configType = null;
        if (req.params.workspacetype)
            configType = "workspace-" + req.params.workspacetype;
        else if (req.params.devel)
            configType = "devel";

        var configName = getConfigName(configType, options);
        var cdn = options.options.cdn;
        options.options.themePrefix = "/static/" + cdn.version + "/skin/" + configName;
        options.options.workerPrefix = "/static/" + cdn.version + "/worker";
        if (req.params.packed == 1)
            options.options.CORSWorkerPrefix = "/static/" + cdn.version + "/worker";

        var collab = options.collab && req.params.collab !== 0 && req.params.nocollab != 1;
        var opts = extend({}, options);
        opts.options.collab = collab;
        if (req.params.packed == 1)
            opts.packed = opts.options.packed = true;

        api.updatConfig(opts.options, {
            w: req.params.w,
            token: req.params.token
        });

        opts.options.debug = req.params.debug;
        res.setHeader("Cache-Control", "no-cache, no-store");
        res.render(__dirname + "/views/standalone.html.ejs", {
            architectConfig: getConfig(configType, opts),
            configName: configName,
            packed: opts.packed,
            version: opts.version
        }, next);
    });

    api.get("/_ping", function(params, callback) {
        return callback(null, {"ping": "pong"});
    });

    api.get("/preview/:path*", [
        function(req, res, next) {
            req.projectSession = {
                pid: 1
            };
            req.session = {};
            next();
        },
        previewHandler.getProxyUrl(function() {
            return {
                url: "http://localhost:" + options.options.port + "/vfs"
            };
        }),
        previewHandler.proxyCall()
    ]);

    api.get("/preview", function(req, res, next) {
        res.redirect(req.url + "/");
    });

    api.get("/vfs-root", function(req, res, next) {
        if (!options.options.testing)
            return next();

        res.writeHead(200, {"Content-Type": "application/javascript"});
        res.end("define(function(require, exports, module) { return '"
            + options.workspaceDir + "'; });");
    });

    api.get("/update", function(req, res, next) {
        res.writeHead(200, {
            "Content-Type": "application/javascript",
            "Access-Control-Allow-Origin": "*"
        });
        var path = resolve(__dirname + "/../../build/output/latest.tar.gz");
        fs.readlink(path, function(err, target) {
            res.end((target || "").split(".")[0]);
        });
    });

    api.get("/update/:path*", function(req, res, next) {
        var filename = req.params.path;
        var path = resolve(__dirname + "/../../build/output/" + filename);

        res.writeHead(200, {"Content-Type": "application/octet-stream"});
        var stream = fs.createReadStream(path);
        stream.pipe(res);
    });

    api.get("/configs/require_config.js", function(req, res, next) {
        var config = res.getOptions().requirejsConfig || {};
        config.waitSeconds = 240;

        res.writeHead(200, {"Content-Type": "application/javascript"});
        res.end("requirejs.config(" + JSON.stringify(config) + ");");
    });

    api.get("/test/all.json", function(req, res, next) {
        var base = __dirname + "/../../";
        var blacklistfile = base + "/test/blacklist.txt";
        var filefinder = require(base + "/test/filefinder.js");
        filefinder.find(base, "plugins", ".*_test.js", blacklistfile, function(err, result) {
            result.all = result.list.concat(result.blacklist);
            async.filterSeries(result.list, function(file, next) {
                fs.readFile(file, "utf8", function(err, file) {
                    if (err) return next(false);
                    if (file.match(/^"use server"/m) && !file.match(/^"use client"/m))
                        return next(false);
                    next(file.match(/^define\(|^require\(\[/m));
                });
            }, function(files) {
                result.list = files;
                res.writeHead(200, {"Content-Type": "application/json"});
                res.end(JSON.stringify(result, null, 2));
            });
        });
    });

    api.get("/api.json", {name: "api"}, frontdoor.middleware.describeApi(api));

    // fake authentication
    api.authenticate = api.authenticate || function() {
        return function(req, res, next) {
            req.user = extend({}, options.options.extendOptions.user);
            next();
        };
    };
    api.ensureAdmin = api.ensureAdmin || function() {
        return function(req, res, next) {
            next();
        };
    };
    api.getVfsOptions = api.getVfsOptions || function(user, pid) {
        if (!options._projects) {
            options._projects = [options.workspaceDir];
        }
        var wd = options._projects[pid] || options._projects[0];
        console.log(user)
        return {
            workspaceDir: wd,
            extendOptions: {
                user: user,
                project: {
                    id: pid,
                    name: pid + "-" + options._projects[pid]
                },
                readonly: user.id > 100
            }
        };
    };
    api.updatConfig = api.updatConfig || function(opts, params) {
        var id = params.token;
        opts.accessToken = opts.extendToken = id || "token";
        var user = opts.extendOptions.user;
        user.id = id || -1;
        user.name = id ? "user" + id : "johndoe";
        user.email = id ? "user" + id + "@c9.io" : "johndoe@example.org";
        user.fullname = id ? "User " + id : "John Doe";
        opts.workspaceDir = params.w ? params.w : options.workspaceDir;
        opts.projectName = basename(opts.workspaceDir);
        if (!options._projects) {
            options._projects = [options.workspaceDir];
        }
        var project = opts.extendOptions.project;
        var pid = options._projects.indexOf(opts.workspaceDir);
        if (pid == -1)
            pid = options._projects.push(opts.workspaceDir) - 1;
        project.id = pid;
    };

    imports.connect.setGlobalOption("apiBaseUrl", "");

    register(null, {
        "api": api,
        "passport": {
            authenticate: function() {
                return function(req, res, next) {
                    req.user = extend({}, options.options.extendOptions.user);
                    next();
                };
            }
        }
    });
}

function getConfigName(requested, options) {
    var name;
    if (requested) {
        name = requested;
    }
    else if (options.workspaceType) {
        name = "workspace-" + options.workspaceType;
    }
    else if (options.options.client_config) {
        // pick up client config from settings, if present
        name = options.options.client_config;
    }
    else if (options.readonly) {
        name = "default-ro";
    }
    else {
        name = "default";
    }

    if (options.local)
        name += "-local";

    return name;
}

function getConfig(requested, options) {
    var filename = __dirname + "/../../configs/client-" + getConfigName(requested, options) + ".js";

    var installPath = options.settingDir || options.installPath || "";
    var workspaceDir = options.options.workspaceDir;
    var settings = {
        "user": join(installPath, "user.settings"),
        "project": join(options.local ? installPath : join(workspaceDir, ".c9"), "project.settings"),
        "state": join(options.local ? installPath : join(workspaceDir, ".c9"), "state.settings")
    };

    var fs = require("fs");
    for (var type in settings) {
        var data = "";
        try {
            data = fs.readFileSync(settings[type], "utf8");
        } catch (e) {
            console.log(e);
        }
        settings[type] = data;
    }
    options.options.settings = settings;

    return require(filename)(options.options);
}
<commit_msg>remove confusing error logs<commit_after>"use strict";

plugin.consumes = [
    "connect.static",
    "connect",
    "preview.handler",
    "connect.render",
    "connect.render.ejs"
];
plugin.provides = ["api", "passport"];

module.exports = plugin;

var fs = require("fs");
var assert = require("assert");
var async = require("async");
var join = require("path").join;
var extend = require("util")._extend;
var resolve = require("path").resolve;
var basename = require("path").basename;
var frontdoor = require("frontdoor");

function plugin(options, imports, register) {
    var previewHandler = imports["preview.handler"];
    var statics = imports["connect.static"];

    assert(options.workspaceDir, "Option 'workspaceDir' is required");
    assert(options.options, "Option 'options' is required");

    // serve index.html
    statics.addStatics([{
        path: __dirname + "/www",
        mount: "/"
    }]);

    statics.addStatics([{
        path: __dirname + "/../../configs",
        mount: "/configs"
    }]);

    statics.addStatics([{
        path: __dirname + "/../../test/resources",
        mount: "/test"
    }]);

    var api = frontdoor();
    imports.connect.use(api);

    api.get("/", function(req, res, next) {
        res.writeHead(302, { "Location": options.sdk ? "/ide.html" : "/static/places.html" });
        res.end();
    });

    api.get("/ide.html", {
        params: {
            workspacetype: {
                source: "query",
                optional: true
            },
            devel: {
                source: "query",
                optional: true
            },
            collab: {
                type: "number",
                optional: true,
                source: "query"
            },
            nocollab: {
                type: "number",
                optional: true,
                source: "query"
            },
            debug: {
                optional: true,
                source: "query"
            },
            packed: {
                source: "query",
                type: "number",
                optional: true
            },
            token: {
                source: "query",
                optional: true
            },
            w: {
                source: "query",
                optional: true
            },
        }
    }, function(req, res, next) {
        var configType = null;
        if (req.params.workspacetype)
            configType = "workspace-" + req.params.workspacetype;
        else if (req.params.devel)
            configType = "devel";

        var configName = getConfigName(configType, options);
        var cdn = options.options.cdn;
        options.options.themePrefix = "/static/" + cdn.version + "/skin/" + configName;
        options.options.workerPrefix = "/static/" + cdn.version + "/worker";
        if (req.params.packed == 1)
            options.options.CORSWorkerPrefix = "/static/" + cdn.version + "/worker";

        var collab = options.collab && req.params.collab !== 0 && req.params.nocollab != 1;
        var opts = extend({}, options);
        opts.options.collab = collab;
        if (req.params.packed == 1)
            opts.packed = opts.options.packed = true;

        api.updatConfig(opts.options, {
            w: req.params.w,
            token: req.params.token
        });

        opts.options.debug = req.params.debug;
        res.setHeader("Cache-Control", "no-cache, no-store");
        res.render(__dirname + "/views/standalone.html.ejs", {
            architectConfig: getConfig(configType, opts),
            configName: configName,
            packed: opts.packed,
            version: opts.version
        }, next);
    });

    api.get("/_ping", function(params, callback) {
        return callback(null, {"ping": "pong"});
    });

    api.get("/preview/:path*", [
        function(req, res, next) {
            req.projectSession = {
                pid: 1
            };
            req.session = {};
            next();
        },
        previewHandler.getProxyUrl(function() {
            return {
                url: "http://localhost:" + options.options.port + "/vfs"
            };
        }),
        previewHandler.proxyCall()
    ]);

    api.get("/preview", function(req, res, next) {
        res.redirect(req.url + "/");
    });

    api.get("/vfs-root", function(req, res, next) {
        if (!options.options.testing)
            return next();

        res.writeHead(200, {"Content-Type": "application/javascript"});
        res.end("define(function(require, exports, module) { return '"
            + options.workspaceDir + "'; });");
    });

    api.get("/update", function(req, res, next) {
        res.writeHead(200, {
            "Content-Type": "application/javascript",
            "Access-Control-Allow-Origin": "*"
        });
        var path = resolve(__dirname + "/../../build/output/latest.tar.gz");
        fs.readlink(path, function(err, target) {
            res.end((target || "").split(".")[0]);
        });
    });

    api.get("/update/:path*", function(req, res, next) {
        var filename = req.params.path;
        var path = resolve(__dirname + "/../../build/output/" + filename);

        res.writeHead(200, {"Content-Type": "application/octet-stream"});
        var stream = fs.createReadStream(path);
        stream.pipe(res);
    });

    api.get("/configs/require_config.js", function(req, res, next) {
        var config = res.getOptions().requirejsConfig || {};
        config.waitSeconds = 240;

        res.writeHead(200, {"Content-Type": "application/javascript"});
        res.end("requirejs.config(" + JSON.stringify(config) + ");");
    });

    api.get("/test/all.json", function(req, res, next) {
        var base = __dirname + "/../../";
        var blacklistfile = base + "/test/blacklist.txt";
        var filefinder = require(base + "/test/filefinder.js");
        filefinder.find(base, "plugins", ".*_test.js", blacklistfile, function(err, result) {
            result.all = result.list.concat(result.blacklist);
            async.filterSeries(result.list, function(file, next) {
                fs.readFile(file, "utf8", function(err, file) {
                    if (err) return next(false);
                    if (file.match(/^"use server"/m) && !file.match(/^"use client"/m))
                        return next(false);
                    next(file.match(/^define\(|^require\(\[/m));
                });
            }, function(files) {
                result.list = files;
                res.writeHead(200, {"Content-Type": "application/json"});
                res.end(JSON.stringify(result, null, 2));
            });
        });
    });

    api.get("/api.json", {name: "api"}, frontdoor.middleware.describeApi(api));

    // fake authentication
    api.authenticate = api.authenticate || function() {
        return function(req, res, next) {
            req.user = extend({}, options.options.extendOptions.user);
            next();
        };
    };
    api.ensureAdmin = api.ensureAdmin || function() {
        return function(req, res, next) {
            next();
        };
    };
    api.getVfsOptions = api.getVfsOptions || function(user, pid) {
        if (!options._projects) {
            options._projects = [options.workspaceDir];
        }
        var wd = options._projects[pid] || options._projects[0];

        return {
            workspaceDir: wd,
            extendOptions: {
                user: user,
                project: {
                    id: pid,
                    name: pid + "-" + options._projects[pid]
                },
                readonly: user.id > 100
            }
        };
    };
    api.updatConfig = api.updatConfig || function(opts, params) {
        var id = params.token;
        opts.accessToken = opts.extendToken = id || "token";
        var user = opts.extendOptions.user;
        user.id = id || -1;
        user.name = id ? "user" + id : "johndoe";
        user.email = id ? "user" + id + "@c9.io" : "johndoe@example.org";
        user.fullname = id ? "User " + id : "John Doe";
        opts.workspaceDir = params.w ? params.w : options.workspaceDir;
        opts.projectName = basename(opts.workspaceDir);
        if (!options._projects) {
            options._projects = [options.workspaceDir];
        }
        var project = opts.extendOptions.project;
        var pid = options._projects.indexOf(opts.workspaceDir);
        if (pid == -1)
            pid = options._projects.push(opts.workspaceDir) - 1;
        project.id = pid;
    };

    imports.connect.setGlobalOption("apiBaseUrl", "");

    register(null, {
        "api": api,
        "passport": {
            authenticate: function() {
                return function(req, res, next) {
                    req.user = extend({}, options.options.extendOptions.user);
                    next();
                };
            }
        }
    });
}

function getConfigName(requested, options) {
    var name;
    if (requested) {
        name = requested;
    }
    else if (options.workspaceType) {
        name = "workspace-" + options.workspaceType;
    }
    else if (options.options.client_config) {
        // pick up client config from settings, if present
        name = options.options.client_config;
    }
    else if (options.readonly) {
        name = "default-ro";
    }
    else {
        name = "default";
    }

    if (options.local)
        name += "-local";

    return name;
}

function getConfig(requested, options) {
    var filename = __dirname + "/../../configs/client-" + getConfigName(requested, options) + ".js";

    var installPath = options.settingDir || options.installPath || "";
    var workspaceDir = options.options.workspaceDir;
    var settings = {
        "user": join(installPath, "user.settings"),
        "project": join(options.local ? installPath : join(workspaceDir, ".c9"), "project.settings"),
        "state": join(options.local ? installPath : join(workspaceDir, ".c9"), "state.settings")
    };

    var fs = require("fs");
    for (var type in settings) {
        var data = "";
        try {
            data = fs.readFileSync(settings[type], "utf8");
        } catch (e) {
        }
        settings[type] = data;
    }
    options.options.settings = settings;

    return require(filename)(options.options);
}
<|endoftext|>


<commit_before>$(function () {
    $('#projectStatusFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    $('#projectCategoryFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    $('#projectPrizeFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    //myProjects filters
    $('#myProjectStatusFilter')
       .change(function () {
           $('#myProjectsCreatedFilter').removeClass('tab_item--active');
           $('#myProjectsFollowingFilter').removeClass('tab_item--active');
           $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

           $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
               $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
               $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
       });

    $('#myProjectCategoryFilter')
        .change(function () {
            $('#myProjectsCreatedFilter').removeClass('tab_item--active');
            $('#myProjectsFollowingFilter').removeClass('tab_item--active');
            $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

            $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
                $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
                $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
        });

    $('#myProjectPrizeFilter')
        .change(function () {
            $('#myProjectsCreatedFilter').removeClass('tab_item--active');
            $('#myProjectsFollowingFilter').removeClass('tab_item--active');
            $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

            $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
                $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
                $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
        });

    $('#voteForButton')
        .click(function () {
            var $this = $(this);

            if ($this.text().trim() === '') {
                $this.append('Yes');
            }

            $('#projectVoteResults').load('/ProjectDetails/VoteFor?projectId=' + $('#ProjectId').val());
        });

    $('._voting_btn').on('click', function () {
        $(this).toggleClass('active').siblings('._voting_btn').toggleClass('invisible').parents('.voting_group').toggleClass('voted');
    });

    $('#voteAgainstButton')
        .click(function () {
            var $this = $(this);

            if ($this.text().trim() === '') {
                $this.append('No');
            }

            $('#projectVoteResults').load('/ProjectDetails/VoteAgainst?projectId=' + $('#ProjectId').val());
        });

    function barWidth() {
        var barWidth = $('.progress-bar').width();
        $('.progress-fill-text').css('width', barWidth);
    }

    barWidth();

    window.onresize = function () {
        barWidth();
    };

    $('#voteTestButton')
        .click(function (e) {
            e.preventDefault();
            $('#projectDetailsTabs a[href="#Results"]').tab('show');
        });

    $('.replyToCommentButton')
       .click(function () {
           var id = '#' + this.id;
           $(id).load('/ProjectDetails/GetCommentReplyForm?commentId=' + this.id + '&projectId=' + $('#projectId').val());
           $('.' + this.id).hide();
       });

    $('#file').change(function () {
        $("#fileInputHelperText").empty();
        $("#fileInputHelperText").append(this.value.split('\\').pop());
    });

    tinymce.init({
        selector: 'textarea.richEditor',
        plugins: 'lists link image media  preview code',
        toolbar1: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media'
    });

    //restyling js

    $('._show_hidden_form').on('click', function (ev) {
        ev.preventDefault();
        $(this).hide().siblings('.hidden_form').show();
    });

    $('#msg')
        .bind('blur',
            function () {
                if (!$(this).val()) {
                    $(this).parents('.form--message').removeClass('focused');
                    $(this).parents('.message_card__inner').removeAttr('style');
                }
            })
        .bind('focus', function () { $(this).parents('.form--message').addClass('focused'); })
        .keyup(function () {
            if ($(this).val()) {
                $(this).parents('.form--message').addClass('with_value');
            } else {
                $(this).parents('.form--message').removeClass('with_value');
            }
        });

    $('#msg')
      .each(function () { autosize(this); })
      .on('autosize:resized', function () {
          $('.message_card__inner').css({ height: 'auto' });
      });

    var clipboard = new Clipboard('._copy_link');

    clipboard.on('success', function (e) {

        e.trigger.innerHTML = e.trigger.getAttribute('aria-label');
        e.clearSelection();
        clipboard.destroy();
    });

    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            $('body')
                .find('#launcher, .btn_feedback')
                .css({
                    bottom: $('.footer').outerHeight()
                });
        }

        else {
            $('body')
                .find('#launcher, .btn_feedback')
                .css({
                    bottom: 0
                });
        }
    });

    $('#navbar-collapse')
      .on('click', function (e) {
          $('body').toggleClass('menu-collapsed');
      });

    //caches a jQuery object containing the header element
    var header = $('.header:not(.header--static)');
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();

        if (scroll >= 10) {
            header.addClass('fixed');
        } else {
            header.removeClass('fixed');
        }
    });

    $('.sticky_header').affix({
        offset: {
            top: function () {
                return (this.top = $('.sticky_header_container').offset().top);
            }
        }
    });

    $('.sticky_header').on('affix.bs.affix',
        function (e) {
            var height = $(this).outerHeight();
            $(this).parents('.sticky_header_container').css({
                height: height + 1
            });
        });

    $('.closed-voting-places').click(function () {
        $('.closed-voting-dropdown').toggleClass('open');
    });

    $('#enableVoting').click(function () {
        if ($('#enableVoting').is(":checked")) {
            $('#votingDeadlineDatepicker').show();
            $('.votingDeadlineDatepickerValidation').show();
        } else {
            $('#votingDeadlineDatepicker').hide();
            $('.votingDeadlineDatepickerValidation').hide();

            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1;

            var yyyy = today.getFullYear();
            if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + '-' + mm + '-' + dd;

            $('#votingDeadlineDatepicker').attr('value', today);
        }
    });

    $('#datetimepicker1').datetimepicker();
});
<commit_msg>Add js for skip registration checkbox.<commit_after>$(function () {
    $('#projectStatusFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    $('#projectCategoryFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    $('#projectPrizeFilter')
        .change(function () {
            $('#projectListResults').load('/Home/GetProjectList?projectStatusFilter=' +
                $('#projectStatusFilter :selected').val() + '&projectCategoryFilter=' +
                $('#projectCategoryFilter :selected').val().replace(/\s/g, '') + '&projectPrizeFilter=' + $('#projectPrizeFilter :selected').val());
        });

    //myProjects filters
    $('#myProjectStatusFilter')
       .change(function () {
           $('#myProjectsCreatedFilter').removeClass('tab_item--active');
           $('#myProjectsFollowingFilter').removeClass('tab_item--active');
           $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

           $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
               $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
               $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
       });

    $('#myProjectCategoryFilter')
        .change(function () {
            $('#myProjectsCreatedFilter').removeClass('tab_item--active');
            $('#myProjectsFollowingFilter').removeClass('tab_item--active');
            $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

            $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
                $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
                $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
        });

    $('#myProjectPrizeFilter')
        .change(function () {
            $('#myProjectsCreatedFilter').removeClass('tab_item--active');
            $('#myProjectsFollowingFilter').removeClass('tab_item--active');
            $('#myProjectsParticipatingFilter').removeClass('tab_item--active');

            $('#myProjectListResults').load('/Home/GetMyProjectList?myProjectStatusFilter=' +
                $('#myProjectStatusFilter :selected').val() + '&myProjectCategoryFilter=' +
                $('#myProjectCategoryFilter :selected').val().replace(/\s/g, '') + '&myProjectPrizeFilter=' + $('#myProjectPrizeFilter :selected').val());
        });

    $('#voteForButton')
        .click(function () {
            var $this = $(this);

            if ($this.text().trim() === '') {
                $this.append('Yes');
            }

            $('#projectVoteResults').load('/ProjectDetails/VoteFor?projectId=' + $('#ProjectId').val());
        });

    $('._voting_btn').on('click', function () {
        $(this).toggleClass('active').siblings('._voting_btn').toggleClass('invisible').parents('.voting_group').toggleClass('voted');
    });

    $('#voteAgainstButton')
        .click(function () {
            var $this = $(this);

            if ($this.text().trim() === '') {
                $this.append('No');
            }

            $('#projectVoteResults').load('/ProjectDetails/VoteAgainst?projectId=' + $('#ProjectId').val());
        });

    function barWidth() {
        var barWidth = $('.progress-bar').width();
        $('.progress-fill-text').css('width', barWidth);
    }

    barWidth();

    window.onresize = function () {
        barWidth();
    };

    $('#voteTestButton')
        .click(function (e) {
            e.preventDefault();
            $('#projectDetailsTabs a[href="#Results"]').tab('show');
        });

    $('.replyToCommentButton')
       .click(function () {
           var id = '#' + this.id;
           $(id).load('/ProjectDetails/GetCommentReplyForm?commentId=' + this.id + '&projectId=' + $('#projectId').val());
           $('.' + this.id).hide();
       });

    $('#file').change(function () {
        $("#fileInputHelperText").empty();
        $("#fileInputHelperText").append(this.value.split('\\').pop());
    });

    tinymce.init({
        selector: 'textarea.richEditor',
        plugins: 'lists link image media  preview code',
        toolbar1: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media'
    });

    //restyling js

    $('._show_hidden_form').on('click', function (ev) {
        ev.preventDefault();
        $(this).hide().siblings('.hidden_form').show();
    });

    $('#msg')
        .bind('blur',
            function () {
                if (!$(this).val()) {
                    $(this).parents('.form--message').removeClass('focused');
                    $(this).parents('.message_card__inner').removeAttr('style');
                }
            })
        .bind('focus', function () { $(this).parents('.form--message').addClass('focused'); })
        .keyup(function () {
            if ($(this).val()) {
                $(this).parents('.form--message').addClass('with_value');
            } else {
                $(this).parents('.form--message').removeClass('with_value');
            }
        });

    $('#msg')
      .each(function () { autosize(this); })
      .on('autosize:resized', function () {
          $('.message_card__inner').css({ height: 'auto' });
      });

    var clipboard = new Clipboard('._copy_link');

    clipboard.on('success', function (e) {

        e.trigger.innerHTML = e.trigger.getAttribute('aria-label');
        e.clearSelection();
        clipboard.destroy();
    });

    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            $('body')
                .find('#launcher, .btn_feedback')
                .css({
                    bottom: $('.footer').outerHeight()
                });
        }

        else {
            $('body')
                .find('#launcher, .btn_feedback')
                .css({
                    bottom: 0
                });
        }
    });

    $('#navbar-collapse')
      .on('click', function (e) {
          $('body').toggleClass('menu-collapsed');
      });

    //caches a jQuery object containing the header element
    var header = $('.header:not(.header--static)');
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();

        if (scroll >= 10) {
            header.addClass('fixed');
        } else {
            header.removeClass('fixed');
        }
    });

    $('.sticky_header').affix({
        offset: {
            top: function () {
                return (this.top = $('.sticky_header_container').offset().top);
            }
        }
    });

    $('.sticky_header').on('affix.bs.affix',
        function (e) {
            var height = $(this).outerHeight();
            $(this).parents('.sticky_header_container').css({
                height: height + 1
            });
        });

    $('.closed-voting-places').click(function () {
        $('.closed-voting-dropdown').toggleClass('open');
    });

    $('#enableVoting').click(function () {
        if ($('#enableVoting').is(":checked")) {
            $('#votingDeadlineDatepicker').show();
            $('.votingDeadlineDatepickerValidation').show();
        } else {
            $('#votingDeadlineDatepicker').hide();
            $('.votingDeadlineDatepickerValidation').hide();

            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1;

            var yyyy = today.getFullYear();
            if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + '-' + mm + '-' + dd;

            $('#votingDeadlineDatepicker').attr('value', today);
        }
    });

    $('#enableVoting').click(function () {
        if ($('#enableVoting').is(":checked")) {
            $('#votingDeadlineDatepicker').val('');
            $('#votingDeadlineDatepicker').show();
            $('.votingDeadlineDatepickerValidation').show();
        } else {
            $('#votingDeadlineDatepicker').hide();
            $('.votingDeadlineDatepickerValidation').hide();

            $('#votingDeadlineDatepicker').attr('value', getTodayFormatted());
        }
    });

    $('#enableRegistration').click(function () {
        if ($('#enableRegistration').is(":checked")) {
            $('#registrationDeadlineDatepicker').val('');
            $('#registrationDeadlineDatepicker').show();
            $('.registrationDeadlineDatepickerValidation').show();
        } else {
            $('#registrationDeadlineDatepicker').attr('value', getTodayFormatted());

            $('#registrationDeadlineDatepicker').hide();
            $('.registrationDeadlineDatepickerValidation').hide();
        }
    });

    function getTodayFormatted() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1;

        var yyyy = today.getFullYear();
        if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + '-' + mm + '-' + dd;

        return today;
    }

    $('#datetimepicker1').datetimepicker();
});
<|endoftext|>


<commit_before>import StringStream from "../../util/StringStream.js"
import * as modeMethods from "../../modes.js"

// Copy StringStream and mode methods into exports (CodeMirror) object.
exports.StringStream = StringStream
for (var exported in modeMethods) exports[exported] = modeMethods[exported]

// Shim library CodeMirror with the minimal CodeMirror defined above.
require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")]
require.cache[require.resolve("../../addon/runmode/runmode")] = require.cache[require.resolve("./runmode.node")]

// Minimal default mode.
exports.defineMode("null", () => ({token: stream => stream.skipToEnd()}))
exports.defineMIME("text/plain", "null")

exports.registerHelper = exports.registerGlobalHelper = Math.min
exports.splitLines = function(string) { return string.split(/\r?\n|\r/); }

exports.defaults = { indentUnit: 2 }<commit_msg>[runmode.node addon] Export countColumn again<commit_after>import StringStream from "../../util/StringStream.js"
import * as modeMethods from "../../modes.js"
import {countColumn} from "../../util/misc.js"

// Copy StringStream and mode methods into exports (CodeMirror) object.
exports.StringStream = StringStream
exports.countColumn = countColumn
for (var exported in modeMethods) exports[exported] = modeMethods[exported]

// Shim library CodeMirror with the minimal CodeMirror defined above.
require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")]
require.cache[require.resolve("../../addon/runmode/runmode")] = require.cache[require.resolve("./runmode.node")]

// Minimal default mode.
exports.defineMode("null", () => ({token: stream => stream.skipToEnd()}))
exports.defineMIME("text/plain", "null")

exports.registerHelper = exports.registerGlobalHelper = Math.min
exports.splitLines = function(string) { return string.split(/\r?\n|\r/); }

exports.defaults = { indentUnit: 2 }
<|endoftext|>


<commit_before>import messages from 'lib/text'
import settings from 'lib/settings'
import {installReceive} from 'modules/settings/actions'
import {fetchOrders} from 'modules/orders/actions'

const AUTO_RECONNECT_INTERVAL = 5000; //5 seconds
const ORDER_CREATED = 'order.created';
const THEME_INSTALLED = 'theme.installed';
let store = null;

export const connectToWebSocket = (reduxStore) => {
  store = reduxStore;
  connect();
}

const connect = () => {
  const wsUrl = (settings.apiWebSocketUrl && settings.apiWebSocketUrl.length > 0) ?
    settings.apiWebSocketUrl :
    getWebSocketUrlFromCurrentLocation();

  const token = localStorage.getItem('dashboard_token');
  const ws = new WebSocket(`${wsUrl}/ws/dashboard?token=${token}`);

  ws.onmessage = onMessage;
  ws.onopen = onOpen;
  ws.onclose = onClose;
  ws.onerror = onError;
}

const getWebSocketUrlFromCurrentLocation = () => {
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  return `${wsProtocol}//${window.location.host}`;
}

const onMessage = (event) => {
  try {
    const message = JSON.parse(event.data);
    eventHandler(message);
  } catch (err) {}
};

const onOpen = () => {};

const onError = () => {};

const onClose = (event) => {
  if(event.code !== 1000){
    console.log(`WebSocket connection closed with code: ${event.code}.`);
    // try to reconnect
    setTimeout(() => { connect(); }, AUTO_RECONNECT_INTERVAL);
  }
};

const showNotification = (title, body, requireInteraction = false) => {
  let msg = new Notification(title, {
    body: body,
    tag: 'dashboard',
    requireInteraction: requireInteraction
  });

  msg.addEventListener("click", (event) => {
    parent.focus();
    event.target.close();
  });
}

const eventHandler = ({ event, payload }) => {
  switch(event){
    case THEME_INSTALLED:
      const fileName = payload;
      store.dispatch(installReceive());
      showNotification(messages.settings_theme, messages.themeInstalled);
      break;
    case ORDER_CREATED:
      const order = payload;
      store.dispatch(fetchOrders());
      showNotification(`${messages.order} #${order.number}`, `${order.shipping_address.full_name}, ${order.shipping_address.city}`, true);
      break;
    default:
      break;
  }
}
<commit_msg>Change interval to 1 sec. Show logs only on developerMode.<commit_after>import messages from 'lib/text'
import settings from 'lib/settings'
import {installReceive} from 'modules/settings/actions'
import {fetchOrders} from 'modules/orders/actions'

const AUTO_RECONNECT_INTERVAL = 1000; //1 seconds
const ORDER_CREATED = 'order.created';
const THEME_INSTALLED = 'theme.installed';
let store = null;

export const connectToWebSocket = (reduxStore) => {
  store = reduxStore;
  connect();
}

const connect = () => {
  const wsUrl = (settings.apiWebSocketUrl && settings.apiWebSocketUrl.length > 0) ?
    settings.apiWebSocketUrl :
    getWebSocketUrlFromCurrentLocation();

  const token = localStorage.getItem('dashboard_token');
  const ws = new WebSocket(`${wsUrl}/ws/dashboard?token=${token}`);

  ws.onmessage = onMessage;
  ws.onopen = onOpen;
  ws.onclose = onClose;
  ws.onerror = onError;
}

const getWebSocketUrlFromCurrentLocation = () => {
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  return `${wsProtocol}//${window.location.host}`;
}

const onMessage = (event) => {
  try {
    const message = JSON.parse(event.data);
    eventHandler(message);
  } catch (err) {}
};

const onOpen = () => {
  if(settings.developerMode === true) {
    console.log('Connection established.');
  }
};

const onError = () => {};

const onClose = (event) => {
  if(event.code !== 1000){
    if(settings.developerMode === true) {
      console.log(`WebSocket connection closed with code: ${event.code}.`);
    }
    // try to reconnect
    setTimeout(() => { connect(); }, AUTO_RECONNECT_INTERVAL);
  }
};

const showNotification = (title, body, requireInteraction = false) => {
  let msg = new Notification(title, {
    body: body,
    tag: 'dashboard',
    requireInteraction: requireInteraction
  });

  msg.addEventListener("click", (event) => {
    parent.focus();
    event.target.close();
  });
}

const eventHandler = ({ event, payload }) => {
  switch(event){
    case THEME_INSTALLED:
      const fileName = payload;
      store.dispatch(installReceive());
      showNotification(messages.settings_theme, messages.themeInstalled);
      break;
    case ORDER_CREATED:
      const order = payload;
      store.dispatch(fetchOrders());
      showNotification(`${messages.order} #${order.number}`, `${order.shipping_address.full_name}, ${order.shipping_address.city}`, true);
      break;
    default:
      break;
  }
}
<|endoftext|>


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

router.get('/', global.apiCall, function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/announcements/get/:date', global.apiCall, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	global.knex.select('*').from('planner_announcements').limit(1).where({
		date: req.params.date
	}).then(function (data) {
		if (data.length == 0) {
			res.json({
				status: "ok",
				announcement: null
			});
		} else {
			res.json({
				status: "ok",
				announcement: data[0]
			});
		}
	}).catch(function(error) {
		console.error("DB ERROR!");
		console.error(error);
		res.json({
			status: "error",
			error: "Database error"
		});
	});
});

router.get('/fridays/get/:date', global.apiCall, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	global.knex.select('*').from('planner_fridays').limit(1).where({
		date: req.params.date
	}).then(function (data) {
		if (data.length == 0) {
			res.json({
				status: "ok",
				friday: null
			});
		} else {
			res.json({
				status: "ok",
				friday: data[0]
			});
		}
	}).catch(function(error) {
		console.error("DB ERROR!");
		console.error(error);
		res.json({
			status: "error",
			error: "Database error"
		});
	});
});

router.get('/events/get/:date/:section_index', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	if (req.params.section_index == undefined || parseInt(req.params.section_index) == NaN) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	knex("planner_events").select("*").where({
		userId: res.locals.user.id,
		date: req.params.date,
		sectionIndex: req.params.section_index
	}).then(function(obj) {
		res.json({
			status: "ok",
			date: req.params.date,
			events: obj
		});
	}).catch(function() {
		res.json({
			status: "error",
			date: req.params.date,
			error: "Unknown database error"
		});
	});
});

router.post('/events/post/', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	if (req.body.subjectIndex == undefined || parseInt(req.body.subjectIndex) == NaN) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	if (req.body.text == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid text parameter!"
		});
		return;
	}
	if (req.body.done == undefined || parseInt(req.body.done) == NaN || (parseInt(req.body.done) != 0 && parseInt(req.body.done) != 1)) {
		res.json({
			status: "error",
			error: "Missing or invalid done parameter!"
		});
		return;
	}
	knex("planner_events").select("*").where({
		userId: res.locals.user.id,
		date: req.body.date,
		sectionIndex: req.body.subjectIndex
	}).then(function(obj) {
		if (obj.length == 0) {
			// no event, insert it
			knex("planner_events").insert({
				sectionIndex: req.body.subjectIndex,
				userId: res.locals.user.id,
				date: req.body.date,
				text: req.body.text,
				done: req.body.done
			}).then(function() {
				res.json({
					status: "ok"
				});
			});/*.catch(function() {
				res.json({
					status: "error",
					error: "Database error"
				});
			});*/
		} else {
			// an event! update it
			knex("planner_events").where({ eventId: obj[0].eventId }).update({
				text: req.body.text,
				done: req.body.done
			}).then(function() {
				res.json({
					status: "ok"
				});
			});/*.catch(function() {
				res.json({
					status: "error",
					error: "Database error"
				});
			});*/
		}
	});/*.catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error"
		});
	});*/
});

router.get('/sections/get/', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	knex("planner_sections").select("*").where({
		userId: res.locals.user.id
	}).then(function(obj) {
		res.json({
			status: "ok",
			sections: obj
		});
	});
});

router.post('/sections/add', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.sectionName == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid section name parameter!"
		});
		return;
	}
	knex("planner_sections").select("*").where({
		userId: res.locals.user.id
	}).then(function(obj) {
		knex("planner_sections").insert({
			sectionIndex: obj[obj.length - 1].sectionIndex,
			name: req.body.sectionName,
			userId: res.locals.user.id
		}).then(function() {
			res.json({
				status: "ok",
				newIndex: obj.length
			});
		}).catch(function() {
			res.json({
				status: "error",
				error: "Unknown database error."
			});
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

router.post('/sections/remove', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.sectionIndex == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	// use a transaction for consistency
	knex.transaction(function(trx) {
		return trx("planner_sections").select("*").where({
			userId: res.locals.user.id,
			sectionIndex: req.body.sectionIndex
		}).then(function(obj) {
			var itm = obj[0];
			return trx("planner_sections").where({
				sectionGid: itm.sectionGid
			}).update({
				sectionIndex: itm.sectionIndex * -1, // TODO: change this to del after beta and code path is tested
				userId: itm.userId * -1
			}).then(function() {
				return trx("planner_events").where({
					sectionIndex: itm.sectionIndex, // TODO: see above comment
					userId: itm.userId
				}).update({
					sectionIndex: itm.sectionIndex * -1,
					userId: itm.userId * -1
				});
			});
		});
	}).then(function() {
		res.json({
			status: "ok"
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

module.exports = router;<commit_msg>Fix duplicate creation<commit_after>var express = require('express');
var router = express.Router();

router.get('/', global.apiCall, function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/announcements/get/:date', global.apiCall, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	global.knex.select('*').from('planner_announcements').limit(1).where({
		date: req.params.date
	}).then(function (data) {
		if (data.length == 0) {
			res.json({
				status: "ok",
				announcement: null
			});
		} else {
			res.json({
				status: "ok",
				announcement: data[0]
			});
		}
	}).catch(function(error) {
		console.error("DB ERROR!");
		console.error(error);
		res.json({
			status: "error",
			error: "Database error"
		});
	});
});

router.get('/fridays/get/:date', global.apiCall, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	global.knex.select('*').from('planner_fridays').limit(1).where({
		date: req.params.date
	}).then(function (data) {
		if (data.length == 0) {
			res.json({
				status: "ok",
				friday: null
			});
		} else {
			res.json({
				status: "ok",
				friday: data[0]
			});
		}
	}).catch(function(error) {
		console.error("DB ERROR!");
		console.error(error);
		res.json({
			status: "error",
			error: "Database error"
		});
	});
});

router.get('/events/get/:date/:section_index', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.params.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	if (req.params.section_index == undefined || parseInt(req.params.section_index) == NaN) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	knex("planner_events").select("*").where({
		userId: res.locals.user.id,
		date: req.params.date,
		sectionIndex: req.params.section_index
	}).then(function(obj) {
		res.json({
			status: "ok",
			date: req.params.date,
			events: obj
		});
	}).catch(function() {
		res.json({
			status: "error",
			date: req.params.date,
			error: "Unknown database error"
		});
	});
});

router.post('/events/post/', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.date == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid date parameter!"
		});
		return;
	}
	if (req.body.subjectIndex == undefined || parseInt(req.body.subjectIndex) == NaN) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	if (req.body.text == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid text parameter!"
		});
		return;
	}
	if (req.body.done == undefined || parseInt(req.body.done) == NaN || (parseInt(req.body.done) != 0 && parseInt(req.body.done) != 1)) {
		res.json({
			status: "error",
			error: "Missing or invalid done parameter!"
		});
		return;
	}
	knex("planner_events").select("*").where({
		userId: res.locals.user.id,
		date: req.body.date,
		sectionIndex: req.body.subjectIndex
	}).then(function(obj) {
		if (obj.length == 0) {
			// no event, insert it
			knex("planner_events").insert({
				sectionIndex: req.body.subjectIndex,
				userId: res.locals.user.id,
				date: req.body.date,
				text: req.body.text,
				done: req.body.done
			}).then(function() {
				res.json({
					status: "ok"
				});
			});/*.catch(function() {
				res.json({
					status: "error",
					error: "Database error"
				});
			});*/
		} else {
			// an event! update it
			knex("planner_events").where({ eventId: obj[0].eventId }).update({
				text: req.body.text,
				done: req.body.done
			}).then(function() {
				res.json({
					status: "ok"
				});
			});/*.catch(function() {
				res.json({
					status: "error",
					error: "Database error"
				});
			});*/
		}
	});/*.catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error"
		});
	});*/
});

router.get('/sections/get/', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	knex("planner_sections").select("*").where({
		userId: res.locals.user.id
	}).then(function(obj) {
		res.json({
			status: "ok",
			sections: obj
		});
	});
});

router.post('/sections/add', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.sectionName == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid section name parameter!"
		});
		return;
	}
	knex("planner_sections").select("*").where({
		userId: res.locals.user.id
	}).then(function(obj) {
		knex("planner_sections").insert({
			sectionIndex: obj[obj.length - 1].sectionIndex + 1,
			name: req.body.sectionName,
			userId: res.locals.user.id
		}).then(function() {
			res.json({
				status: "ok",
				newIndex: obj.length
			});
		}).catch(function() {
			res.json({
				status: "error",
				error: "Unknown database error."
			});
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

router.post('/sections/remove', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.body.sectionIndex == undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid section index parameter!"
		});
		return;
	}
	// use a transaction for consistency
	knex.transaction(function(trx) {
		return trx("planner_sections").select("*").where({
			userId: res.locals.user.id,
			sectionIndex: req.body.sectionIndex
		}).then(function(obj) {
			var itm = obj[0];
			return trx("planner_sections").where({
				sectionGid: itm.sectionGid
			}).update({
				sectionIndex: itm.sectionIndex * -1, // TODO: change this to del after beta and code path is tested
				userId: itm.userId * -1
			}).then(function() {
				return trx("planner_events").where({
					sectionIndex: itm.sectionIndex, // TODO: see above comment
					userId: itm.userId
				}).update({
					sectionIndex: itm.sectionIndex * -1,
					userId: itm.userId * -1
				});
			});
		});
	}).then(function() {
		res.json({
			status: "ok"
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

module.exports = router;<|endoftext|>


<commit_before>/*
 * Copyright 2013 BlackBerry Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var fs = require("fs"),
    cp = require("child_process"),
    os = require("os"),
    util = require("util"),
    projectUtil = require("../lib/util"),
    path = require("path"),
    isWinXp = (os.platform() === "win32") && (os.release().split(".")[0] === "5"),
    winXpPath = process.env.HOMEPATH + "\\Local Settings\\Application Data\\Research In Motion",
    osPaths = {
        "win32": isWinXp ? path.resolve(winXpPath) : process.env.LOCALAPPDATA + "\\Research In Motion",
        "darwin": process.env.HOME + "/Library/Research\ In\ Motion",
        "linux": process.env.HOME + "/.rim"
    },
    osPath = path.normalize(osPaths[os.platform()]),
    bbtoolsPath = path.resolve(__dirname + "/../../cordova-blackberry/bin/dependencies/bb-tools/bin/"),
    keytoolCmd = "blackberry-keytool" + (projectUtil.isWindows() ? ".bat" : ""),
    signerCmd = "blackberry-signer" + (projectUtil.isWindows() ? ".bat" : "");

function checkForBarSigner() {
    var filepath = path.join(osPath, "barsigner.csk");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function checkForBBIDToken() {
    var filepath = path.join(osPath, "bbidtoken.csk");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function checkForDevCert() {
    var filepath = path.join(osPath, "author.p12");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function getState(callback) {
    var state = {
        bbidToken: checkForBBIDToken(),
        barSigner: checkForBarSigner(),
        devCert: checkForDevCert()
    };
    callback(undefined, state);
}

function addSigningKey(keyPath, callback) {
    // copy to OS location
    try {
        projectUtil.copyFile(path.resolve(keyPath), osPath);
    } catch (e) {
        callback(e, e.message);
    }
    callback();
}

function createDevCertificate(keystorePass, companyName, callback) {
    // create author.p12, proper placement is done by keytool
    var execStr = [keytoolCmd,
        "-genkeypair",
        "-storepass",
        keystorePass,
        '-dname',
        '"cn=' + companyName + '"'
    ].join(" ");

    // run command
    cp.exec(execStr, {
        cwd: bbtoolsPath
    }, callback);
}

function linkSigningKeys(barSignerPass, bbidTokenPass, callback) {
    // link barsigner.csk to bbidtoken.csk
    var execStr = [signerCmd,
        "-linkcsk",
        "-oldcskpass",
        barSignerPass,
        "-bbidcskpass",
        bbidTokenPass
    ].join(" ");

    // run command
    cp.exec(execStr, {
        cwd: bbtoolsPath
    }, callback);
}

module.exports = {

    get: function (req, res) {
        var projectPath = req.query.path,
            cmd = req.query.cmd,
            args = req.query.args,
            callback = function (error, stdout, stderr) {
                res.send(200, {
                    success: !error,
                    code: error ? error.code : 0,
                    cmd: cmd,
                    args: args,
                    stdout: stdout,
                    stderr: stderr
                });
            };

            if (cmd === "state") {
                getState(callback);
            } else if (cmd === "add") {
                addSigningKey(req.query.path, callback);
            } else if (cmd === "createDevCert") {
                createDevCertificate(req.query.keystorePass, req.query.companyName, callback);
            } else if (cmd === "linkSigningKeys") {
                addSigningKey(req.query.path, function () {
                    linkSigningKeys(req.query.barSignerPass, req.query.bbidTokenPass, callback);
                });
            } else {
                // Unsupported
                callback({code: -1}, "", "Unsupported command");
            }
    }
};
<commit_msg>Win: Use USERPROFILE instead of HOMEPATH<commit_after>/*
 * Copyright 2013 BlackBerry Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var fs = require("fs"),
    cp = require("child_process"),
    os = require("os"),
    util = require("util"),
    projectUtil = require("../lib/util"),
    path = require("path"),
    isWinXp = (os.platform() === "win32") && (os.release().split(".")[0] === "5"),
    winXpPath = process.env.USERPROFILE + "\\Local Settings\\Application Data\\Research In Motion",
    osPaths = {
        "win32": isWinXp ? path.resolve(winXpPath) : process.env.LOCALAPPDATA + "\\Research In Motion",
        "darwin": process.env.HOME + "/Library/Research\ In\ Motion",
        "linux": process.env.HOME + "/.rim"
    },
    osPath = path.normalize(osPaths[os.platform()]),
    bbtoolsPath = path.resolve(__dirname + "/../../cordova-blackberry/bin/dependencies/bb-tools/bin/"),
    keytoolCmd = "blackberry-keytool" + (projectUtil.isWindows() ? ".bat" : ""),
    signerCmd = "blackberry-signer" + (projectUtil.isWindows() ? ".bat" : "");

function checkForBarSigner() {
    var filepath = path.join(osPath, "barsigner.csk");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function checkForBBIDToken() {
    var filepath = path.join(osPath, "bbidtoken.csk");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function checkForDevCert() {
    var filepath = path.join(osPath, "author.p12");
    return fs.existsSync(filepath) ? filepath : undefined;
}

function getState(callback) {
    var state = {
        bbidToken: checkForBBIDToken(),
        barSigner: checkForBarSigner(),
        devCert: checkForDevCert()
    };
    callback(undefined, state);
}

function addSigningKey(keyPath, callback) {
    // copy to OS location
    try {
        projectUtil.copyFile(path.resolve(keyPath), osPath);
    } catch (e) {
        callback(e, e.message);
    }
    callback();
}

function createDevCertificate(keystorePass, companyName, callback) {
    // create author.p12, proper placement is done by keytool
    var execStr = [keytoolCmd,
        "-genkeypair",
        "-storepass",
        keystorePass,
        '-dname',
        '"cn=' + companyName + '"'
    ].join(" ");

    // run command
    cp.exec(execStr, {
        cwd: bbtoolsPath
    }, callback);
}

function linkSigningKeys(barSignerPass, bbidTokenPass, callback) {
    // link barsigner.csk to bbidtoken.csk
    var execStr = [signerCmd,
        "-linkcsk",
        "-oldcskpass",
        barSignerPass,
        "-bbidcskpass",
        bbidTokenPass
    ].join(" ");

    // run command
    cp.exec(execStr, {
        cwd: bbtoolsPath
    }, callback);
}

module.exports = {

    get: function (req, res) {
        var projectPath = req.query.path,
            cmd = req.query.cmd,
            args = req.query.args,
            callback = function (error, stdout, stderr) {
                res.send(200, {
                    success: !error,
                    code: error ? error.code : 0,
                    cmd: cmd,
                    args: args,
                    stdout: stdout,
                    stderr: stderr
                });
            };

            if (cmd === "state") {
                getState(callback);
            } else if (cmd === "add") {
                addSigningKey(req.query.path, callback);
            } else if (cmd === "createDevCert") {
                createDevCertificate(req.query.keystorePass, req.query.companyName, callback);
            } else if (cmd === "linkSigningKeys") {
                addSigningKey(req.query.path, function () {
                    linkSigningKeys(req.query.barSignerPass, req.query.bbidTokenPass, callback);
                });
            } else {
                // Unsupported
                callback({code: -1}, "", "Unsupported command");
            }
    }
};
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const router = express.Router();
const M2X = require('m2x');
const vincenty = require('node-vincenty');
const m2x = new M2X(process.env.M2X_KEY);

const deviceID = ( process.env.M2X_DEVICE_ID ) ? process.env.M2X_DEVICE_ID : '8b492694122cc040401c2d4f9a6a3b56';
let masterPoint = {
    name: 'Master Point',
    // TEST (SACRED HEARTS CAFETERIA) 21.285471, -157.807362
    lat: 21.2858534,
    lon: -157.8064349,
    active: false,
    createdAt: Date.now(),
  };
let gameCounter = 0;
let totalCounter = 0;
// NOTE: TIMES SUPERMARKET
// const testPoint = {
//     name: 'Test Point',
//     lat: 21.286615,
//     lon: -157.807592,
//     active: false,
//     createdAt: Date.now(),
//   }

router.route('/')
  // GET the current check-point stream status
  .get((req, res) => {
    m2x.devices.values(deviceID, "check-points", (values) => {
      res.send(values);
    });
  })
  // Create a new game state
  .post((req, res) => {
    let payload = {
      value: JSON.stringify([
        {
          id: 1,
          name: 'Sacred Hearts',
          clue: 'The marker is on the third table to the right of the room, by the vending machine',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 2,
          name: 'Manoa Innovatation Center',
          clue: 'The marker is in the cafeteria',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 3,
          name: 'University of Hawaii at Manoa',
          clue: 'The marker is at a Catholic School',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 4,
          name: 'Sacred Hearts',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          clue: 'The marker is on Oahu',
          createdAt: Date.now(),
        }, {
          id: 5,
          name: 'Sacred Hearts',
          clue: 'The marker is on NOT on the moon',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }
      ])
    };

    m2x.devices.setStreamValue(deviceID, "check-points", payload, (values) => {
      res.send(values);
    });
  });

router.route('/capture/lat/:lat/long/:lon')
  // GET capture route
  .get((req, res) => {
    const lat = req.params.lat;
    const lon = req.params.lon;
    gameCounter++;
    totalCounter++;

    vincenty.distVincenty(lat, lon, masterPoint.lat, masterPoint.lon, (distance, initialBearing, finalBearing) => {
      // NOTE: 15m capture range.
      if( distance < 15 && distance >= 0 ){
        // TODO: DO SOMETHING BETTER
        res.send('GOTTEM! It took a total of ' + gameCounter + ' total attempts since last found.');
        gameCounter = 0;
      } else {
        res.send('NOPE! TRY AGAIN');
      }
    });
  });

router.route('/reset')
  // GET checks server master point for win condition
  .get((req, res) => {
    res.send('stub');
  });

router.route('/lat/:lat/long/:lon')
  // GET the current check-point id's status - if it's not activated - then active that checkpoint
  .get((req, res) => {

    const lat = req.params.lat;
    const lon = req.params.lon;
    gameCounter++;
    totalCounter++;
    let payload = {
      value: JSON.stringify(
        {
          // id: 'stub',
          lat: req.params.lat,
          lon: req.params.lon,
          value: 1, // NOTE: Maybe unnecessary if using a gameCounter on server.
          timestamp: Date.now(),
        }
      )
    };

    m2x.devices.setStreamValue(deviceID, "check-points", payload, (result) => {
      console.log('result',result.json);
    });
    vincenty.distVincenty(lat, lon, masterPoint.lat, masterPoint.lon, (distance, initialBearing, finalBearing) => {
        res.json({
          distance,
          finalBearing,
        });
    });
  });

module.exports = router;
<commit_msg>Set stream name to a variable.<commit_after>'use strict';

const express = require('express');
const router = express.Router();
const M2X = require('m2x');
const vincenty = require('node-vincenty');
const m2x = new M2X(process.env.M2X_KEY);
const streamName = 'check-points';

const deviceID = ( process.env.M2X_DEVICE_ID ) ? process.env.M2X_DEVICE_ID : '8b492694122cc040401c2d4f9a6a3b56';
let masterPoint = {
    name: 'Master Point',
    // TEST (SACRED HEARTS CAFETERIA) 21.285471, -157.807362
    lat: 21.2858534,
    lon: -157.8064349,
    active: false,
    createdAt: Date.now(),
  };
let gameCounter = 0;
let totalCounter = 0;
// NOTE: TIMES SUPERMARKET
// const testPoint = {
//     name: 'Test Point',
//     lat: 21.286615,
//     lon: -157.807592,
//     active: false,
//     createdAt: Date.now(),
//   }

router.route('/')
  // GET the current check-point stream status
  .get((req, res) => {
    m2x.devices.values(deviceID, streamName, (values) => {
      res.send(values);
    });
  })
  // Create a new game state
  .post((req, res) => {
    let payload = {
      value: JSON.stringify([
        {
          id: 1,
          name: 'Sacred Hearts',
          clue: 'The marker is on the third table to the right of the room, by the vending machine',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 2,
          name: 'Manoa Innovatation Center',
          clue: 'The marker is in the cafeteria',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 3,
          name: 'University of Hawaii at Manoa',
          clue: 'The marker is at a Catholic School',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }, {
          id: 4,
          name: 'Sacred Hearts',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          clue: 'The marker is on Oahu',
          createdAt: Date.now(),
        }, {
          id: 5,
          name: 'Sacred Hearts',
          clue: 'The marker is on NOT on the moon',
          lat: 21.2858534,
          lon: -157.8064349,
          angle: 123,
          createdAt: Date.now(),
        }
      ])
    };

    m2x.devices.setStreamValue(deviceID, streamName, payload, (values) => {
      res.send(values);
    });
  });

router.route('/capture/lat/:lat/long/:lon')
  // GET capture route
  .get((req, res) => {
    const lat = req.params.lat;
    const lon = req.params.lon;
    gameCounter++;
    totalCounter++;

    vincenty.distVincenty(lat, lon, masterPoint.lat, masterPoint.lon, (distance, initialBearing, finalBearing) => {
      // NOTE: 15m capture range.
      if( distance < 15 && distance >= 0 ){
        // TODO: DO SOMETHING BETTER
        res.send('GOTTEM! It took a total of ' + gameCounter + ' total attempts since last found.');
        gameCounter = 0;
      } else {
        res.send('NOPE! TRY AGAIN');
      }
    });
  });

router.route('/reset')
  // GET checks server master point for win condition
  .get((req, res) => {
    res.send('stub');
  });

router.route('/lat/:lat/long/:lon')
  // GET the current check-point id's status - if it's not activated - then active that checkpoint
  .get((req, res) => {

    const lat = req.params.lat;
    const lon = req.params.lon;
    gameCounter++;
    totalCounter++;
    let payload = {
      value: JSON.stringify(
        {
          // id: 'stub',
          lat: req.params.lat,
          lon: req.params.lon,
          value: 1, // NOTE: Maybe unnecessary if using a gameCounter on server.
          timestamp: Date.now(),
        }
      )
    };

    m2x.devices.setStreamValue(deviceID, streamName, payload, (result) => {
      console.log('result',result.json);
    });
    vincenty.distVincenty(lat, lon, masterPoint.lat, masterPoint.lon, (distance, initialBearing, finalBearing) => {
        res.json({
          distance,
          finalBearing,
        });
    });
  });

module.exports = router;
<|endoftext|>