<commit_before>Function.prototype.getName = function () {
    return this.name || this.toString().split("(")[0].replace(/function\s*/, "");
};

if (!Object.prototype.watch) {
    Object.defineProperty(Object.prototype, "watch", {
        enumerable: false,
        configurable: true,
        writable: false,
        value: function (prop, handler) {
            var old = this[prop];
            var cur = old;
            var getter = function () {
                return cur;
            };
            var setter = function (val) {
                old = cur;
                cur = handler.call(this, prop, old, val);
                return cur;
            };
            if (delete this[prop]) {
                Object.defineProperty(this, prop, {
                    get: getter,
                    set: setter,
                    enumerable: true,
                    configurable: true
                });
            }
        }
    });
}

function setUpApp(bootstrapApp) {

    var sockJSConnection;

    var jwt = getJwt();

    if (jwt) {
        cleanUrl();
        if (!sessionStorage.token) {
            sessionStorage.token = jwt;
        }
        if (sessionStorage.role === appConfig.anonymousRole) {
            delete sessionStorage.role;
        }
        connect({
            jwt: sessionStorage.token
        });
    } else {
        if (appConfig.allowAnonymous) {
            sessionStorage.role = appConfig.anonymousRole;
            connect({});
        } else {
            if (appConfig.mockRole) {
                window.open(appConfig.authService + "/token?referer=" + location.href + "&mock=" + appConfig.mockRole, "_self");
            } else {
                window.open(appConfig.authService + "/token?referer=" + location.href, "_self");
            }
        }
    }

    function attemptConnect(headers, attempt) {

        sockJSConnection = new SockJS(appConfig.webService + "/connect", null, {
            transports: appConfig.sockJsConnectionType
        });

        window.stompClient = Stomp.over(sockJSConnection);

        if (!appConfig.stompDebug) {
            window.stompClient.debug = null;
        }

        var wait = angular.isUndefined(angular.element(document).scope()) ? 500 : 5000;

        window.stompClient.connect(headers, function () {
            bootstrapApp();
        }, function () {
            if (attempt < 3) {
                setTimeout(function () {
                    attempt++;
                    attemptConnect(headers, attempt);
                }, wait);
            } else {
                bootstrapApp();
            }
        });

    };

    function connect(headers) {
        angular.element(document).ready(function () {
            attemptConnect(headers, 0);
        });
    };

    function getQueryVariable(variable) {
      var value;
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if(pair[0] === variable){
          value = pair[1];
        }
      }
      return value;
    }

    function getJwt() {
        if (sessionStorage.token) {
            return sessionStorage.token;
        }
        return getQueryVariable('jwt');
    };

    function cleanUrl() {
      var uri = location.toString();
      if (uri.indexOf("?") > 0) {
          var clean_uri = uri.substring(0, uri.indexOf("?"));
          history.replaceState({}, document.title, clean_uri);
      }
    }

}
<commit_msg>clear only jwt from url<commit_after>Function.prototype.getName = function () {
    return this.name || this.toString().split("(")[0].replace(/function\s*/, "");
};

if (!Object.prototype.watch) {
    Object.defineProperty(Object.prototype, "watch", {
        enumerable: false,
        configurable: true,
        writable: false,
        value: function (prop, handler) {
            var old = this[prop];
            var cur = old;
            var getter = function () {
                return cur;
            };
            var setter = function (val) {
                old = cur;
                cur = handler.call(this, prop, old, val);
                return cur;
            };
            if (delete this[prop]) {
                Object.defineProperty(this, prop, {
                    get: getter,
                    set: setter,
                    enumerable: true,
                    configurable: true
                });
            }
        }
    });
}

function setUpApp(bootstrapApp) {

    var sockJSConnection;

    var jwt = getJwt();

    if (jwt) {
        cleanUrl();
        if (!sessionStorage.token) {
            sessionStorage.token = jwt;
        }
        if (sessionStorage.role === appConfig.anonymousRole) {
            delete sessionStorage.role;
        }
        connect({
            jwt: sessionStorage.token
        });
    } else {
        if (appConfig.allowAnonymous) {
            sessionStorage.role = appConfig.anonymousRole;
            connect({});
        } else {
            if (appConfig.mockRole) {
                window.open(appConfig.authService + "/token?referer=" + location.href + "&mock=" + appConfig.mockRole, "_self");
            } else {
                window.open(appConfig.authService + "/token?referer=" + location.href, "_self");
            }
        }
    }

    function attemptConnect(headers, attempt) {

        sockJSConnection = new SockJS(appConfig.webService + "/connect", null, {
            transports: appConfig.sockJsConnectionType
        });

        window.stompClient = Stomp.over(sockJSConnection);

        if (!appConfig.stompDebug) {
            window.stompClient.debug = null;
        }

        var wait = angular.isUndefined(angular.element(document).scope()) ? 500 : 5000;

        window.stompClient.connect(headers, function () {
            bootstrapApp();
        }, function () {
            if (attempt < 3) {
                setTimeout(function () {
                    attempt++;
                    attemptConnect(headers, attempt);
                }, wait);
            } else {
                bootstrapApp();
            }
        });

    };

    function connect(headers) {
        angular.element(document).ready(function () {
            attemptConnect(headers, 0);
        });
    };

    function getQueryVariable(variable) {
      var value;
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if(pair[0] === variable){
          value = pair[1];
        }
      }
      return value;
    }

    function getJwt() {
        if (sessionStorage.token) {
            return sessionStorage.token;
        }
        return getQueryVariable('jwt');
    }

    function cleanUrl() {
      var uri = location.toString();
      var jwtQuery = "jwt=" + getQueryVariable('jwt');
      history.replaceState({}, document.title, uri.replace(jwtQuery, ""));
    }

}
<|endoftext|>


<commit_before>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief FoxxService and FoxxContext types
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2015 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Alan Plum
/// @author Copyright 2015, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

const _ = require('lodash');
const internal = require('internal');
const assert = require('assert');
const Module = require('module');
const path = require('path');
const fs = require('fs');
const parameterTypes = require('@arangodb/foxx/manager-utils').parameterTypes;
const getReadableName = require('@arangodb/foxx/manager-utils').getReadableName;
const $_MODULE_ROOT = Symbol.for('@arangodb/module.root');
const $_MODULE_CONTEXT = Symbol.for('@arangodb/module.context');

const APP_PATH = internal.appPath ? path.resolve(internal.appPath) : undefined;
const STARTUP_PATH = internal.startupPath ? path.resolve(internal.startupPath) : undefined;
const DEV_APP_PATH = internal.devAppPath ? path.resolve(internal.devAppPath) : undefined;

class FoxxContext {
  constructor(service) {
    this.basePath = path.resolve(service.root, service.path);
    this.comments = [];
    Object.defineProperty(this, '_service', {
      get() {
        return service;
      }
    });
  }

  fileName(filename) {
    return fs.safeJoin(this._prefix, filename);
  }

  file(filename, encoding) {
    return fs.readFileSync(this.fileName(filename), encoding);
  }

  foxxFilename(filename) {
    return this.fileName(filename);
  }

  path(name) {
    return path.join(this._prefix, name);
  }

