<commit_before>angular
.module('webui.services.rpc', [
  'webui.services.rpc.syscall', 'webui.services.configuration', 'webui.services.alerts',
  'webui.services.utils'
])
.factory('$rpc', [
  '$syscall', '$globalTimeout', '$alerts', '$utils',
  '$rootScope', '$location', '$authconf', '$filter',
function(syscall, globalTimeout, alerts, utils, rootScope, uri, authconf, filter) {

  var subscriptions = []
    , configurations = [authconf]
    , currentConf = {}
    , currentToken
    , timeout = null
    , forceNextUpdate = false;

  var cookieConf = utils.getCookie('aria2conf');
  // try at the start, so that it is presistant even when default authconf works
  if(cookieConf) configurations.unshift(cookieConf);

  if (['http', 'https'].indexOf(uri.protocol()) != -1 && uri.host() != 'localhost') {
    configurations.push({
      host: uri.host(),
      path: '/jsonrpc',
      port: 6800,
      encrypt: false
    },
    {
      host: uri.host(),
      port: uri.port(),
      path: '/jsonrpc',
      encrypt: ( uri.protocol() == 'https' )
    },
    {
      host: uri.host(),
      port: uri.port(),
      path: authconf.path,
      encrypt: ( uri.protocol() == 'https' )
    });
  }

  // set if we got error on connection. This will cause another connection attempt.
  var needNewConnection = true;

  // update is implemented such that
  // only one syscall at max is ongoing
  // (i.e. serially) so should be private
  // to maintain that invariant
  var update = function() {

    clearTimeout(timeout);
    timeout = null;

    subscriptions = _.filter(subscriptions, function(e) {
      return !!e && e.once !== 2;
    });
    var subs = subscriptions.slice();
    if (!subs.length) {
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    if (syscall.state == 'initializing') {
      console.log("Syscall is initializing, waiting");
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    if (needNewConnection && configurations.length) {
      needNewConnection = false;
      currentConf = configurations[0];
      if (currentConf && currentConf.auth && currentConf.auth.token) {
        currentToken = currentConf.auth.token;
      }
      else {
        currentToken = null;
      }
      syscall.init(currentConf);
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    var params = _.map(subs, function(s) {
      var p = s.params;
      if (currentToken) {
        p = ["token:" + currentToken].concat(p || []);
      }
      return {
        methodName: s.name,
        params: p && p.length ? p : undefined
      };
    });

    var error = function() {
      needNewConnection = true;
      var ind = configurations.indexOf(currentConf);
      if (ind != -1) configurations.splice(ind, 1);

      // If some proposed configurations are still in the pipeline then retry
      if (configurations.length) {
        alerts.log(filter('translate')("The last connection attempt was unsuccessful. Trying another configuration"));
        timeout = setTimeout(update, 0);
      }
      else {
        alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' +
          filter('translate')('Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings')
        , 'error');
        timeout = setTimeout(update, globalTimeout);
      }
    };

    syscall.invoke({
      name: 'system.multicall',
      params: [params],
      success: function(data) {
        var failed = _.some(data.result, function(d) {
          return d.code && d.message === "Unauthorized";
        });

        if (failed) {
          needNewConnection = true;
          alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' +
            filter('translate')('Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings', 'error'));
          timeout = setTimeout(update, globalTimeout);
          return;
        }

        if (configurations.length) {
          // configuration worked, save it in cookie for next time and
          // delete the pipelined configurations!!
          if (currentToken)
            alerts.addAlert(filter('translate')('Successfully connected to Aria2 through its remote RPC …'), 'success');
          else
            alerts.addAlert(filter('translate')('Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)'));
          configurations = [];
        }

        utils.setCookie('aria2conf', currentConf);

        var cbs = [];
        _.each(data.result, function(d, i) {
          var handle = subs[i];
          if (handle) {
            if (d.code) {
              console.error(handle, d);
              alerts.addAlert(d.message, 'error');
            }
            // run them later as the cb itself can mutate the subscriptions
            cbs.push({cb: handle.cb, data: d});
            if (handle.once) {
              handle.once = 2;
            }
          }
        });

        _.each(cbs, function(hnd) {
          hnd.cb(hnd.data);
        });

        rootScope.$digest();

        if (forceNextUpdate) {
          forceNextUpdate = false;
          timeout = setTimeout(update, 0);
        }
        else {
          timeout = setTimeout(update, globalTimeout);
        }
      },
      error: error
    });
  };

  // initiate the update loop
  timeout = setTimeout(update, globalTimeout);

  return {
    // conf can be configuration or array of configurations,
    // each one will be tried one after the other till success,
    // for all options for one conf read rpc/syscall.js
    configure: function(conf) {
      alerts.addAlert(filter('translate')('Trying to connect to aria2 using the new connection configuration'), 'info');

      if (conf instanceof Array)
        configurations = conf;
      else
        configurations = [conf];

      if (timeout) {
        clearTimeout(timeout);
        timeout = setTimeout(update, 0);
      }
    },

    // get current configuration being used
    getConfiguration: function() { return currentConf },

    // get currently configured directURL
    getDirectURL : function() { return currentConf.directURL },

    // syscall is done only once, delay is optional
    // and pass true to only dispatch it in the global timeout
    // which can be used to batch up once calls
    once: function(name, params, cb, delay) {
      cb = cb || angular.noop;
      params = params || [];

      subscriptions.push({
        once: true,
        name: 'aria2.' + name,
        params: params,
        cb: cb
      });

      if (!delay) {
        this.forceUpdate();
      }
    },

    // callback is called each time with updated syscall data
    // after the global timeout, delay is optional and pass it
    // true to dispatch the first syscall also on global timeout
    // which can be used to batch the subscribe calls
    subscribe: function(name, params, cb, delay) {
      cb = cb || angular.noop;
      params = params || [];

      var handle = {
        once: false,
        name: 'aria2.' + name,
        params: params,
        cb: cb
      };
      subscriptions.push(handle);

      if (!delay) this.forceUpdate();
      return handle;
    },

    // remove the subscribed callback by passing
    // the returned handle bysubscribe
    unsubscribe: function(handle) {
      var ind = subscriptions.indexOf(handle);
      subscriptions[ind] = null;
    },

    // force the global syscall update
    forceUpdate: function() {
      if (timeout) {
        clearTimeout(timeout);
        timeout = setTimeout(update, 0);
      }
      else {
        // a batch call is already in progress,
        // wait till it returns and force the next one
        forceNextUpdate = true;
      }
    }
  };
}]);
<commit_msg>1. fix the repeatedly alerts when the token or URL is incorrect 2. fix a bug that update will not be called immediately after new configurations set<commit_after>angular
.module('webui.services.rpc', [
  'webui.services.rpc.syscall', 'webui.services.configuration', 'webui.services.alerts',
  'webui.services.utils'
])
.factory('$rpc', [
  '$syscall', '$globalTimeout', '$alerts', '$utils',
  '$rootScope', '$location', '$authconf', '$filter',
function(syscall, globalTimeout, alerts, utils, rootScope, uri, authconf, filter) {

  var subscriptions = []
    , configurations = [authconf]
    , currentConf = {}
    , currentToken
    , timeout = null
    , forceNextUpdate = false;

  var cookieConf = utils.getCookie('aria2conf');
  // try at the start, so that it is presistant even when default authconf works
  if(cookieConf) configurations.unshift(cookieConf);

  if (['http', 'https'].indexOf(uri.protocol()) != -1 && uri.host() != 'localhost') {
    configurations.push({
      host: uri.host(),
      path: '/jsonrpc',
      port: 6800,
      encrypt: false
    },
    {
      host: uri.host(),
      port: uri.port(),
      path: '/jsonrpc',
      encrypt: ( uri.protocol() == 'https' )
    },
    {
      host: uri.host(),
      port: uri.port(),
      path: authconf.path,
      encrypt: ( uri.protocol() == 'https' )
    });
  }

  // set if we got error on connection. This will cause another connection attempt.
  var needNewConnection = true;

  // update is implemented such that
  // only one syscall at max is ongoing
  // (i.e. serially) so should be private
  // to maintain that invariant
  var update = function() {

    clearTimeout(timeout);
    timeout = null;

    subscriptions = _.filter(subscriptions, function(e) {
      return !!e && e.once !== 2;
    });
    var subs = subscriptions.slice();
    if (!subs.length) {
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    if (syscall.state == 'initializing') {
      console.log("Syscall is initializing, waiting");
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    if (needNewConnection && configurations.length) {
      needNewConnection = false;
      currentConf = configurations[0];
      if (currentConf && currentConf.auth && currentConf.auth.token) {
        currentToken = currentConf.auth.token;
      }
      else {
        currentToken = null;
      }
      syscall.init(currentConf);
      timeout = setTimeout(update, globalTimeout);
      return;
    }

    var params = _.map(subs, function(s) {
      var p = s.params;
      if (currentToken) {
        p = ["token:" + currentToken].concat(p || []);
      }
      return {
        methodName: s.name,
        params: p && p.length ? p : undefined
      };
    });

    var error = function() {
      needNewConnection = true;
      var ind = configurations.indexOf(currentConf);
      if (ind != -1) configurations.splice(ind, 1);

      // If some proposed configurations are still in the pipeline then retry
      if (configurations.length) {
        alerts.log(filter('translate')("The last connection attempt was unsuccessful. Trying another configuration"));
        timeout = setTimeout(update, 0);
      }
      else {
        alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' +
          filter('translate')('Could not connect to the aria2 RPC server. Will retry in 10 secs. You might want to check the connection settings by going to Settings > Connection Settings')
        , 'error');
//        timeout = setTimeout(update, globalTimeout);
      }
    };

    syscall.invoke({
      name: 'system.multicall',
      params: [params],
      success: function(data) {
        var failed = _.some(data.result, function(d) {
          return d.code && d.message === "Unauthorized";
        });

        if (failed) {
          needNewConnection = true;
          alerts.addAlert('' + filter('translate')('Oh Snap!') + ' ' +
            filter('translate')('Authentication failed while connecting to Aria2 RPC server. Will retry in 10 secs. You might want to confirm your authentication details by going to Settings > Connection Settings', 'error'));
          timeout = setTimeout(update, globalTimeout);
          return;
        }

        if (configurations.length) {
          // configuration worked, save it in cookie for next time and
          // delete the pipelined configurations!!
          if (currentToken)
            alerts.addAlert(filter('translate')('Successfully connected to Aria2 through its remote RPC …'), 'success');
          else
            alerts.addAlert(filter('translate')('Successfully connected to Aria2 through remote RPC, however the connection is still insecure. For complete security try adding an authorization secret token while starting Aria2 (through the flag --rpc-secret)'));
          configurations = [];
        }

        utils.setCookie('aria2conf', currentConf);

        var cbs = [];
        _.each(data.result, function(d, i) {
          var handle = subs[i];
          if (handle) {
            if (d.code) {
              console.error(handle, d);
              alerts.addAlert(d.message, 'error');
            }
            // run them later as the cb itself can mutate the subscriptions
            cbs.push({cb: handle.cb, data: d});
            if (handle.once) {
              handle.once = 2;
            }
          }
        });

        _.each(cbs, function(hnd) {
          hnd.cb(hnd.data);
        });

        rootScope.$digest();

        if (forceNextUpdate) {
          forceNextUpdate = false;
          timeout = setTimeout(update, 0);
        }
        else {
          timeout = setTimeout(update, globalTimeout);
        }
      },
      error: error
    });
  };

  // initiate the update loop
  timeout = setTimeout(update, globalTimeout);

  return {
    // conf can be configuration or array of configurations,
    // each one will be tried one after the other till success,
    // for all options for one conf read rpc/syscall.js
    configure: function(conf) {
      alerts.addAlert(filter('translate')('Trying to connect to aria2 using the new connection configuration'), 'info');

      if (conf instanceof Array)
        configurations = conf;
      else
        configurations = [conf];

      if (timeout)
        clearTimeout(timeout);
      timeout = setTimeout(update, 0);
    },

    // get current configuration being used
    getConfiguration: function() { return currentConf },

    // get currently configured directURL
    getDirectURL : function() { return currentConf.directURL },

    // syscall is done only once, delay is optional
    // and pass true to only dispatch it in the global timeout
    // which can be used to batch up once calls
    once: function(name, params, cb, delay) {
      cb = cb || angular.noop;
      params = params || [];

      subscriptions.push({
        once: true,
        name: 'aria2.' + name,
        params: params,
        cb: cb
      });

      if (!delay) {
        this.forceUpdate();
      }
    },

    // callback is called each time with updated syscall data
    // after the global timeout, delay is optional and pass it
    // true to dispatch the first syscall also on global timeout
    // which can be used to batch the subscribe calls
    subscribe: function(name, params, cb, delay) {
      cb = cb || angular.noop;
      params = params || [];

      var handle = {
        once: false,
        name: 'aria2.' + name,
        params: params,
        cb: cb
      };
      subscriptions.push(handle);

      if (!delay) this.forceUpdate();
      return handle;
    },

    // remove the subscribed callback by passing
    // the returned handle bysubscribe
    unsubscribe: function(handle) {
      var ind = subscriptions.indexOf(handle);
      subscriptions[ind] = null;
    },

    // force the global syscall update
    forceUpdate: function() {
      if (timeout) {
        clearTimeout(timeout);
        timeout = setTimeout(update, 0);
      }
      else {
        // a batch call is already in progress,
        // wait till it returns and force the next one
        forceNextUpdate = true;
      }
    }
  };
}]);
<|endoftext|>


<commit_before>var
	_      = require('lodash'),
	assert = require('assert'),
	bole   = require('bole'),
	dgram  = require('dgram'),
	events = require('events'),
	stream = require('stream'),
	util   = require('util')
;

var GraphiteUDP = module.exports = function GraphiteUDP(opts)
{
	assert(opts && _.isObject(opts), 'you must pass an options object');
	assert(opts.host && _.isString(opts.host), 'you must pass a hostname in the `host` option');
	assert(opts.port && _.isNumber(opts.port), 'you must pass a `port` option');

	stream.Writable.call(this, { objectMode: true });
	if (!opts.batchDelay || !_.isNumber(opts.batchDelay)) opts.batchDelay = 5000; // in ms

	this.socket = dgram.createSocket('udp4');
	this.socket.on('error', this.onError.bind(this));

	this.options = opts;
	this.log = bole('graphite ' + opts.host + ':' + opts.port);
	this.log.info('graphite output configured @ ' + opts.host + ':' + opts.port);
};
util.inherits(GraphiteUDP, stream.Writable);

GraphiteUDP.prototype.socket = null;
GraphiteUDP.prototype.timer = null;
GraphiteUDP.prototype.batch = [];

GraphiteUDP.prototype.onError = function onError(err)
{
	this.log.error('socket error');
	this.log.error(err);
};

GraphiteUDP.prototype.writeBatch = function writeBatch()
{
	var self = this;
	var data = new Buffer(this.batch.join('\n'));
	this.socket.send(data, 0, data.length, this.options.port, this.options.host, function(err, written)
	{
		if (err)
		{
			self.log.error('problem writing to graphite');
			self.log.error(err);
		}
		// TODO consider retrying and stuff
	});

	this.batch = [];
	this.timer = null;
};

GraphiteUDP.prototype._write = function _write(event, encoding, callback)
{
	if (!event.hasOwnProperty('name') || !event.hasOwnProperty('value'))
	{
		this.log.info(event, 'declining to write malformed metric to graphite', event);
		callback();
	}

	// timestamps must be unix epoch time in seconds
	var ts = event.time;
	if (!ts) ts = new Date();
	if (_.isObject(ts)) ts = Math.round(ts.getTime() / 1000);

	// graphite message format is name<space>value<space>timestamp
	this.batch.push([event.name, event.value, ts].join(' '));

	if (!this.timer) this.timer = setTimeout(this.writeBatch.bind(this), this.options.batchDelay);

	// we are firing & forgetting.
	callback();
};
<commit_msg>That was going to be a bug.<commit_after>var
	_      = require('lodash'),
	assert = require('assert'),
	bole   = require('bole'),
	dgram  = require('dgram'),
	events = require('events'),
	stream = require('stream'),
	util   = require('util')
;

var GraphiteUDP = module.exports = function GraphiteUDP(opts)
{
	assert(opts && _.isObject(opts), 'you must pass an options object');
	assert(opts.host && _.isString(opts.host), 'you must pass a hostname in the `host` option');
	assert(opts.port && _.isNumber(opts.port), 'you must pass a `port` option');

	stream.Writable.call(this, { objectMode: true });
	if (!opts.batchDelay || !_.isNumber(opts.batchDelay)) opts.batchDelay = 5000; // in ms

	this.socket = dgram.createSocket('udp4');
	this.socket.on('error', this.onError.bind(this));

	this.options = opts;
	this.log = bole('graphite ' + opts.host + ':' + opts.port);
	this.log.info('graphite output configured @ ' + opts.host + ':' + opts.port);
};
util.inherits(GraphiteUDP, stream.Writable);

GraphiteUDP.prototype.socket = null;
GraphiteUDP.prototype.timer = null;
GraphiteUDP.prototype.batch = [];

GraphiteUDP.prototype.onError = function onError(err)
{
	this.log.error('socket error');
	this.log.error(err);
};

GraphiteUDP.prototype.writeBatch = function writeBatch()
{
	var self = this;
	var data = new Buffer(this.batch.join('\n'));
	this.socket.send(data, 0, data.length, this.options.port, this.options.host, function(err, written)
	{
		if (err)
		{
			self.log.error('problem writing to graphite');
			self.log.error(err);
		}
		// TODO consider retrying and stuff
	});

	this.batch = [];
	this.timer = null;
};

GraphiteUDP.prototype._write = function _write(event, encoding, callback)
{
	if (!event.hasOwnProperty('name') || !event.hasOwnProperty('value'))
	{
		this.log.info(event, 'declining to write malformed metric to graphite', event);
		callback();
		return;
	}

	// timestamps must be unix epoch time in seconds
	var ts = event.time;
	if (!ts) ts = new Date();
	if (_.isObject(ts)) ts = Math.round(ts.getTime() / 1000);

	// graphite message format is name<space>value<space>timestamp
	this.batch.push([event.name, event.value, ts].join(' '));

	if (!this.timer) this.timer = setTimeout(this.writeBatch.bind(this), this.options.batchDelay);

	// we are firing & forgetting.
	callback();
};
<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * Parametric IO Type wrapper that adds support for null values in toStateObject/fromStateObject. This type is to
 * prevent the propagation of null handling, mainly in to/fromStateObject, in each type. This also makes null
 * explicit for phet-io.
 *
 * Sample usage:
 *
 *  this.ageProperty = new Property( null, {
 *    tandem: tandem.createTandem( 'ageProperty' ),
 *    phetioType: PropertyIO( NullableIO( NumberIO ) ) // signifies that the Property can be Number or null
 * } );
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var ObjectIO = require( 'PHET_IO/types/ObjectIO' );

  /**
   * Parametric type constructor function, do not use `new`
   * @param {function} ioType - an IO type (constructor function)
   * @returns {function} - the IO type that supports null
   * @constructor
   */
  function NullableIO( ioType ) {

    // Instantiate the concrete IO type using the specified type parameter
    var NullableIOImpl = function NullableIOImpl( property, phetioID ) {
      ObjectIO.call( this, property, phetioID );
    };

    return phetioInherit( ObjectIO, 'NullableIO', NullableIOImpl, {}, {

      // Signify parameterTypes to phetioInherit
      parameterTypes: [ ioType ],

      // Signify documentation, used in documentation wrappers
      documentation: 'A wrapper to wrap another IOType, adding support for null.',

      /**
       * If the argument is null, returns null.
       * Otherwise converts the instance to a state object for serialization.
       * @param {Object|null} instance - of type {ioType|null}
       * @returns {Object|null}
       * @public
       * @static
       */
      toStateObject: function( instance ) {
        if ( instance === null ) {
          return null;
        }
        else {
          return ioType.toStateObject( instance );
        }
      },

      /**
       * If the argument is null, returns null.
       * Otherwise converts a state object to an instance of the underlying type.
       * @param {Object|null} stateObject
       * @returns {Object|null}
       * @public
       * @static
       */
      fromStateObject: function( stateObject ) {
        if ( stateObject === null ) {
          return null;
        }
        else {
          return ioType.fromStateObject( stateObject );
        }
      }
    } );
  }

  phetioNamespace.register( 'NullableIO', NullableIO );

  return NullableIO;
} );<commit_msg>delete dynamic documentation phet-io wrapper, https://github.com/phetsims/phet-io-wrappers/issues/77<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * Parametric IO Type wrapper that adds support for null values in toStateObject/fromStateObject. This type is to
 * prevent the propagation of null handling, mainly in to/fromStateObject, in each type. This also makes null
 * explicit for phet-io.
 *
 * Sample usage:
 *
 *  this.ageProperty = new Property( null, {
 *    tandem: tandem.createTandem( 'ageProperty' ),
 *    phetioType: PropertyIO( NullableIO( NumberIO ) ) // signifies that the Property can be Number or null
 * } );
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var ObjectIO = require( 'PHET_IO/types/ObjectIO' );

  /**
   * Parametric type constructor function, do not use `new`
   * @param {function} ioType - an IO type (constructor function)
   * @returns {function} - the IO type that supports null
   * @constructor
   */
  function NullableIO( ioType ) {

    // Instantiate the concrete IO type using the specified type parameter
    var NullableIOImpl = function NullableIOImpl( property, phetioID ) {
      ObjectIO.call( this, property, phetioID );
    };

    return phetioInherit( ObjectIO, 'NullableIO', NullableIOImpl, {}, {

      // Signify parameterTypes to phetioInherit
      parameterTypes: [ ioType ],

      // Signify documentation, used in documentation wrappers like PhET-iO Studio.
      documentation: 'A wrapper to wrap another IOType, adding support for null.',

      /**
       * If the argument is null, returns null.
       * Otherwise converts the instance to a state object for serialization.
       * @param {Object|null} instance - of type {ioType|null}
       * @returns {Object|null}
       * @public
       * @static
       */
      toStateObject: function( instance ) {
        if ( instance === null ) {
          return null;
        }
        else {
          return ioType.toStateObject( instance );
        }
      },

      /**
       * If the argument is null, returns null.
       * Otherwise converts a state object to an instance of the underlying type.
       * @param {Object|null} stateObject
       * @returns {Object|null}
       * @public
       * @static
       */
      fromStateObject: function( stateObject ) {
        if ( stateObject === null ) {
          return null;
        }
        else {
          return ioType.fromStateObject( stateObject );
        }
      }
    } );
  }

  phetioNamespace.register( 'NullableIO', NullableIO );

  return NullableIO;
} );<|endoftext|>