  collectionName(name) {
    let fqn = (
      this.collectionPrefix
      + name.replace(/[^a-z0-9]/ig, '_').replace(/(^_+|_+$)/g, '').substr(0, 64)
    );
    if (!fqn.length) {
      throw new Error(`Cannot derive collection name from "${name}"`);
    }
    return fqn;
  }

  collection(name) {
    return internal.db._collection(this.collectionName(name));
  }

  get _prefix() {
    return this.basePath;
  }

  get baseUrl() {
    return `/_db/${encodeURIComponent(internal.db._name())}/${this._service.mount.slice(1)}`;
  }

  get collectionPrefix() {
    return this._service.collectionPrefix;
  }

  get mount() {
    return this._service.mount;
  }

  get name() {
    return this._service.name;
  }

  get version() {
    return this._service.version;
  }

  get manifest() {
    return this._service.manifest;
  }

  get isDevelopment() {
    return this._service.isDevelopment;
  }

  get isProduction() {
    return !this.isDevelopment;
  }

  get options() {
    return this._service.options;
  }

  get configuration() {
    return this._service.configuration;
  }

  get dependencies() {
    return this._service.dependencies;
  }
}

Object.defineProperties(FoxxContext.prototype, {
  comment: {
    value: function (str) {
      this.comments.push(str);
    }
  },
  clearComments: {
    value: function () {
      this.comments.splice(0, this.comments.length);
    }
  }
});

function createConfiguration(definitions) {
  const config = {};
  Object.keys(definitions).forEach(function (name) {
    const def = definitions[name];
    if (def.default !== undefined) {
      config[name] = def.default;
    }
  });
  return config;
}

function createDependencies(definitions, options) {
  const deps = {};
  Object.keys(definitions).forEach(function (name) {
    Object.defineProperty(deps, name, {
      configurable: true,
      enumerable: true,
      get() {
        const mount = options[name];
        return mount ? require('@arangodb/foxx').getExports(mount) : null;
      }
    });
  });
  return deps;
}

class FoxxService {
  constructor(data) {
    assert(data, 'no arguments');
    assert(data.mount, 'mount path required');
    assert(data.path, `local path required for app "${data.mount}"`);
    assert(data.manifest, `called without manifest for app "${data.mount}"`);

    // mount paths always start with a slash
    this.mount = data.mount;
    this.path = data.path;
    this.isDevelopment = data.isDevelopment || false;

    this.manifest = data.manifest;
    if (!this.manifest.dependencies) {
      this.manifest.dependencies = {};
    }
    if (!this.manifest.configuration) {
      this.manifest.configuration = {};
    }

    this.options = data.options;
    if (!this.options.configuration) {
      this.options.configuration = {};
    }
    if (!this.options.dependencies) {
      this.options.dependencies = {};
    }

    this.configuration = createConfiguration(this.manifest.configuration);
    this.dependencies = createDependencies(this.manifest.dependencies, this.options.dependencies);
    let warnings = this.applyConfiguration(this.options.configuration);
    if (warnings.length) {
      console.warnLines(
        `Stored configuration for app "${data.mount}" has errors:\n${warnings.join('\n  ')}`
      );
    }
    // don't need to apply deps from options -- they work automatically

    if (this.manifest.thumbnail) {
      let thumb = path.resolve(this.root, this.path, this.manifest.thumbnail);
      try {
        this.thumbnail = fs.read64(thumb);
      } catch (e) {
        this.thumbnail = null;
        /*
        console.warnLines(
          `Cannot read thumbnail "${thumb}" for app "${data.mount}": ${e.stack}`
        );
        */
      }
    } else {
      this.thumbnail = null;
    }

    this.requireCache = {};
    const lib = this.manifest.lib || '.';
    const moduleRoot = path.resolve(this.root, this.path, lib);
    const foxxConsole = require('@arangodb/foxx/console')(this.mount);
    this.main = new Module(`foxx:${data.mount}`);
    this.main.filename = path.resolve(moduleRoot, '.foxx');
    this.main[$_MODULE_ROOT] = moduleRoot;
    this.main[$_MODULE_CONTEXT].console = foxxConsole;
    this.main.require.cache = this.requireCache;
    this.main.context = new FoxxContext(this);
  }

  applyConfiguration(config) {
    const definitions = this.manifest.configuration;
    const warnings = [];

    _.each(config, function (rawValue, name) {
      const def = definitions[name];
      if (!def) {
        warnings.push(`Unexpected option "${name}"`);
        return;
      }

      if (def.required === false && (rawValue === undefined || rawValue === null || rawValue === '')) {
        delete this.options.configuration[name];
        this.configuration[name] = def.default;
        return;
      }

      const validate = parameterTypes[def.type];
      let parsedValue = rawValue;
      let warning;

      if (validate.isJoi) {
        let result = validate.required().validate(rawValue);
        if (result.error) {
          warning = result.error.message.replace(/^"value"/, `"${name}"`);
        } else {
          parsedValue = result.value;
        }
      } else {
        try {
          parsedValue = validate(rawValue);
        } catch (e) {
          warning = `"${name}": ${e.message}`;
        }
      }

      if (warning) {
        warnings.push(warning);
      } else {
        this.options.configuration[name] = rawValue;
        this.configuration[name] = parsedValue;
      }
    }, this);

    return warnings;
  }

  applyDependencies(deps) {
    var definitions = this.manifest.dependencies;
    var warnings = [];

    _.each(deps, function (mount, name) {
      const dfn = definitions[name];
      if (!dfn) {
        warnings.push(`Unexpected dependency "${name}"`);
      } else {
        this.options.dependencies[name] = mount;
      }
    }, this);

    return warnings;
  }

  _PRINT(context) {
    context.output += `[FoxxService "${this.name}" (${this.version}) on ${this.mount}]`;
  }

  toJSON() {
    const result = {
      name: this.name,
      version: this.version,
      manifest: this.manifest,
      path: this.path,
      options: this.options,
      mount: this.mount,
      root: this.root,
      isSystem: this.isSystem,
      isDevelopment: this.isDevelopment
    };
    if (this.error) {
      result.error = this.error;
    }
    if (this.manifest.author) {
      result.author = this.manifest.author;
    }
    if (this.manifest.description) {
      result.description = this.manifest.description;
    }
    if (this.thumbnail) {
      result.thumbnail = this.thumbnail;
    }
    return result;
  }

  simpleJSON() {
    return {
      name: this.name,
      version: this.version,
      mount: this.mount
    };
  }

  development(isDevelopment) {
    this.isDevelopment = isDevelopment;
  }

  getConfiguration(simple) {
    var config = {};
    var definitions = this.manifest.configuration;
    var options = this.options.configuration;
    _.each(definitions, function (dfn, name) {
      var value = options[name] === undefined ? dfn.default : options[name];
      config[name] = simple ? value : _.extend({}, dfn, {
        title: getReadableName(name),
        current: value
      });
    });
    return config;
  }

  getDependencies(simple) {
    var deps = {};
    var definitions = this.manifest.dependencies;
    var options = this.options.dependencies;
    _.each(definitions, function (dfn, name) {
      deps[name] = simple ? options[name] : {
        definition: dfn,
        title: getReadableName(name),
        current: options[name]
      };
    });
    return deps;
  }

  needsConfiguration() {
    var config = this.getConfiguration();
    var deps = this.getDependencies();
    return _.any(config, function (cfg) {
      return cfg.current === undefined && cfg.required !== false;
    }) || _.any(deps, function (dep) {
      return dep.current === undefined && dep.definition.required !== false;
    });
  }

  run(filename, options) {
    options = options || {};
    filename = path.resolve(this.main[$_MODULE_CONTEXT].__dirname, filename);

    var module = new Module(filename, this.main);
    module[$_MODULE_CONTEXT].console = this.main[$_MODULE_CONTEXT].console;
    module.context = _.extend(
      new FoxxContext(this),
      this.main.context,
      options.foxxContext
    );

    if (options.preprocess) {
      module.preprocess = options.preprocess;
    }

    if (options.context) {
      Object.keys(options.context).forEach(function (key) {
        module[$_MODULE_CONTEXT][key] = options.context[key];
      });
    }

    module.load(filename);
    return module.exports;
  }

  get exports() {
    return this.main.exports;
  }

  get name() {
    return this.manifest.name;
  }

  get version() {
    return this.manifest.version;
  }

  get isSystem() {
    return this.mount.charAt(1) === '_';
  }

  get root() {
    if (this.isSystem) {
      return FoxxService._systemAppPath;
    }
    return FoxxService._appPath;
  }

  get collectionPrefix() {
    return this.mount.substr(1).replace(/[-.:/]/g, '_') + '_';
  }

  static get _startupPath() {
    return STARTUP_PATH;
  }

  static get _appPath() {
    return APP_PATH ? (
      path.join(APP_PATH, '_db', internal.db._name())
    ) : undefined;
  }

  static get _systemAppPath() {
    return APP_PATH ? (
      path.join(STARTUP_PATH, 'apps', 'system')
    ) : undefined;
  }

  static get _oldAppPath() {
    return APP_PATH ? (
      path.join(APP_PATH, 'databases', internal.db._name())
    ) : undefined;
  }

  static get _devAppPath() {
    return DEV_APP_PATH ? (
      path.join(DEV_APP_PATH, 'databases', internal.db._name())
    ) : undefined;
  }
}

module.exports = FoxxService;
<commit_msg>Expose module.context.service<commit_after>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief FoxxService and FoxxContext types
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2015 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Alan Plum
/// @author Copyright 2015, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

const _ = require('lodash');
const internal = require('internal');
const assert = require('assert');
const Module = require('module');
const path = require('path');
const fs = require('fs');
const parameterTypes = require('@arangodb/foxx/manager-utils').parameterTypes;
const getReadableName = require('@arangodb/foxx/manager-utils').getReadableName;
const $_MODULE_ROOT = Symbol.for('@arangodb/module.root');
const $_MODULE_CONTEXT = Symbol.for('@arangodb/module.context');

const APP_PATH = internal.appPath ? path.resolve(internal.appPath) : undefined;
const STARTUP_PATH = internal.startupPath ? path.resolve(internal.startupPath) : undefined;
const DEV_APP_PATH = internal.devAppPath ? path.resolve(internal.devAppPath) : undefined;

class FoxxContext {
  constructor(service) {
    this.basePath = path.resolve(service.root, service.path);
    this.service = service;
    this.argv = [];

    this.comments = [];
  }

  fileName(filename) {
    return fs.safeJoin(this._prefix, filename);
  }

  file(filename, encoding) {
    return fs.readFileSync(this.fileName(filename), encoding);
  }

  foxxFilename(filename) {
    return this.fileName(filename);
  }

  path(name) {
    return path.join(this._prefix, name);
  }

  collectionName(name) {
    let fqn = (
      this.collectionPrefix
      + name.replace(/[^a-z0-9]/ig, '_').replace(/(^_+|_+$)/g, '').substr(0, 64)
    );
    if (!fqn.length) {
      throw new Error(`Cannot derive collection name from "${name}"`);
    }
    return fqn;
  }

  collection(name) {
    return internal.db._collection(this.collectionName(name));
  }

  get _prefix() {
    return this.basePath;
  }

  get baseUrl() {
    return `/_db/${encodeURIComponent(internal.db._name())}/${this.service.mount.slice(1)}`;
  }

  get collectionPrefix() {
    return this.service.collectionPrefix;
  }

  get mount() {
    return this.service.mount;
  }

  get name() {
    return this.service.name;
  }

  get version() {
    return this.service.version;
  }

  get manifest() {
    return this.service.manifest;
  }

  get isDevelopment() {
    return this.service.isDevelopment;
  }

  get isProduction() {
    return !this.isDevelopment;
  }

  get options() {
    return this.service.options;
  }

  get configuration() {
    return this.service.configuration;
  }

  get dependencies() {
    return this.service.dependencies;
  }
}

Object.defineProperties(FoxxContext.prototype, {
  comment: {
    value: function (str) {
      this.comments.push(str);
    }
  },
  clearComments: {
    value: function () {
      this.comments.splice(0, this.comments.length);
    }
  }
});

function createConfiguration(definitions) {
  const config = {};
  Object.keys(definitions).forEach(function (name) {
    const def = definitions[name];
    if (def.default !== undefined) {
      config[name] = def.default;
    }
  });
  return config;
}

function createDependencies(definitions, options) {
  const deps = {};
  Object.keys(definitions).forEach(function (name) {
    Object.defineProperty(deps, name, {
      configurable: true,
      enumerable: true,
      get() {
        const mount = options[name];
        return mount ? require('@arangodb/foxx').getExports(mount) : null;
      }
    });
  });
  return deps;
}

class FoxxService {
  constructor(data) {
    assert(data, 'no arguments');
    assert(data.mount, 'mount path required');
    assert(data.path, `local path required for app "${data.mount}"`);
    assert(data.manifest, `called without manifest for app "${data.mount}"`);

    // mount paths always start with a slash
    this.mount = data.mount;
    this.path = data.path;
    this.isDevelopment = data.isDevelopment || false;

    this.manifest = data.manifest;
    if (!this.manifest.dependencies) {
      this.manifest.dependencies = {};
    }
    if (!this.manifest.configuration) {
      this.manifest.configuration = {};
    }

    this.options = data.options;
    if (!this.options.configuration) {
      this.options.configuration = {};
    }
    if (!this.options.dependencies) {
      this.options.dependencies = {};
    }

    this.configuration = createConfiguration(this.manifest.configuration);
    this.dependencies = createDependencies(this.manifest.dependencies, this.options.dependencies);
    let warnings = this.applyConfiguration(this.options.configuration);
    if (warnings.length) {
      console.warnLines(
        `Stored configuration for app "${data.mount}" has errors:\n${warnings.join('\n  ')}`
      );
    }
    // don't need to apply deps from options -- they work automatically

    if (this.manifest.thumbnail) {
      let thumb = path.resolve(this.root, this.path, this.manifest.thumbnail);
      try {
        this.thumbnail = fs.read64(thumb);
      } catch (e) {
        this.thumbnail = null;
        /*
        console.warnLines(
          `Cannot read thumbnail "${thumb}" for app "${data.mount}": ${e.stack}`
        );
        */
      }
    } else {
      this.thumbnail = null;
    }

    this.requireCache = {};
    const lib = this.manifest.lib || '.';
    const moduleRoot = path.resolve(this.root, this.path, lib);
    const foxxConsole = require('@arangodb/foxx/console')(this.mount);
    this.main = new Module(`foxx:${data.mount}`);
    this.main.filename = path.resolve(moduleRoot, '.foxx');
    this.main[$_MODULE_ROOT] = moduleRoot;
    this.main[$_MODULE_CONTEXT].console = foxxConsole;
    this.main.require.cache = this.requireCache;
    this.main.context = new FoxxContext(this);
  }