<commit_before>var async = require('async'),
  LocalStrategy = require('passport-local').Strategy,
  HashStrategy = require('passport-hash').Strategy,
  GoogleStrategy = require('passport-google').Strategy;

// todo - IMPORTANT
//http://passportjs.org/guide/authorize/

var passportManager={
  'strategies':[],
  'routes':[],
  'initialized':false
};

passportManager.useStrategy = function(strategy){
  if(this.initialized) throw new Error('passportManager is already initialized!');
  this.strategies.push(strategy.strategy);
  this.routes.push(strategy.routes);
};

passportManager.doInitializePassportStrategies = function(passport,core){
  this.initialized=true;
//using default strategies

  //used for username/email and password
  passport.use(new LocalStrategy(
    function (username, password, done) {
      core.model.Users.findOneByLoginOrEmail(username, function (err, user) {
        if (err) {
          return done(err, false);
        } else {
          if (user) {
            if (user.verifyPassword(password)) {
              return done(null, user);
            } else {
              return done(null, false);
            }
          } else {
            return done(null, false);
          }
        }
      });
    })
  );

  //used for verify account by email
  passport.use(new HashStrategy(function (hash, done) {
    core.model.Users.findOneByApiKeyAndVerify(hash, function (err, userFound) {
      done(err, userFound);
    });
  }));

  //use google strategie by default, because it do not requires tunning!

  passport.use(new GoogleStrategy({
      returnURL: core.config.hostUrl + 'auth/google/return',
      realm: core.config.hostUrl
    },
    function (identifier, profile, done) {
      console.log('==============');
      console.log(profile);
      console.log('==============');
      var email = profile.emails[0].value;
      if (email) {
        core.model.Users.processOAuthProfile(email, done);
      } else {
        return done(new Error('There is something strange instead of user profile'));
      }
    }
  ));

  //initializing the pluggable strategies
  this.strategies.map(function(strategy){
    passport.use(strategy(core));
  });

  //Storing user in session, storage key is username
  passport.serializeUser(function (user, done) {
    done(null, user.apiKey);
  });

  //retrieving user from session
  passport.deserializeUser(function (apiKey, done) {
    core.model.Users.findOne({apiKey: apiKey}, function (err, user) {
      done(err, user);
    });
  });
};