  applyConfiguration(config) {
    const definitions = this.manifest.configuration;
    const warnings = [];

    _.each(config, function (rawValue, name) {
      const def = definitions[name];
      if (!def) {
        warnings.push(`Unexpected option "${name}"`);
        return;
      }

      if (def.required === false && (rawValue === undefined || rawValue === null || rawValue === '')) {
        delete this.options.configuration[name];
        this.configuration[name] = def.default;
        return;
      }

      const validate = parameterTypes[def.type];
      let parsedValue = rawValue;
      let warning;

      if (validate.isJoi) {
        let result = validate.required().validate(rawValue);
        if (result.error) {
          warning = result.error.message.replace(/^"value"/, `"${name}"`);
        } else {
          parsedValue = result.value;
        }
      } else {
        try {
          parsedValue = validate(rawValue);
        } catch (e) {
          warning = `"${name}": ${e.message}`;
        }
      }

      if (warning) {
        warnings.push(warning);
      } else {
        this.options.configuration[name] = rawValue;
        this.configuration[name] = parsedValue;
      }
    }, this);

    return warnings;
  }

  applyDependencies(deps) {
    var definitions = this.manifest.dependencies;
    var warnings = [];

    _.each(deps, function (mount, name) {
      const dfn = definitions[name];
      if (!dfn) {
        warnings.push(`Unexpected dependency "${name}"`);
      } else {
        this.options.dependencies[name] = mount;
      }
    }, this);

    return warnings;
  }

  _PRINT(context) {
    context.output += `[FoxxService "${this.name}" (${this.version}) on ${this.mount}]`;
  }

  toJSON() {
    const result = {
      name: this.name,
      version: this.version,
      manifest: this.manifest,
      path: this.path,
      options: this.options,
      mount: this.mount,
      root: this.root,
      isSystem: this.isSystem,
      isDevelopment: this.isDevelopment
    };
    if (this.error) {
      result.error = this.error;
    }
    if (this.manifest.author) {
      result.author = this.manifest.author;
    }
    if (this.manifest.description) {
      result.description = this.manifest.description;
    }
    if (this.thumbnail) {
      result.thumbnail = this.thumbnail;
    }
    return result;
  }

  simpleJSON() {
    return {
      name: this.name,
      version: this.version,
      mount: this.mount
    };
  }

  development(isDevelopment) {
    this.isDevelopment = isDevelopment;
  }

  getConfiguration(simple) {
    var config = {};
    var definitions = this.manifest.configuration;
    var options = this.options.configuration;
    _.each(definitions, function (dfn, name) {
      var value = options[name] === undefined ? dfn.default : options[name];
      config[name] = simple ? value : _.extend({}, dfn, {
        title: getReadableName(name),
        current: value
      });
    });
    return config;
  }

  getDependencies(simple) {
    var deps = {};
    var definitions = this.manifest.dependencies;
    var options = this.options.dependencies;
    _.each(definitions, function (dfn, name) {
      deps[name] = simple ? options[name] : {
        definition: dfn,
        title: getReadableName(name),
        current: options[name]
      };
    });
    return deps;
  }

  needsConfiguration() {
    var config = this.getConfiguration();
    var deps = this.getDependencies();
    return _.any(config, function (cfg) {
      return cfg.current === undefined && cfg.required !== false;
    }) || _.any(deps, function (dep) {
      return dep.current === undefined && dep.definition.required !== false;
    });
  }

  run(filename, options) {
    options = options || {};
    filename = path.resolve(this.main[$_MODULE_CONTEXT].__dirname, filename);

    var module = new Module(filename, this.main);
    module[$_MODULE_CONTEXT].console = this.main[$_MODULE_CONTEXT].console;
    module.context = _.extend(
      new FoxxContext(this),
      this.main.context,
      options.foxxContext
    );

    if (options.preprocess) {
      module.preprocess = options.preprocess;
    }

    if (options.context) {
      Object.keys(options.context).forEach(function (key) {
        module[$_MODULE_CONTEXT][key] = options.context[key];
      });
    }

    module.load(filename);
    return module.exports;
  }

  get exports() {
    return this.main.exports;
  }

  get name() {
    return this.manifest.name;
  }

  get version() {
    return this.manifest.version;
  }

  get isSystem() {
    return this.mount.charAt(1) === '_';
  }

  get root() {
    if (this.isSystem) {
      return FoxxService._systemAppPath;
    }
    return FoxxService._appPath;
  }

  get collectionPrefix() {
    return this.mount.substr(1).replace(/[-.:/]/g, '_') + '_';
  }

  static get _startupPath() {
    return STARTUP_PATH;
  }

  static get _appPath() {
    return APP_PATH ? (
      path.join(APP_PATH, '_db', internal.db._name())
    ) : undefined;
  }

  static get _systemAppPath() {
    return APP_PATH ? (
      path.join(STARTUP_PATH, 'apps', 'system')
    ) : undefined;
  }

  static get _oldAppPath() {
    return APP_PATH ? (
      path.join(APP_PATH, 'databases', internal.db._name())
    ) : undefined;
  }

  static get _devAppPath() {
    return DEV_APP_PATH ? (
      path.join(DEV_APP_PATH, 'databases', internal.db._name())
    ) : undefined;
  }
}

module.exports = FoxxService;
<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, shell, globalShortcut } from 'electron';
import {
  INPUT_HEIGHT,
  WINDOW_WIDTH,
  RESULT_HEIGHT,
  MIN_VISIBLE_RESULTS
} from './app/constants/ui';

let menu;
let template;
let mainWindow = null;

// if (process.env.NODE_ENV === 'development') {
//   require('electron-debug')(); // eslint-disable-line global-require
// }

// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') app.quit();
// });

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    alwaysOnTop: true,
    show: false,
    width: WINDOW_WIDTH,
    minWidth: WINDOW_WIDTH,
    maxWidth: WINDOW_WIDTH,
    height: INPUT_HEIGHT,
    minHeight: INPUT_HEIGHT + RESULT_HEIGHT * MIN_VISIBLE_RESULTS,
    frame: false,
    resizable: false
  });

  mainWindow.loadURL(`file://${__dirname}/app/app.html`);

  if (process.env.NODE_ENV !== 'development') {
    // Hide window on blur in production move
    // In development we usually use developer tools
    mainWindow.on('blur', () => mainWindow.hide());
  }

  //
  // const HOTKEY = 'Cmd+Alt+Shift+Control+Space';
  const HOTKEY = 'Control+Space';

  globalShortcut.register(HOTKEY, () => {
    mainWindow.show();
    mainWindow.focus();
  });

  app.dock.hide();

  // if (process.env.NODE_ENV === 'development') {
  //   mainWindow.openDevTools();
  //   mainWindow.webContents.on('context-menu', (e, props) => {
  //     const { x, y } = props;

  //     Menu.buildFromTemplate([{
  //       label: 'Inspect element',
  //       click() {
  //         mainWindow.inspectElement(x, y);
  //       }
  //     }]).popup(mainWindow);
  //   });
  // }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<commit_msg>Remove unused commented code<commit_after>import { app, BrowserWindow, Menu, shell, globalShortcut } from 'electron';
import {
  INPUT_HEIGHT,
  WINDOW_WIDTH,
  RESULT_HEIGHT,
  MIN_VISIBLE_RESULTS
} from './app/constants/ui';

let menu;
let template;
let mainWindow = null;

// if (process.env.NODE_ENV === 'development') {
//   require('electron-debug')(); // eslint-disable-line global-require
// }

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    alwaysOnTop: true,
    show: false,
    width: WINDOW_WIDTH,
    minWidth: WINDOW_WIDTH,
    maxWidth: WINDOW_WIDTH,
    height: INPUT_HEIGHT,
    minHeight: INPUT_HEIGHT + RESULT_HEIGHT * MIN_VISIBLE_RESULTS,
    frame: false,
    resizable: false
  });

  mainWindow.loadURL(`file://${__dirname}/app/app.html`);

  if (process.env.NODE_ENV !== 'development') {
    // Hide window on blur in production move
    // In development we usually use developer tools
    mainWindow.on('blur', () => mainWindow.hide());
  }

  //
  // const HOTKEY = 'Cmd+Alt+Shift+Control+Space';
  const HOTKEY = 'Control+Space';

  globalShortcut.register(HOTKEY, () => {
    mainWindow.show();
    mainWindow.focus();
  });

  app.dock.hide();

  // if (process.env.NODE_ENV === 'development') {
  //   mainWindow.openDevTools();
  //   mainWindow.webContents.on('context-menu', (e, props) => {
  //     const { x, y } = props;

  //     Menu.buildFromTemplate([{
  //       label: 'Inspect element',
  //       click() {
  //         mainWindow.inspectElement(x, y);
  //       }
  //     }]).popup(mainWindow);
  //   });
  // }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, crashReporter, shell, autoUpdater } from 'electron'
const { version } = require('./package.json')
import open from 'open'

let menu
let template
let mainWindow = null

crashReporter.start()

const feedUrl = `https://felony-update.herokuapp.com/${process.platform}/${process.arch}/${version}`
if (process.env.NODE_ENV !== 'development') {
  autoUpdater.setFeedURL(feedUrl)
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')()
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    'show': false,
    'width': 295,
    'height': 435,
    'title-bar-style': 'hidden',
  })

  mainWindow.loadURL(`file://${ __dirname }/app/app.html`)

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show()
    mainWindow.focus()
  })

  mainWindow.webContents.on('new-window', function (event, url) {
    event.preventDefault()
    open(url)
  })
  mainWindow.on('closed', () => {
    mainWindow = null
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools()
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About Felony',
        selector: 'orderFrontStandardAboutPanel:',
      }, {
        type: 'separator',
      }, {
        label: 'Services',
        submenu: [],
      }, {
        type: 'separator',
      }, {
        label: 'Hide Felony',
        accelerator: 'Command+H',
        selector: 'hide:',
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:',
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:',
      }, {
        type: 'separator',
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit()
        },
      }],
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:',
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:',
      }, {
        type: 'separator',
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:',
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:',
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:',
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:',
      }],
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart()
        },
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools()
        },
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }],
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:',
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:',
      }, {
        type: 'separator',
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:',
      }],
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        },
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        },
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        },
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        },
      }],
    }]

    menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O',
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close()
        },
      }],
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.restart()
        },
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools()
        },
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }],
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        },
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        },
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        },
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        },
      }],
    }]
    menu = Menu.buildFromTemplate(template)
    mainWindow.setMenu(menu)
  }
})
<commit_msg>Fix autoUpdater<commit_after>import { app, BrowserWindow, Menu, crashReporter, shell, autoUpdater } from 'electron'
const { version } = require('./package.json')
import open from 'open'

let menu
let template
let mainWindow = null

crashReporter.start()
const feedUrl = `https://felony-app-update.herokuapp.com/update/${process.platform}_${process.arch}/${version}`

if (process.env.NODE_ENV !== 'development') {
  autoUpdater.setFeedURL(feedUrl)

  try {
    let check = true

    autoUpdater.checkForUpdates()
    setInterval(() => {
      if (check) {
        autoUpdater.checkForUpdates()
      }
    }, 120000)

    autoUpdater.on('checking-for-update', () => {
      check = false
      console.log('checking')
    })

    autoUpdater.on('update-available', () => {
      // Update
    })

    autoUpdater.on('update-not-available', () => {
      // No update
    })

    autoUpdater.on('update-downloaded', () => {
      // TODO: ask before installing
      autoUpdater.quitAndInstall()
    })
  } catch (err) {
    console.log('error', err)
  }
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')()
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    'show': false,
    'width': 295,
    'height': 435,
    'title-bar-style': 'hidden',
  })

  mainWindow.loadURL(`file://${ __dirname }/app/app.html`)

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show()
    mainWindow.focus()
  })

  mainWindow.webContents.on('new-window', function (event, url) {
    event.preventDefault()
    open(url)
  })
  mainWindow.on('closed', () => {
    mainWindow = null
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools()
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About Felony',
        selector: 'orderFrontStandardAboutPanel:',
      }, {
        type: 'separator',
      }, {
        label: 'Services',
        submenu: [],
      }, {
        type: 'separator',
      }, {
        label: 'Hide Felony',
        accelerator: 'Command+H',
        selector: 'hide:',
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:',
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:',
      }, {
        type: 'separator',
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit()
        },
      }],
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:',
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:',
      }, {
        type: 'separator',
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:',
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:',
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:',
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:',
      }],
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart()
        },
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools()
        },
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }],
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:',
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:',
      }, {
        type: 'separator',
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:',
      }],
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        },
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        },
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        },
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        },
      }],
    }]

    menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O',
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close()
        },
      }],
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.restart()
        },
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools()
        },
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        },
      }],
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        },
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        },
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        },
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        },
      }],
    }]
    menu = Menu.buildFromTemplate(template)
    mainWindow.setMenu(menu)
  }
})
<|endoftext|>


<commit_before>'use strict';

/**
 * A thin MongoDB layer that wraps
 * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) to be
 * used with [persistence](https://github.com/n-fuse/persistence).
 *
 * @module persistence-mongodb
 */

var mongo = require('mongodb');
var async = require('async');

/**
 * Connects to a MongoDB database.
 *
 * @param {Object}
 *            [options] a single object for the Server options and the DB
 *            options.
 * @param {String}
 *            options.host defaults to `'localhost'`
 * @param {Int}
 *            options.port defaults to `27017` created: -1}]`
 * @param {String}
 *            options.name name of the database created: -1}]`
 * @param {Function(err,
 *            db)} callback is called when an error occurs or when the database
 *            connection has been established.
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {DB}
 *            callback.db the `DB` instance
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/database.html#server-options}
 *      and
 *      {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/database.html#db-options}
 *      for more information on the possible options
 */