passportManager.doInitializePassportRoutes = function (passport, core) {
  this.initialized=true;
  //registration by username, password and email
  //todo - implement the https://npmjs.org/packages/captcha
  core.app.post('/auth/signup', function (request, response) {
    request.model.Users.signUp(request.body.username, request.body.email, request.body.password,
      function (err, userCreated) {
        if(request.is('json')){
          if (err) {
            response.json(400,{
              errors: {form: err.message}
            });
          } else {
            userCreated.notify({'type': 'email', 'subject': "Account confirmation", 'template': 'signin'});
            response.json(201,{
              'username':userCreated.username,
              'email':userCreated.email
            });
          }
        } else {
          if (err) {
            request.flash('error', err.message);
          } else {
            userCreated.notify({'type': 'email', 'subject': "Account confirmation", 'template': 'signin'});
            request.flash('info', 'You have been registered! Please, check your email for instructions!');
          }
          response.redirect('/');
        }
      }
    );
  });

  //verify that login/email is not busy! - to be called by ajax
  core.app.get('/auth/isBusy', function (request, response) {
    async.parallel({
      'username_ok': function (cb) {
        var username = request.query.username;
        if (username) {
          if (/^[a-zA-Z0-9_]{3,32}$/.test(username)) { //username looks OK
            request.model.Users.findOne({'username': username}, function (err, userFound) {
              cb(err, (userFound ? true : false));
            });
          } else {
            cb(null, false);//username looks bad
          }
        } else {
          cb(null, false);//username is empty
        }
      },
      'email_ok': function (cb) {
        var email = request.query.email;
        if (email) {
          // https://github.com/chriso/node-validator/blob/master/lib/validators.js#L27
          if (/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/.test(email)) { //email looks OK
            request.model.Users.findOne({'email': email}, function (err, userFound) {
              cb(err, userFound ? true : false);
            });
          } else {
            cb(null, false);//email looks bad
          }
        } else {
          cb(null, false);//email is empty
        }
      }
    }, function (err, results) {
      if (err) {
        throw err;
      }
      response.json(results)
    });
  });

  //route to complete profile
  core.app.post('/auth/completeProfile', function (request, response) {
    if (request.user) {
      request.user.completeProfile(request.body.username, request.body.password, function (err) {
        if (err) {
          request.flash('error', err.message);
        } else {
          request.flash('success', 'Thanks! Your profile is completed!')
        }
        response.redirect('back');
      });
    } else {
      response.send(403);
    }
  });

  core.app.post('/auth/resetPassword', function (request, response) {
    if (request.body.apiKey && request.body.password) {
      request.model.Users.findOneByApiKeyAndResetPassword(request.body.apiKey, request.body.password, function (err) {
        if (err) {
          request.flash('error', err.message);
        } else {
          request.flash('success', 'Thanks! Your password is reset!')
        }
        response.redirect('/');
      });
    } else {
      response.send(400, 'Wrong request! apiKey and password are missed!');
    }

  });

  //google works alwayes, it do not need tunning
  core.app.get('/auth/google', passport.authenticate('google'));
  core.app.get('/auth/google/return', passport.authenticate('google', { failureRedirect: '/', successRedirect: '/' }));

  //autorization by password and username
  core.app.post('/auth/login', passport.authenticate('local', {successRedirect: '/', failureRedirect: '/', failureFlash: true}));

  //initializing pluggable routes
  this.routes.map(function(strategyRoute){
    strategyRoute(passport,core);
  });

  //acount confirmation by link in email
  core.app.get('/auth/confirm/:hash',
    passport.authenticate('hash', { failureRedirect: '/' }),
    function (req, res) {
      res.redirect('/');
    });

  //because if it were get we can irritate users by  on our site)
  core.app.post('/auth/logout', function (request, response) {
    request.logout();
    response.send(200, 'OK');
  });
}