exports.connect = function(options, callback) {
  // set optional arguments
  if (arguments.length == 1) {
    callback == options;
    options = {};
  }

  var host = options.host || 'localhost';
  var port = options.port || 27017;

  // strict mode must always be off, since otherwise, collection creation etc.
  // would not work
  options.strict = false;
  options.safe = true;

  var mongoServer = new mongo.Server(host, port, options);
  var dbConnector = new mongo.Db(options.name, mongoServer, options);

  // open database but only return an object that only has a few methods
  dbConnector.open(function(err, conn) {
    if (err)
      return callback(err);

    callback(null, new DB(conn));
  });
};

/**
 * @classdesc Thin wrapper around mongodb's Db class.
 * @constructor
 *
 * @param {Db}
 *            dbConnection db connection object
 * @property {String} protocol Database protocol
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/db.html}
 */
exports.DB = function DB(dbConnection) {
  this._db = dbConnection;
}

/**
 * Creates/gets a collection. Additionally, this method ensures the fields given
 * in `indexes` are always indexed.
 *
 * @param {String}
 *            name collection's name
 * @param {Array}
 *            [indexes] array of indexes passed to `ensureIndex()` eg. `['id', {
 *            created: -1}]`
 * @param {Function(err,
 *            collection)} callback is called when an error occurs or when the
 *            collection is returned.
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Collection}
 *            callback.collection the `Collection` instance
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/indexes.html}
 */
DB.prototype.getCollection = function(name, indexes, callback) {
  if (arguments.length == 2) {
    callback = indexes;
    indexes = null;
  }

  this._db.collection(name, function(err, coll) {
    if (err)
      return callback(err);

    // when there are no indexes, return the collection immediately
    if (indexes === null || indexes.length == 0)
      return callback(null, new Collection(coll));

    // ensure all indexes before returning the collection
    // therefore indexes are mapped to the ensureIndex method
    indexes.forEach(function(index) {
      coll.ensureIndex(index, function() {
      });
    });

    callback(null, new Collection(coll));
  });
};

// NOTE:
// Removing collections or databases is not supported and can only be done
// manually via the mongo console.

/**
 * @classdesc Thin wrapper around mongodb's collection type.
 * @constructor
 *
 * @param {Collection}
 *            collection collection object
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html}
 */
function Collection(coll) {
  this._coll = coll;
}

/**
 * Finds all records that match a given query.
 *
 * @param {Object|String}
 *            query resulting objects must match this query. Consult the
 *            [node-mongodb-native
 *            documentation](http://mongodb.github.com/node-mongodb-native/markdown-docs/queries.html#query-object)
 * @param {String|Int|ObjectId}
 *            [query._id] If specified, MongoDB will search by ID
 * @param {String[]}
 *            [fields] specifies the fields of the resulting objects
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            res)} callback is called when an error occurs or when the
 *            record(s) return
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#find}
 */
Collection.prototype.find = function(query, fields, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = fields;
    fields = null;
    options = {};
  } else if (arguments.length == 3) {
    callback = options;
    options = fields;
    fields = null;
  }

  // call the query
  if (fields === null)
    this._coll.find(query, options).toArray(callback);
  else
    this._coll.find(query, fields).toArray(callback);
};

/**
 * Finds the first record that matches a given query. Use this method, if you
 * know that there will be only one resulting document. (E.g. when you want to
 * find a result by its `_id`.)
 *
 * @param {Object|String}
 *            query resulting objects must match this query. Consult the
 *            [node-mongodb-native
 *            documentation](http://mongodb.github.com/node-mongodb-native/markdown-docs/queries.html#query-object)
 * @param {String|Int|ObjectId}
 *            [query._id] If specified, MongoDB will search by ID
 * @param {String[]}
 *            [fields] specifies the fields of the resulting objects
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            res)} callback is called when an error occurs or when the
 *            record(s) return
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#find}
 */
Collection.prototype.findOne = function(query, fields, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = fields;
    fields = null;
    options = {};
  } else if (arguments.length == 3) {
    callback = options;
    options = fields;
    fields = null;
  }

  // call the query
  if (fields == null)
    this._coll.findOne(query, options, callback);
  else
    this._coll.findOne(query, fields, options, callback);
};

/**
 * Saves a record. If an object with the same `_id` exists already, this will
 * overwrite it completely.
 *
 * @param {Object}
 *            record record that shall be saved. This parameter can be an
 *            arbitrary _non-circular_ JS object that contains only primitive
 *            values or arrays and objects, no functions.
 * @param {String|Int|ObjectId}
 *            [record._id] ID that is used by MongoDB. If no ID is specified,
 *            the a default MongoDB ID will be generated.
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            saved)} callback is called when an error occurs or when the record
 *            has been saved
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#save}
 */
Collection.prototype.save = function(record, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = options;
    options = {};
  }

  options.safe = true;

  this._coll.save(record, options, callback);
};
<commit_msg>MongoDB-layer improved<commit_after>'use strict';

/**
 * A thin MongoDB layer that wraps
 * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) to be
 * used with [persistence](https://github.com/n-fuse/persistence).
 *
 * @module persistence-mongodb
 */

var mongo = require('mongodb');
var async = require('async');

/**
 * Connects to a MongoDB database.
 *
 * @param {Object}
 *            [options] a single object for the Server options and the DB
 *            options.
 * @param {String}
 *            options.host defaults to `'localhost'`
 * @param {Int}
 *            options.port defaults to `27017` created: -1}]`
 * @param {String}
 *            options.name name of the database created: -1}]`
 * @param {Function(err,
 *            db)} callback is called when an error occurs or when the database
 *            connection has been established.
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {DB}
 *            callback.db the `DB` instance
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/database.html#server-options}
 *      and
 *      {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/database.html#db-options}
 *      for more information on the possible options
 */
exports.connect = function(options, callback) {
  // set optional arguments
  if (arguments.length == 1) {
    callback == options;
    options = {};
  }

  var host = options.host || 'localhost';
  var port = options.port || 27017;

  // strict mode must always be off, since otherwise, collection creation etc.
  // would not work
  options.strict = false;
  options.safe = true;

  var mongoServer = new mongo.Server(host, port, options);
  var dbConnector = new mongo.Db(options.name, mongoServer, options);

  // open database but only return an object that only has a few methods
  dbConnector.open(function(err, conn) {
    if (err)
      return callback(err);

    callback(null, new DB(conn));
  });
};

/**
 * @classdesc Thin wrapper around mongodb's Db class.
 * @constructor
 *
 * @param {Db}
 *            dbConnection db connection object
 * @property {String} protocol Database protocol
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/db.html}
 */
exports.DB = function DB(dbConnection) {
  this._db = dbConnection;
}

/**
 * Creates/gets a collection. Additionally, this method ensures the fields given
 * in `indexes` are always indexed.
 *
 * @param {String}
 *            name collection's name
 * @param {Array}
 *            [indexes] array of indexes passed to `ensureIndex()` eg. `['id', {
 *            created: -1}]`
 * @param {Function(err,
 *            collection)} callback is called when an error occurs or when the
 *            collection is returned.
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Collection}
 *            callback.collection the `Collection` instance
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/markdown-docs/indexes.html}
 */