module.exports = exports = passportManager;<commit_msg>[doc] - removed completed todo<commit_after>var async = require('async'),
  LocalStrategy = require('passport-local').Strategy,
  HashStrategy = require('passport-hash').Strategy,
  GoogleStrategy = require('passport-google').Strategy;

var passportManager={
  'strategies':[],
  'routes':[],
  'initialized':false
};

passportManager.useStrategy = function(strategy){
  if(this.initialized) throw new Error('passportManager is already initialized!');
  this.strategies.push(strategy.strategy);
  this.routes.push(strategy.routes);
};

passportManager.doInitializePassportStrategies = function(passport,core){
  this.initialized=true;
//using default strategies

  //used for username/email and password
  passport.use(new LocalStrategy(
    function (username, password, done) {
      core.model.Users.findOneByLoginOrEmail(username, function (err, user) {
        if (err) {
          return done(err, false);
        } else {
          if (user) {
            if (user.verifyPassword(password)) {
              return done(null, user);
            } else {
              return done(null, false);
            }
          } else {
            return done(null, false);
          }
        }
      });
    })
  );

  //used for verify account by email
  passport.use(new HashStrategy(function (hash, done) {
    core.model.Users.findOneByApiKeyAndVerify(hash, function (err, userFound) {
      done(err, userFound);
    });
  }));

  //use google strategie by default, because it do not requires tunning!

  passport.use(new GoogleStrategy({
      returnURL: core.config.hostUrl + 'auth/google/return',
      realm: core.config.hostUrl
    },
    function (identifier, profile, done) {
      console.log('==============');
      console.log(profile);
      console.log('==============');
      var email = profile.emails[0].value;
      if (email) {
        core.model.Users.processOAuthProfile(email, done);
      } else {
        return done(new Error('There is something strange instead of user profile'));
      }
    }
  ));

  //initializing the pluggable strategies
  this.strategies.map(function(strategy){
    passport.use(strategy(core));
  });

  //Storing user in session, storage key is username
  passport.serializeUser(function (user, done) {
    done(null, user.apiKey);
  });

  //retrieving user from session
  passport.deserializeUser(function (apiKey, done) {
    core.model.Users.findOne({apiKey: apiKey}, function (err, user) {
      done(err, user);
    });
  });
};

passportManager.doInitializePassportRoutes = function (passport, core) {
  this.initialized=true;
  //registration by username, password and email
  //todo - implement the https://npmjs.org/packages/captcha
  core.app.post('/auth/signup', function (request, response) {
    request.model.Users.signUp(request.body.username, request.body.email, request.body.password,
      function (err, userCreated) {
        if(request.is('json')){
          if (err) {
            response.json(400,{
              errors: {form: err.message}
            });
          } else {
            userCreated.notify({'type': 'email', 'subject': "Account confirmation", 'template': 'signin'});
            response.json(201,{
              'username':userCreated.username,
              'email':userCreated.email
            });
          }
        } else {
          if (err) {
            request.flash('error', err.message);
          } else {
            userCreated.notify({'type': 'email', 'subject': "Account confirmation", 'template': 'signin'});
            request.flash('info', 'You have been registered! Please, check your email for instructions!');
          }
          response.redirect('/');
        }
      }
    );
  });

  //verify that login/email is not busy! - to be called by ajax
  core.app.get('/auth/isBusy', function (request, response) {
    async.parallel({
      'username_ok': function (cb) {
        var username = request.query.username;
        if (username) {
          if (/^[a-zA-Z0-9_]{3,32}$/.test(username)) { //username looks OK
            request.model.Users.findOne({'username': username}, function (err, userFound) {
              cb(err, (userFound ? true : false));
            });
          } else {
            cb(null, false);//username looks bad
          }
        } else {
          cb(null, false);//username is empty
        }
      },
      'email_ok': function (cb) {
        var email = request.query.email;
        if (email) {
          // https://github.com/chriso/node-validator/blob/master/lib/validators.js#L27
          if (/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/.test(email)) { //email looks OK
            request.model.Users.findOne({'email': email}, function (err, userFound) {
              cb(err, userFound ? true : false);
            });
          } else {
            cb(null, false);//email looks bad
          }
        } else {
          cb(null, false);//email is empty
        }
      }
    }, function (err, results) {
      if (err) {
        throw err;
      }
      response.json(results)
    });
  });

  //route to complete profile
  core.app.post('/auth/completeProfile', function (request, response) {
    if (request.user) {
      request.user.completeProfile(request.body.username, request.body.password, function (err) {
        if (err) {
          request.flash('error', err.message);
        } else {
          request.flash('success', 'Thanks! Your profile is completed!')
        }
        response.redirect('back');
      });
    } else {
      response.send(403);
    }
  });

  core.app.post('/auth/resetPassword', function (request, response) {
    if (request.body.apiKey && request.body.password) {
      request.model.Users.findOneByApiKeyAndResetPassword(request.body.apiKey, request.body.password, function (err) {
        if (err) {
          request.flash('error', err.message);
        } else {
          request.flash('success', 'Thanks! Your password is reset!')
        }
        response.redirect('/');
      });
    } else {
      response.send(400, 'Wrong request! apiKey and password are missed!');
    }

  });

  //google works alwayes, it do not need tunning
  core.app.get('/auth/google', passport.authenticate('google'));
  core.app.get('/auth/google/return', passport.authenticate('google', { failureRedirect: '/', successRedirect: '/' }));

  //autorization by password and username
  core.app.post('/auth/login', passport.authenticate('local', {successRedirect: '/', failureRedirect: '/', failureFlash: true}));

  //initializing pluggable routes
  this.routes.map(function(strategyRoute){
    strategyRoute(passport,core);
  });

  //acount confirmation by link in email
  core.app.get('/auth/confirm/:hash',
    passport.authenticate('hash', { failureRedirect: '/' }),
    function (req, res) {
      res.redirect('/');
    });

  //because if it were get we can irritate users by  on our site)
  core.app.post('/auth/logout', function (request, response) {
    request.logout();
    response.send(200, 'OK');
  });
}

module.exports = exports = passportManager;<|endoftext|>