DB.prototype.getCollection = function(name, indexes, callback) {
  if (arguments.length == 2) {
    callback = indexes;
    indexes = null;
  }

  this._db.collection(name, function(err, coll) {
    if (err)
      return callback(err);

    // when there are no indexes, return the collection immediately
    if (indexes === null || indexes.length == 0)
      return callback(null, new Collection(coll));

    // ensure all indexes before returning the collection
    // therefore indexes are mapped to the ensureIndex method
    indexes.forEach(function(index) {
      coll.ensureIndex(index, function() {
      });
    });

    callback(null, new Collection(coll));
  });
};

// NOTE:
// Removing collections or databases is not supported and can only be done
// manually via the mongo console.

/**
 * @classdesc Thin wrapper around mongodb's collection type.
 * @constructor
 *
 * @param {Collection}
 *            collection collection object
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html}
 */
function Collection(coll) {
  this._coll = coll;
}

/**
 * Finds all records that match a given query.
 *
 * @param {Object|String}
 *            query resulting objects must match this query. Consult the
 *            [node-mongodb-native
 *            documentation](http://mongodb.github.com/node-mongodb-native/markdown-docs/queries.html#query-object)
 * @param {String|Int|ObjectId}
 *            [query._id] If specified, MongoDB will search by ID
 * @param {String[]}
 *            [fields] specifies the fields of the resulting objects
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            res)} callback is called when an error occurs or when the
 *            record(s) return
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#find}
 */
Collection.prototype.find = function(query, fields, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = fields;
    fields = null;
    options = {};
  } else if (arguments.length == 3) {
    callback = options;
    options = fields;
    fields = null;
  }

  // call the query
  if (fields === null)
    this._coll.find(query, options).toArray(callback);
  else
    this._coll.find(query, fields).toArray(callback);
};

/**
 * Finds the first record that matches a given query. Use this method, if you
 * know that there will be only one resulting document. (E.g. when you want to
 * find a result by its `_id`.)
 *
 * @param {Object|String}
 *            query resulting objects must match this query. Consult the
 *            [node-mongodb-native
 *            documentation](http://mongodb.github.com/node-mongodb-native/markdown-docs/queries.html#query-object)
 * @param {String|Int|ObjectId}
 *            [query._id] If specified, MongoDB will search by ID
 * @param {String[]}
 *            [fields] specifies the fields of the resulting objects
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            res)} callback is called when an error occurs or when the
 *            record(s) return
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#find}
 */
Collection.prototype.findOne = function(query, fields, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = fields;
    fields = null;
    options = {};
  } else if (arguments.length == 3) {
    callback = options;
    options = fields;
    fields = null;
  }

  // call the query
  if (fields == null)
    this._coll.findOne(query, options, callback);
  else
    this._coll.findOne(query, fields, options, callback);
};

/**
 * Saves a record. If an object with the same `_id` exists already, this will
 * overwrite it completely.
 *
 * @param {Object}
 *            record record that shall be saved. This parameter can be an
 *            arbitrary _non-circular_ JS object that contains only primitive
 *            values or arrays and objects, no functions.
 * @param {String|Int|ObjectId}
 *            [record._id] ID that is used by MongoDB. If no ID is specified,
 *            the a default MongoDB ID will be generated.
 * @param {Object}
 *            [options] defines extra logic (sorting options, paging etc.)
 * @param {Function(err,
 *            saved)} callback is called when an error occurs or when the record
 *            has been saved
 * @param {Error*}
 *            callback.err the error, if an error occurred or `null`
 * @param {Object|Int}
 *            callback.saved the record, if it has been inserted and `1` if the
 *            record has been updated
 *
 * @see {@link http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#save}
 */
Collection.prototype.save = function(record, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = options;
    options = {};
  }

  options.safe = true;

  this._coll.save(record, options, callback);
};

Collection.prototype.delete = function(query, options, callback) {
  // optional arguments
  if (arguments.length == 2) {
    callback = options;
    options = {};
  }

  options.safe = true;

  this._coll.remove(query, options, callback);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import config from 'config/environment';
import troopImage from 'images/Troop.png';
import styles from './idme.css';

class Idme extends Component {
  componentWillMount() {}
  idMe = () => {
    window.open(
      `${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${config.host}/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`
    );
  };

  render() {
    return (

    );
  }
}

export default Idme;
<commit_msg>Remove componentWillMount from idMe.js shared component<commit_after>import React, { Component } from 'react';
import config from 'config/environment';
import troopImage from 'images/Troop.png';
import styles from './idme.css';

class Idme extends Component {
  idMe = () => {
    window.open(
      `${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${config.host}/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`
    );
  };

  render() {
    return (

    );
  }
}

export default Idme;
<|endoftext|>


<commit_before>var pg        = require("pg").native,
    projector = require("../projector"),
    __        = require("lodash");
/*
 * Something like this eventually?
 * https://github.com/mapbox/tilemill/blob/master/models/Layer.bones#L60
 */

var PostGISSource = function(options) {
  this._projection = options.projection;
  this._projectionRaw = options.projection && options.projection.indexOf('EPSG')? options.projection.slice(options.projection.indexOf(':')+1):null; // for PostGIS < v1.5, if we want to support it
  this._connectionString = options.connectionString; // required
  this._tableName = options.tableName;               // required
  this._geomField = options.geomField;               // required
  this._attrFields = __.isArray(options.fields) ?
                       options.fields.join(',') :
                       options.fields; // array of attribute fields, or comma separated suggested for better performanace
  this.sourceName = options.name || options.tableName;

  // TODO: allow `pg` options to be easily set (e.g. max connections, etc.)
  // TODO: throw errors if required fields are missing

  console.log("Creating PostGIS source: "+this._connectionString+" "+this._tableName);
  return this;
}

PostGISSource.prototype = {
  constructor: PostGISSource,

  // need some way to check projection equivalency programmatically so we can use built-in postgis projection i.e.
  //
  // check proj4 support with: SELECT PostGIS_Full_Version();
  // i.e. POSTGIS="1.3.3" GEOS="3.1.0-CAPI-1.5.0" PROJ="Rel. 4.4.9, 29 Oct 2004" USE_STATS
  //
  // if (!projector.equals(projection,mapProjection){
  //    var query = SELECT ST_TRANSFORM(query, projection, mapProjecion)

  getShapes: function(minX, minY, maxX, maxY, mapProjection, callback) {
    console.log("GETSHAPES", this._projection, mapProjection);
    // we don't get real coordinates from Map.js yet so we'll fake it for now
    // minX = -122.4565;
    // minY = 37.756;
    // maxX = -122.451;
    // maxY = 37.761;
    /*
    minX = -122.5195;
    minY = 37.7062;
    maxX = -122.3812;
    maxY = 37.8036;
    */

    var min = [minX, minY];
    var max = [maxX, maxY];

    // project request coordinates into data coordinates
    if (mapProjection !== this._projection) {
      min = projector.project.Point(mapProjection, this._projection, min);
      max = projector.project.Point(mapProjection, this._projection, max);
      console.log(min,max);
    }

    //min = [-122.5195, 37.7062];
    //max = [-122.3812, 37.8036];

    pg.connect(this._connectionString, function(err, client) { // Switched method signature... WTF?!
      if (err) { console.error(err); return callback(err, null); }
      console.log("Loading features...");
      var start, query;

      start = Date.now();
      if (this._attrFields) {
        query = "SELECT ST_AsGeoJson("+this._geomField+") as geometry, "+this._attrFields+" FROM "+this._tableName+" WHERE "+this._geomField+" && ST_MakeEnvelope($1,$2,$3,$4);";
      }
      else {
        query = "SELECT ST_AsGeoJson("+this._geomField+") as geometry,* FROM "+this._tableName+" WHERE "+this._geomField+" && ST_MakeEnvelope($1,$2,$3,$4);";
      }
      console.log("Querying... "+query+" "+min+", "+max);
      client.query(query, [min[0], min[1], max[0], max[1]], function(err, result) {
        if (err) { return callback(err, null); }
        console.log("Loaded in " + (Date.now() - start) + "ms");

        var geoJson;

        if (result && result.rows) {
          // Removed this._lastResult because it wasn't clear why it's being stored
          // Also, since we're processing blackbox data, we should probably catch any exceptions from processing it
          try {
            geoJson = this._toGeoJson(result.rows);
            if (this._projection !== mapProjection){
              console.log("REPROJECTING GEOMETRY");
              //console.log('before',geoJson.features[0].geometry.coordinates[0][0][0]);
              geoJson = projector.project.FeatureCollection(this._projection, mapProjection, geoJson);
              //console.log('after',geoJson.features[0].geometry.coordinates[0][0][0]);
            }
          }
          catch(err) {
            return callback(err, null);
          }
        }
        callback(err, geoJson);
      }.bind(this));
    }.bind(this));
  },

  _toGeoJson: function(rows){
    var obj, i;

    obj = {
      type: "FeatureCollection",
      features: []
    };

    for (i = 0; i < rows.length; i++) {
      var item, feature, geometry;
      item = rows[i];

      geometry = JSON.parse(item.geometry);
      delete item.geometry;

      feature = {
        type: "Feature",
        properties: item,
        geometry: geometry
      }

      obj.features.push(feature);
    }
    return obj;
  }
}

module.exports = PostGISSource;
<commit_msg>Cleanup<commit_after>var pg        = require("pg").native,
    projector = require("../projector"),
    __        = require("lodash");
/*
 * Something like this eventually?
 * https://github.com/mapbox/tilemill/blob/master/models/Layer.bones#L60
 */

var PostGISSource = function(options) {
  this._projection = options.projection;
  this._projectionRaw = options.projection && options.projection.indexOf('EPSG')? options.projection.slice(options.projection.indexOf(':')+1):null; // for PostGIS < v1.5, if we want to support it
  this._connectionString = options.connectionString; // required
  this._tableName = options.tableName;               // required
  this._geomField = options.geomField;               // required
  this._attrFields = __.isArray(options.fields) ?
                       options.fields.join(',') :
                       options.fields; // array of attribute fields, or comma separated suggested for better performanace
  this.sourceName = options.name || options.tableName;

  // TODO: allow `pg` options to be easily set (e.g. max connections, etc.)
  // TODO: throw errors if required fields are missing

  console.log("Creating PostGIS source: "+this._connectionString+" "+this._tableName);
  return this;
}

PostGISSource.prototype = {
  constructor: PostGISSource,

  // need some way to check projection equivalency programmatically so we can use built-in postgis projection i.e.
  //
  // check proj4 support with: SELECT PostGIS_Full_Version();
  // i.e. POSTGIS="1.3.3" GEOS="3.1.0-CAPI-1.5.0" PROJ="Rel. 4.4.9, 29 Oct 2004" USE_STATS
  //
  // if (!projector.equals(projection,mapProjection){
  //    var query = SELECT ST_TRANSFORM(query, projection, mapProjecion)

  getShapes: function(minX, minY, maxX, maxY, mapProjection, callback) {
    console.log("GETSHAPES", this._projection, mapProjection);
    // we don't get real coordinates from Map.js yet so we'll fake it for now
    // minX = -122.4565;
    // minY = 37.756;
    // maxX = -122.451;
    // maxY = 37.761;

    var min = [minX, minY];
    var max = [maxX, maxY];

    // project request coordinates into data coordinates
    if (mapProjection !== this._projection) {
      min = projector.project.Point(mapProjection, this._projection, min);
      max = projector.project.Point(mapProjection, this._projection, max);
      console.log(min,max);
    }

    //min = [-122.5195, 37.7062];
    //max = [-122.3812, 37.8036];

    pg.connect(this._connectionString, function(err, client) { // Switched method signature... WTF?!
      if (err) { console.error(err); return callback(err, null); }
      console.log("Loading features...");
      var start, query;

      start = Date.now();
      if (this._attrFields) {
        query = "SELECT ST_AsGeoJson("+this._geomField+") as geometry, "+this._attrFields+" FROM "+this._tableName+" WHERE "+this._geomField+" && ST_MakeEnvelope($1,$2,$3,$4);";
      }
      else {
        query = "SELECT ST_AsGeoJson("+this._geomField+") as geometry,* FROM "+this._tableName+" WHERE "+this._geomField+" && ST_MakeEnvelope($1,$2,$3,$4);";
      }
      console.log("Querying... "+query+" "+min+", "+max);
      client.query(query, [min[0], min[1], max[0], max[1]], function(err, result) {
        if (err) { return callback(err, null); }
        console.log("Loaded in " + (Date.now() - start) + "ms");

        var geoJson;

        if (result && result.rows) {
          // Removed this._lastResult because it wasn't clear why it's being stored
          // Also, since we're processing blackbox data, we should probably catch any exceptions from processing it
          try {
            geoJson = this._toGeoJson(result.rows);
            if (this._projection !== mapProjection){
              //console.log("REPROJECTING GEOMETRY");
              //console.log('before',geoJson.features[0].geometry.coordinates[0][0][0]);
              geoJson = projector.project.FeatureCollection(this._projection, mapProjection, geoJson);
              //console.log('after',geoJson.features[0].geometry.coordinates[0][0][0]);
            }
          }
          catch(err) {
            return callback(err, null);
          }
        }
        callback(err, geoJson);
      }.bind(this));
    }.bind(this));
  },

  _toGeoJson: function(rows){
    var obj, i;

    obj = {
      type: "FeatureCollection",
      features: []
    };

    for (i = 0; i < rows.length; i++) {
      var item, feature, geometry;
      item = rows[i];

      geometry = JSON.parse(item.geometry);
      delete item.geometry;

      feature = {
        type: "Feature",
        properties: item,
        geometry: geometry
      }

      obj.features.push(feature);
    }
    return obj;
  }
}

module.exports = PostGISSource;
<|endoftext|>


<commit_before>const { FLOAT } = require('sequelize')

module.exports = db => db.define('relevances', {
  score: {
    type: FLOAT,
    defaultValue: 0
  }
})

module.exports.associations = (Relevance, { Article, Topic }) => {
  Article.hasMany(Relevance)
  Topic.hasMany(Relevance)
}

<commit_msg>Update relevance.js<commit_after>const { FLOAT } = require('sequelize')

module.exports = db => db.define('relevances', {
  score: {
    type: FLOAT,
    defaultValue: 0
  }
})

module.exports.associations = (Relevance, { Article, Topic }) => {
  Article.hasMany(Relevance)
  Topic.hasMany(Relevance)
}

<|endoftext|>