<commit_before>(function () {
  var ns = $.namespace('pskl.utils');

  var layersToLoad = 0;

  ns.Serializer = {
    serializePiskel : function (piskel) {
      var serializedLayers = piskel.getLayers().map(function (l) {
        return pskl.utils.Serializer.serializeLayer(l);
      });
      return JSON.stringify({
        modelVersion : Constants.MODEL_VERSION,
        piskel : {
          height : piskel.getHeight(),
          width : piskel.getWidth(),
          layers : serializedLayers
        }
      });
    },

    serializeLayer : function (layer) {
      var frames = layer.getFrames();
      var renderer = new pskl.rendering.FramesheetRenderer(frames);
      var base64PNG = renderer.renderAsCanvas().toDataURL();

      return JSON.stringify({
        name : layer.getName(),
        base64PNG : base64PNG,
        frameCount : frames.length
      });
    },

    deserializePiskel : function (piskelString) {
      var data = JSON.parse(piskelString);
      return this.createPiskel(data);
    },

    /**
     * Similar to deserializePiskel, but dealing directly with a parsed piskel
     * @param  {Object} data JSON.parse of a serialized piskel
     * @return {pskl.model.Piskel} a piskel
     */
    createPiskel : function (data) {
      var piskel = null;
      if (data.modelVersion == Constants.MODEL_VERSION) {
        var piskelData = data.piskel;
        piskel = new pskl.model.Piskel(piskelData.width, piskelData.height);
        layersToLoad = piskelData.layers;
        piskelData.layers.forEach(function (serializedLayer) {
          var layer = pskl.utils.Serializer.deserializeLayer(serializedLayer);
          piskel.addLayer(layer);
        });
      } else if (data.modelVersion == 1) {
        throw 'No backward compatible adapter for modelVersion 1';
      } else {
        piskel = pskl.utils.Serializer.backwardDeserializer_(data);
      }

      return piskel;
    },

    deserializeLayer : function (layerString) {
      var layerData = JSON.parse(layerString);
      var layer = new pskl.model.Layer(layerData.name);
      // TODO : nasty trick to keep the whole loading process lazily synchronous
      // 1 - adding a fake frame so that the rendering can start
      layer.addFrame(new pskl.model.Frame(32,32));

      // 2 - create an image to load the base64PNG representing the layer
      var base64PNG = layerData.base64PNG;
      var image = new Image();

      // 3 - attach the onload callback that will be triggered asynchronously
      image.onload = function () {
        // 6 - remove the fake frame
        layer.removeFrameAt(0);

        // 7 - extract the frames from the loaded image
        var frames = pskl.utils.LayerUtils.createFromImage(image, layerData.frameCount);

        // 8 - add each image to the layer
        frames.forEach(function (frame) {
          layer.addFrame(pskl.model.Frame.fromPixelGrid(frame));
        });
      };

      // 4 - set the source of the image
      image.src = base64PNG;

      // 5 - return a pointer to the new layer instance, which at this point contains a fake frame
      return layer;
    },

    deserializeLayer_v1 : function (layerString) {
      var layerData = JSON.parse(layerString);
      var layer = new pskl.model.Layer(layerData.name);
      layerData.frames.forEach(function (serializedFrame) {
        var frame = pskl.utils.Serializer.deserializeFrame(serializedFrame);
        layer.addFrame(frame);
      });

      return layer;
    },

    deserializeFrame : function (frameString) {
      var framePixelGrid = JSON.parse(frameString);
      return pskl.model.Frame.fromPixelGrid(framePixelGrid);
    },

    /**
     * Deserialize old piskel framesheets. Initially piskels were stored as arrays of frames : "[[pixelGrid],[pixelGrid],[pixelGrid]]".
     */
    backwardDeserializer_ : function (frames) {
      var layer = new pskl.model.Layer('Layer 1');
      frames.forEach(function (frame) {
        layer.addFrame(pskl.model.Frame.fromPixelGrid(frame));
      });
      var width = layer.getFrameAt(0).getWidth(), height = layer.getFrameAt(0).getHeight();
      var piskel = new pskl.model.Piskel(width, height);
      piskel.addLayer(layer);

      return piskel;
    }
  };
})();
<commit_msg>fix : reduce piskel model size<commit_after>(function () {
  var ns = $.namespace('pskl.utils');

  var layersToLoad = 0;

  ns.Serializer = {
    serializePiskel : function (piskel) {
      var serializedLayers = piskel.getLayers().map(function (l) {
        return pskl.utils.Serializer.serializeLayer(l);
      });
      return JSON.stringify({
        modelVersion : Constants.MODEL_VERSION,
        piskel : {
          height : piskel.getHeight(),
          width : piskel.getWidth(),
          layers : serializedLayers
        }
      });
    },

    serializeLayer : function (layer) {
      var frames = layer.getFrames();
      var renderer = new pskl.rendering.FramesheetRenderer(frames);
      var base64PNG = renderer.renderAsCanvas().toDataURL();

      return JSON.stringify({
        name : layer.getName(),
        base64PNG : base64PNG,
        frameCount : frames.length
      });
    },

    /**
     * @param  {Object} data JSON.parse of a serialized piskel
     * @return {pskl.model.Piskel} a piskel
     */
    createPiskel : function (data) {
      var piskel = null;
      if (data.modelVersion == Constants.MODEL_VERSION) {
        var piskelData = data.piskel;
        piskel = new pskl.model.Piskel(piskelData.width, piskelData.height);

        piskelData.layers.forEach(function (serializedLayer) {
          var layer = pskl.utils.Serializer.deserializeLayer(serializedLayer);
          piskel.addLayer(layer);
        });
      } else if (data.modelVersion == 1) {
        piskel = pskl.utils.Serializer.backwardDeserializer_v1(data);
      } else {
        piskel = pskl.utils.Serializer.backwardDeserializer_(data);
      }

      return piskel;
    },

    deserializeLayer : function (layerString) {
      var layerData = JSON.parse(layerString);
      var layer = new pskl.model.Layer(layerData.name);
      // TODO : nasty trick to keep the whole loading process lazily synchronous
      // 1 - adding a fake frame so that the rendering can start
      layer.addFrame(new pskl.model.Frame(32,32));

      // 2 - create an image to load the base64PNG representing the layer
      var base64PNG = layerData.base64PNG;
      var image = new Image();

      // 3 - attach the onload callback that will be triggered asynchronously
      image.onload = function () {
        // 6 - remove the fake frame
        layer.removeFrameAt(0);

        // 7 - extract the frames from the loaded image
        var frames = pskl.utils.LayerUtils.createFromImage(image, layerData.frameCount);

        // 8 - add each image to the layer
        frames.forEach(function (frame) {
          layer.addFrame(pskl.model.Frame.fromPixelGrid(frame));
        });
      };

      // 4 - set the source of the image
      image.src = base64PNG;

      // 5 - return a pointer to the new layer instance, which at this point contains a fake frame
      return layer;
    },

    deserializeFrame : function (frameString) {
      var framePixelGrid = JSON.parse(frameString);
      return pskl.model.Frame.fromPixelGrid(framePixelGrid);
    },

    backwardDeserializer_v1 : function (data) {
      var piskelData = data.piskel;
      var piskel = new pskl.model.Piskel(piskelData.width, piskelData.height);

      piskelData.layers.forEach(function (serializedLayer) {
        var layer = pskl.utils.Serializer.deserializeLayer_v1(serializedLayer);
        piskel.addLayer(layer);
      });

      return piskel;
    },

    deserializeLayer_v1 : function (layerString) {
      var layerData = JSON.parse(layerString);
      var layer = new pskl.model.Layer(layerData.name);
      layerData.frames.forEach(function (serializedFrame) {
        var frame = pskl.utils.Serializer.deserializeFrame(serializedFrame);
        layer.addFrame(frame);
      });

      return layer;
    },

    /**
     * Deserialize old piskel framesheets. Initially piskels were stored as arrays of frames : "[[pixelGrid],[pixelGrid],[pixelGrid]]".
     */
    backwardDeserializer_ : function (frames) {
      var layer = new pskl.model.Layer('Layer 1');
      frames.forEach(function (frame) {
        layer.addFrame(pskl.model.Frame.fromPixelGrid(frame));
      });
      var width = layer.getFrameAt(0).getWidth(), height = layer.getFrameAt(0).getHeight();
      var piskel = new pskl.model.Piskel(width, height);
      piskel.addLayer(layer);

      return piskel;
    }
  };
})();
<|endoftext|>


<commit_before>/*
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

export const exportDB = '{{#each cols}}\n' +
'mongoexport{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}} --db {{database}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if pretty}} --pretty{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if noHeaderLine}} --noHeaderLine{{/if}}{{#if exportType}} --type {{exportType}}{{/if}}{{#if outputFields}} --fields {{outputFields}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if skip}} --skip {{skip}}{{/if}}{{#if limit}} --limit {{limit}}{{/if}}{{#if exportSort}} --sort {{exportSort}}{{/if}}{{#if assertExists}} --assertExists{{/if}}{{#if output}} -o {{output}}{{/if}} \n'
+ '{{/each}}';

export const dumpDB = '{{#each cols}}\n' +
'mongodump{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}} --db {{database}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o {{output}}{{/if}} \n'
+ '{{/each}}';

export const dumpServer = '{{#each cols}}\n' +
'mongodump{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o {{output}}{{/if}} \n'
+ '{{/each}}';

export const restoreServer =
'mongorestore{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if objcheck}} --objcheck{{/if}}{{#if oplogReplay}} --oplogReplay{{/if}}{{#if oplogLimit}} --oplogLimit {{oplogLimit}}{{/if}}{{#if restoreDbUsersAndRoles}} --restoreDbUsersAndRoles{{/if}}{{#if gzip}} --gzip{{/if}}{{#if drop}} --drop{{/if}}{{#if dryRun}} -dryRun{{/if}}{{#if writeConcern}} --writeConcern {{writeConcern}}{{/if}}{{#if noIndexRestore}} --noIndexRestore{{/if}}{{#if noOptionsRestore}} --noOptionsRestore{{/if}}{{#if keepIndexVersion}} --keepIndexVersion{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if numInsertionWorkersPerCollection}} --numInsertionWorkersPerCollection {{numInsertionWorkersPerCollection}}{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} {{inputFile}}{{/if}}';

export const importCollection =
  'mongoimport{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if outputFields}} --fields {{outputFields}}{{/if}}{{#if headerLine}} --headerLine{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if parseGrace}} --parseGrace {{parseGrace}}{{/if}}{{#if outputType}} --type {{outputType}}{{/if}}{{#if columnsHaveTypes}} --columnsHaveTypes {{columnsHaveTypes}}{{/if}}{{#if drop}} --drop{{/if}}{{#if ignoreBlanks}} --ignoreBlanks{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numInsertionWorkers}} --numInsertionWorkers {{numInsertionWorkers}}{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if mode}} --mode {{mode}}{{/if}}{{#if upsertFields}} --upsertFields {{upsertFields}}{{/if}}{{#if writeConcern}} --writeConcern {{writeConcern}}{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} {{inputFile}}{{/if}}';
<commit_msg>fix enter different for platforms<commit_after>/*
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

import os from 'os';

const enter = os.release().indexOf('Windows') >= 0 ? '\r\n' : '\n';

export const exportDB = '{{#each cols}}\n' +
'mongoexport{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}} --db {{database}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if pretty}} --pretty{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if noHeaderLine}} --noHeaderLine{{/if}}{{#if exportType}} --type {{exportType}}{{/if}}{{#if outputFields}} --fields {{outputFields}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if skip}} --skip {{skip}}{{/if}}{{#if limit}} --limit {{limit}}{{/if}}{{#if exportSort}} --sort {{exportSort}}{{/if}}{{#if assertExists}} --assertExists{{/if}}{{#if output}} -o {{output}}{{/if}} ' + enter
+ '{{/each}}';

export const dumpDB = '{{#each cols}}\n' +
'mongodump{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}} --db {{database}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o {{output}}{{/if}} ' + enter
+ '{{/each}}';

export const dumpServer = '{{#each cols}}\n' +
'mongodump{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if query}} -q {{query}}{{/if}}{{#if readPreference}} --readPreference {{readPreference}}{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o {{output}}{{/if}} ' + enter
+ '{{/each}}';

export const restoreServer =
'mongorestore{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if objcheck}} --objcheck{{/if}}{{#if oplogReplay}} --oplogReplay{{/if}}{{#if oplogLimit}} --oplogLimit {{oplogLimit}}{{/if}}{{#if restoreDbUsersAndRoles}} --restoreDbUsersAndRoles{{/if}}{{#if gzip}} --gzip{{/if}}{{#if drop}} --drop{{/if}}{{#if dryRun}} -dryRun{{/if}}{{#if writeConcern}} --writeConcern {{writeConcern}}{{/if}}{{#if noIndexRestore}} --noIndexRestore{{/if}}{{#if noOptionsRestore}} --noOptionsRestore{{/if}}{{#if keepIndexVersion}} --keepIndexVersion{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numParallelCollections}} --numParallelCollections {{numParallelCollections}}{{/if}}{{#if numInsertionWorkersPerCollection}} --numInsertionWorkersPerCollection {{numInsertionWorkersPerCollection}}{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} {{inputFile}}{{/if}}';

export const importCollection =
  'mongoimport{{#if host}} --host {{host}}{{/if}}{{#if port}} --port {{port}}{{/if}}{{#if database}} --db {{database}}{{/if}}{{#if collection}} --collection {{collection}}{{/if}}{{#if username}} -u {{username}}{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase {{authDb}}{{/if}}{{#if outputFields}} --fields {{outputFields}}{{/if}}{{#if headerLine}} --headerLine{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if parseGrace}} --parseGrace {{parseGrace}}{{/if}}{{#if outputType}} --type {{outputType}}{{/if}}{{#if columnsHaveTypes}} --columnsHaveTypes {{columnsHaveTypes}}{{/if}}{{#if drop}} --drop{{/if}}{{#if ignoreBlanks}} --ignoreBlanks{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numInsertionWorkers}} --numInsertionWorkers {{numInsertionWorkers}}{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if mode}} --mode {{mode}}{{/if}}{{#if upsertFields}} --upsertFields {{upsertFields}}{{/if}}{{#if writeConcern}} --writeConcern {{writeConcern}}{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} {{inputFile}}{{/if}}';
<|endoftext|>


<commit_before>/*
 * vim: ts=4:sw=4:expandtab
 */
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var SocketView = Whisper.View.extend({
        className: 'status',
        initialize: function() {
            setInterval(this.updateStatus.bind(this), 5000);
        },
        updateStatus: function() {
            var className, message = '';
            switch(getSocketStatus && getSocketStatus()) {
                case WebSocket.CONNECTING:
                    className = 'connecting';
                    break;
                case WebSocket.OPEN:
                    className = 'open';
                    break;
                case WebSocket.CLOSING:
                    className = 'closing';
                    break;
                case WebSocket.CLOSED:
                    className = 'closed';
                    message = i18n('disconnected');
                    break;
            }
            if (!this.$el.hasClass(className)) {
                this.$el.attr('class', className);
                this.$el.text(message);
            }
        }
    });

    Whisper.ConversationStack = Whisper.View.extend({
        className: 'conversation-stack',
        open: function(conversation) {
            var id = 'conversation-' + conversation.cid;
            if (id !== this.el.firstChild.id) {
                this.$el.first().find('video, audio').each(function() {
                    this.pause();
                });
                var $el = this.$('#'+id);
                if ($el === null || $el.length === 0) {
                    var view = new Whisper.ConversationView({
                        model: conversation,
                        appWindow: this.model.appWindow
                    });
                    $el = view.$el;
                }
                $el.prependTo(this.el);
                conversation.trigger('opened');
            }
        }
    });

    Whisper.FontSizeView = Whisper.View.extend({
        defaultSize: 14,
        maxSize: 30,
        minSize: 14,
        initialize: function() {
            this.currentSize = this.defaultSize;
            this.render();
        },
        events: { 'mousewheel': 'zoomText' },
        zoomText: function(e) {
            if (e.ctrlKey === true) {
                if (e.originalEvent.deltaY > 0) {
                    if (this.currentSize > this.minSize) {
                        this.currentSize--;
                        this.render();
                    }
                } else if (e.originalEvent.deltaY < 0) {
                    if (this.currentSize < this.maxSize) {
                        this.currentSize++;
                        this.render();
                    }
                }
            }
        },
        render: function() {
            this.$el.css('font-size', this.currentSize + 'px');
        }
    });

    Whisper.InboxView = Whisper.View.extend({
        templateName: 'two-column',
        className: 'inbox',
        initialize: function (options) {
            this.render();
            new Whisper.FontSizeView({ el: this.el });
            this.conversation_stack = new Whisper.ConversationStack({
                el: this.$('.conversation-stack'),
                model: { appWindow: options.appWindow }
            });

            var inboxCollection = getInboxCollection();
            this.inboxListView = new Whisper.ConversationListView({
                el         : this.$('.inbox'),
                collection : inboxCollection
            }).render();

            this.inboxListView.listenTo(inboxCollection,
                    'add change:timestamp change:name change:number',
                    this.inboxListView.sort);

            this.searchView = new Whisper.ConversationSearchView({
                el    : this.$('.search-results'),
                input : this.$('input.search')
            });

            this.searchView.$el.hide();

            this.listenTo(this.searchView, 'hide', function() {
                this.searchView.$el.hide();
                this.inboxListView.$el.show();
            });
            this.listenTo(this.searchView, 'show', function() {
                this.searchView.$el.show();
                this.inboxListView.$el.hide();
            });
            this.listenTo(this.searchView, 'open',
                this.openConversation.bind(this, null));

            new SocketView().render().$el.appendTo(this.$('.socket-status'));

            extension.windows.onClosed(function() {
                this.inboxListView.stopListening();
            }.bind(this));

            if (extension.expired()) {
                var banner = new Whisper.ExpiredAlertBanner().render();
                banner.$el.prependTo(this.$el);
                this.$el.addClass('expired');
            }
        },
        render_attributes: {
            welcomeToSignal         : i18n('welcomeToSignal'),
            selectAContact          : i18n('selectAContact'),
            searchForPeopleOrGroups : i18n('searchForPeopleOrGroups'),
            submitDebugLog          : i18n('submitDebugLog'),
            settings                : i18n('settings'),
            restartSignal           : i18n('restartSignal'),
        },
        events: {
            'click': 'onClick',
            'click #header': 'focusHeader',
            'click .conversation': 'focusConversation',
            'click .global-menu .hamburger': 'toggleMenu',
            'click .show-debug-log': 'showDebugLog',
            'click .showSettings': 'showSettings',
            'select .gutter .conversation-list-item': 'openConversation',
            'input input.search': 'filterContacts',
            'click .restart-signal': 'reloadBackgroundPage',
            'show .lightbox': 'showLightbox'
        },
        focusConversation: function(e) {
            if (e && this.$(e.target).closest('.placeholder').length) {
                return;
            }

            this.$('#header, .gutter').addClass('inactive');
            this.$('.conversation-stack').removeClass('inactive');
        },
        focusHeader: function() {
            this.$('.conversation-stack').addClass('inactive');
            this.$('#header, .gutter').removeClass('inactive');
            this.$('.conversation:first .menu').trigger('close');
        },
        reloadBackgroundPage: function() {
            chrome.runtime.reload();
        },
        showSettings: function() {
            var view = new Whisper.SettingsView().render();
            view.update();
            view.$el.appendTo(this.el);
        },
        filterContacts: function(e) {
            this.searchView.filterContacts(e);
            var input = this.$('input.search');
            if (input.val().length > 0) {
                input.addClass('active');
            } else {
                input.removeClass('active');
            }
        },
        openConversation: function(e, conversation) {
            this.searchView.hideHints();
            conversation = ConversationController.create(conversation);
            this.conversation_stack.open(conversation);
            this.focusConversation();
        },
        toggleMenu: function() {
            this.$('.global-menu .menu-list').toggle();
        },
        showDebugLog: function() {
            this.$('.debug-log').remove();
            new Whisper.DebugLogView().$el.appendTo(this.el);
        },
        showLightbox: function(e) {
            this.$el.append(e.target);
        },
        closeRecording: function(e) {
            if (e && this.$(e.target).closest('.capture-audio').length > 0 ) {
                return;
            }
            this.$('.conversation:first .audio-capture').trigger('close');
        },
        closeMenu: function(e) {
            if (e && this.$(e.target).parent('.global-menu').length > 0 ) {
                return;
            }

            this.$('.global-menu .menu-list').hide();
        },
        onClick: function(e) {
            this.closeMenu(e);
            this.closeRecording(e);
        }
    });

    Whisper.ExpiredAlertBanner = Whisper.View.extend({
        templateName: 'expired_alert',
        className: 'expiredAlert clearfix',
        render_attributes: function() {
            return {
                expiredWarning: i18n('expiredWarning'),
                upgrade: i18n('upgrade'),
            };
        }
    });

})();
<commit_msg>Fix closing recorder when clicking away<commit_after>/*
 * vim: ts=4:sw=4:expandtab
 */
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var SocketView = Whisper.View.extend({
        className: 'status',
        initialize: function() {
            setInterval(this.updateStatus.bind(this), 5000);
        },
        updateStatus: function() {
            var className, message = '';
            switch(getSocketStatus && getSocketStatus()) {
                case WebSocket.CONNECTING:
                    className = 'connecting';
                    break;
                case WebSocket.OPEN:
                    className = 'open';
                    break;
                case WebSocket.CLOSING:
                    className = 'closing';
                    break;
                case WebSocket.CLOSED:
                    className = 'closed';
                    message = i18n('disconnected');
                    break;
            }
            if (!this.$el.hasClass(className)) {
                this.$el.attr('class', className);
                this.$el.text(message);
            }
        }
    });

    Whisper.ConversationStack = Whisper.View.extend({
        className: 'conversation-stack',
        open: function(conversation) {
            var id = 'conversation-' + conversation.cid;
            if (id !== this.el.firstChild.id) {
                this.$el.first().find('video, audio').each(function() {
                    this.pause();
                });
                var $el = this.$('#'+id);
                if ($el === null || $el.length === 0) {
                    var view = new Whisper.ConversationView({
                        model: conversation,
                        appWindow: this.model.appWindow
                    });
                    $el = view.$el;
                }
                $el.prependTo(this.el);
                conversation.trigger('opened');
            }
        }
    });

    Whisper.FontSizeView = Whisper.View.extend({
        defaultSize: 14,
        maxSize: 30,
        minSize: 14,
        initialize: function() {
            this.currentSize = this.defaultSize;
            this.render();
        },
        events: { 'mousewheel': 'zoomText' },
        zoomText: function(e) {
            if (e.ctrlKey === true) {
                if (e.originalEvent.deltaY > 0) {
                    if (this.currentSize > this.minSize) {
                        this.currentSize--;
                        this.render();
                    }
                } else if (e.originalEvent.deltaY < 0) {
                    if (this.currentSize < this.maxSize) {
                        this.currentSize++;
                        this.render();
                    }
                }
            }
        },
        render: function() {
            this.$el.css('font-size', this.currentSize + 'px');
        }
    });

    Whisper.InboxView = Whisper.View.extend({
        templateName: 'two-column',
        className: 'inbox',
        initialize: function (options) {
            this.render();
            new Whisper.FontSizeView({ el: this.el });
            this.conversation_stack = new Whisper.ConversationStack({
                el: this.$('.conversation-stack'),
                model: { appWindow: options.appWindow }
            });

            var inboxCollection = getInboxCollection();
            this.inboxListView = new Whisper.ConversationListView({
                el         : this.$('.inbox'),
                collection : inboxCollection
            }).render();

            this.inboxListView.listenTo(inboxCollection,
                    'add change:timestamp change:name change:number',
                    this.inboxListView.sort);

            this.searchView = new Whisper.ConversationSearchView({
                el    : this.$('.search-results'),
                input : this.$('input.search')
            });

            this.searchView.$el.hide();

            this.listenTo(this.searchView, 'hide', function() {
                this.searchView.$el.hide();
                this.inboxListView.$el.show();
            });
            this.listenTo(this.searchView, 'show', function() {
                this.searchView.$el.show();
                this.inboxListView.$el.hide();
            });
            this.listenTo(this.searchView, 'open',
                this.openConversation.bind(this, null));

            new SocketView().render().$el.appendTo(this.$('.socket-status'));

            extension.windows.onClosed(function() {
                this.inboxListView.stopListening();
            }.bind(this));

            if (extension.expired()) {
                var banner = new Whisper.ExpiredAlertBanner().render();
                banner.$el.prependTo(this.$el);
                this.$el.addClass('expired');
            }
        },
        render_attributes: {
            welcomeToSignal         : i18n('welcomeToSignal'),
            selectAContact          : i18n('selectAContact'),
            searchForPeopleOrGroups : i18n('searchForPeopleOrGroups'),
            submitDebugLog          : i18n('submitDebugLog'),
            settings                : i18n('settings'),
            restartSignal           : i18n('restartSignal'),
        },
        events: {
            'click': 'onClick',
            'click #header': 'focusHeader',
            'click .conversation': 'focusConversation',
            'click .global-menu .hamburger': 'toggleMenu',
            'click .show-debug-log': 'showDebugLog',
            'click .showSettings': 'showSettings',
            'select .gutter .conversation-list-item': 'openConversation',
            'input input.search': 'filterContacts',
            'click .restart-signal': 'reloadBackgroundPage',
            'show .lightbox': 'showLightbox'
        },
        focusConversation: function(e) {
            if (e && this.$(e.target).closest('.placeholder').length) {
                return;
            }

            this.$('#header, .gutter').addClass('inactive');
            this.$('.conversation-stack').removeClass('inactive');
        },
        focusHeader: function() {
            this.$('.conversation-stack').addClass('inactive');
            this.$('#header, .gutter').removeClass('inactive');
            this.$('.conversation:first .menu').trigger('close');
        },
        reloadBackgroundPage: function() {
            chrome.runtime.reload();
        },
        showSettings: function() {
            var view = new Whisper.SettingsView().render();
            view.update();
            view.$el.appendTo(this.el);
        },
        filterContacts: function(e) {
            this.searchView.filterContacts(e);
            var input = this.$('input.search');
            if (input.val().length > 0) {
                input.addClass('active');
            } else {
                input.removeClass('active');
            }
        },
        openConversation: function(e, conversation) {
            this.searchView.hideHints();
            conversation = ConversationController.create(conversation);
            this.conversation_stack.open(conversation);
            this.focusConversation();
        },
        toggleMenu: function() {
            this.$('.global-menu .menu-list').toggle();
        },
        showDebugLog: function() {
            this.$('.debug-log').remove();
            new Whisper.DebugLogView().$el.appendTo(this.el);
        },
        showLightbox: function(e) {
            this.$el.append(e.target);
        },
        closeRecording: function(e) {
            if (e && this.$(e.target).closest('.capture-audio').length > 0 ) {
                return;
            }
            this.$('.conversation:first .recorder').trigger('close');
        },
        closeMenu: function(e) {
            if (e && this.$(e.target).parent('.global-menu').length > 0 ) {
                return;
            }

            this.$('.global-menu .menu-list').hide();
        },
        onClick: function(e) {
            this.closeMenu(e);
            this.closeRecording(e);
        }
    });

    Whisper.ExpiredAlertBanner = Whisper.View.extend({
        templateName: 'expired_alert',
        className: 'expiredAlert clearfix',
        render_attributes: function() {
            return {
                expiredWarning: i18n('expiredWarning'),
                upgrade: i18n('upgrade'),
            };
        }
    });

})();
<|endoftext|>


<commit_before>/**
 * @Last modified by:   guiguan
 * @Last modified time: 2018-01-17T13:25:22+11:00
 *
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

import os from 'os';

const enter = os.release().indexOf('Windows') >= 0 ? '\r\n' : '\n';

export const exportDB = '{{#each cols}}\n' +
'mongoexport{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}} --db "{{{escapeDoubleQuotes database}}}"{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if pretty}} --pretty{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if noHeaderLine}} --noHeaderLine{{/if}}{{#if exportType}} --type "{{{escapeDoubleQuotes exportType}}}"{{/if}}{{#if outputFields}} --fields "{{{escapeDoubleQuotes outputFields}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if skip}} --skip "{{{escapeDoubleQuotes skip}}}"{{/if}}{{#if limit}} --limit "{{{escapeDoubleQuotes limit}}}"{{/if}}{{#if exportSort}} --sort "{{{escapeDoubleQuotes exportSort}}}"{{/if}}{{#if assertExists}} --assertExists{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const dumpDB = '{{#each cols}}\n' +
'mongodump{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}} --db "{{{escapeDoubleQuotes database}}}"{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const dumpServer = '{{#each cols}}\n' +
'mongodump{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const restoreServer =
'mongorestore{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if objcheck}} --objcheck{{/if}}{{#if oplogReplay}} --oplogReplay{{/if}}{{#if oplogLimit}} --oplogLimit "{{{escapeDoubleQuotes oplogLimit}}}"{{/if}}{{#if restoreDbUsersAndRoles}} --restoreDbUsersAndRoles{{/if}}{{#if gzip}} --gzip{{/if}}{{#if drop}} --drop{{/if}}{{#if dryRun}} --dryRun{{/if}}{{#if writeConcern}} --writeConcern "{{{escapeDoubleQuotes writeConcern}}}"{{/if}}{{#if noIndexRestore}} --noIndexRestore{{/if}}{{#if noOptionsRestore}} --noOptionsRestore{{/if}}{{#if keepIndexVersion}} --keepIndexVersion{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if numInsertionWorkersPerCollection}} --numInsertionWorkersPerCollection {{{numInsertionWorkersPerCollection}}}{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} "{{{escapeDoubleQuotes inputFile}}}"{{/if}}';

export const importCollection =
  'mongoimport{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if outputFields}} --fields "{{{escapeDoubleQuotes outputFields}}}"{{/if}}{{#if headerLine}} --headerLine{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if parseGrace}} --parseGrace "{{{escapeDoubleQuotes parseGrace}}}"{{/if}}{{#if outputType}} --type "{{{escapeDoubleQuotes outputType}}}"{{/if}}{{#if columnsHaveTypes}} --columnsHaveTypes "{{{escapeDoubleQuotes columnsHaveTypes}}}"{{/if}}{{#if drop}} --drop{{/if}}{{#if ignoreBlanks}} --ignoreBlanks{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numInsertionWorkers}} --numInsertionWorkers "{{{escapeDoubleQuotes numInsertionWorkers}}}"{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if mode}} --mode "{{{escapeDoubleQuotes mode}}}"{{/if}}{{#if upsertFields}} --upsertFields "{{{escapeDoubleQuotes upsertFields}}}"{{/if}}{{#if writeConcern}} --writeConcern "{{{escapeDoubleQuotes writeConcern}}}"{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} "{{{escapeDoubleQuotes inputFile}}}"{{/if}}';
<commit_msg>Fixed mongorestore template<commit_after>/**
 * @Last modified by:   guiguan
 * @Last modified time: 2018-01-23T12:47:29+11:00
 *
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

import os from 'os';

const enter = os.release().indexOf('Windows') >= 0 ? '\r\n' : '\n';

export const exportDB = '{{#each cols}}\n' +
'mongoexport{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}} --db "{{{escapeDoubleQuotes database}}}"{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if pretty}} --pretty{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if noHeaderLine}} --noHeaderLine{{/if}}{{#if exportType}} --type "{{{escapeDoubleQuotes exportType}}}"{{/if}}{{#if outputFields}} --fields "{{{escapeDoubleQuotes outputFields}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if skip}} --skip "{{{escapeDoubleQuotes skip}}}"{{/if}}{{#if limit}} --limit "{{{escapeDoubleQuotes limit}}}"{{/if}}{{#if exportSort}} --sort "{{{escapeDoubleQuotes exportSort}}}"{{/if}}{{#if assertExists}} --assertExists{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const dumpDB = '{{#each cols}}\n' +
'mongodump{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}} --db "{{{escapeDoubleQuotes database}}}"{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const dumpServer = '{{#each cols}}\n' +
'mongodump{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if gzip}} --gzip{{/if}}{{#if repair}} --repair{{/if}}{{#if oplog}} --oplog{{/if}}{{#if dumpDbUsersAndRoles}} --dumpDbUsersAndRoles{{/if}}{{#if viewsAsCollections}} --viewsAsCollections{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if query}} -q "{{{escapeDoubleQuotes query}}}"{{/if}}{{#if readPreference}} --readPreference "{{{escapeDoubleQuotes readPreference}}}"{{/if}}{{#if forceTableScan}} --forceTableScan{{/if}}{{#if output}} -o "{{{escapeDoubleQuotes output}}}"{{/if}} ' + enter
+ '{{/each}}';

export const restoreServer =
'mongorestore{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if objcheck}} --objcheck{{/if}}{{#if oplogReplay}} --oplogReplay{{/if}}{{#if oplogLimit}} --oplogLimit "{{{escapeDoubleQuotes oplogLimit}}}"{{/if}}{{#if restoreDbUsersAndRoles}} --restoreDbUsersAndRoles{{/if}}{{#if gzip}} --gzip{{/if}}{{#if drop}} --drop{{/if}}{{#if dryRun}} --dryRun{{/if}}{{#if writeConcern}} --writeConcern "{{{escapeDoubleQuotes writeConcern}}}"{{/if}}{{#if noIndexRestore}} --noIndexRestore{{/if}}{{#if noOptionsRestore}} --noOptionsRestore{{/if}}{{#if keepIndexVersion}} --keepIndexVersion{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numParallelCollections}} --numParallelCollections "{{{escapeDoubleQuotes numParallelCollections}}}"{{/if}}{{#if numInsertionWorkersPerCollection}} --numInsertionWorkersPerCollection "{{{numInsertionWorkersPerCollection}}}"{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} "{{{escapeDoubleQuotes inputFile}}}"{{/if}}';

export const importCollection =
  'mongoimport{{#if host}} --host "{{{escapeDoubleQuotes host}}}"{{/if}}{{#if port}} --port "{{{escapeDoubleQuotes port}}}"{{/if}}{{#if database}} --db "{{{escapeDoubleQuotes database}}}"{{/if}}{{#if collection}} --collection "{{{escapeDoubleQuotes collection}}}"{{/if}}{{#if username}} -u "{{{escapeDoubleQuotes username}}}"{{/if}}{{#if password}} -p ******{{/if}}{{#if ssl}} --ssl{{/if}}{{#if authDb}} --authenticationDatabase "{{{escapeDoubleQuotes authDb}}}"{{/if}}{{#if outputFields}} --fields "{{{escapeDoubleQuotes outputFields}}}"{{/if}}{{#if headerLine}} --headerLine{{/if}}{{#if jsonArray}} --jsonArray{{/if}}{{#if parseGrace}} --parseGrace "{{{escapeDoubleQuotes parseGrace}}}"{{/if}}{{#if outputType}} --type "{{{escapeDoubleQuotes outputType}}}"{{/if}}{{#if columnsHaveTypes}} --columnsHaveTypes "{{{escapeDoubleQuotes columnsHaveTypes}}}"{{/if}}{{#if drop}} --drop{{/if}}{{#if ignoreBlanks}} --ignoreBlanks{{/if}}{{#if maintainInsertionOrder}} --maintainInsertionOrder{{/if}}{{#if numInsertionWorkers}} --numInsertionWorkers "{{{escapeDoubleQuotes numInsertionWorkers}}}"{{/if}}{{#if stopOnError}} --stopOnError{{/if}}{{#if mode}} --mode "{{{escapeDoubleQuotes mode}}}"{{/if}}{{#if upsertFields}} --upsertFields "{{{escapeDoubleQuotes upsertFields}}}"{{/if}}{{#if writeConcern}} --writeConcern "{{{escapeDoubleQuotes writeConcern}}}"{{/if}}{{#if bypassDocumentValidation}} --bypassDocumentValidation{{/if}}{{#if inputFile}} "{{{escapeDoubleQuotes inputFile}}}"{{/if}}';
<|endoftext|>