<commit_before>var path = require('path');
var os = require('os');
var httpAgent = require('http').Agent;
var httpsAgent = require('https').Agent;
var fse = require('fs-extra');
var pkgConf = require('../package.json');
var config = require('util')._extend(exports, pkgConf);
var now = Date.now();
var variableProperties = ['port', 'sockets', 'timeout', 'dataDirname',
                 		 'username', 'password', 'uipath', 'debug', '_runMode'];

config.WEINRE_HOST = 'weinre.' + config.localUIHost;
config.ASSESTS_PATH = path.join(__dirname, '../assets');
config.HTTPS_FIELD = 'x-' + config.name + '-https-' + now;
config.CLIENT_IP_HEAD = 'x-forwarded-for-' + config.name + '-' + now;
config.HTTPS_FLAG = config.whistleSsl + '.';

function getWhistlePath() {
	var homedir = typeof os.homedir == 'function' ? os.homedir() :
					process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
	return process.env.WHISTLE_PATH || path.join(homedir, '.WhistleAppData');
}

function getDataDir(dirname) {
	var dir = path.join(getWhistlePath(), dirname || '.' + config.name);
	fse.ensureDirSync(dir);
	return dir;
}

exports.getDataDir = getDataDir;

function createAgent(config, https) {
	return new (https ? httpsAgent : httpAgent)(config)
					.on('free', preventThrowOutError);
}

function preventThrowOutError(socket) {
	socket.removeListener('error', freeSocketErrorListener);
	socket.on('error', freeSocketErrorListener);
}

function freeSocketErrorListener(err) {
	var socket = this;
	socket.destroy();
	socket.emit('agentRemove');
	socket.removeListener('error', freeSocketErrorListener);
}

function noop() {}

function resolvePath(file) {
	if (!file || !(file = file.trim())) {
		return file;
	}

	return /^[\w-]+$/.test(file) ? file : path.resolve(file);
}

exports.extend = function extend(newConf) {
	if (newConf) {
		variableProperties.forEach(function(name) {
			config[name] = newConf[name] || pkgConf[name];
		});

		if (Array.isArray(newConf.ports)) {
			config.ports = pkgConf.ports.concat(newConf.ports);
		}

		if (typeof newConf.middlewares == 'string') {
			config.middlewares = newConf.middlewares.trim().split(/\s*,\s*/g);
		}
	}

	config.middlewares = Array.isArray(config.middlewares) ? config.middlewares.map(resolvePath) : [];

	var port = config.port;
	config.ports.forEach(function(name) {
		if (!/port$/.test(name) || name == 'port') {
			throw new Error('port name "' + name + '" must be end of "port", but not equals "port", like: ' + name + 'port');
		}
		config[name] = ++port;
	});

	var agentConfig = {
			maxSockets: config.sockets,
			keepAlive: config.keepAlive,
			keepAliveMsecs: config.keepAliveMsecs
		};
	config.httpAgent = config.debug ? false : createAgent(agentConfig);
	config.httpsAgent = config.debug ? false : createAgent(agentConfig, true);
	config.uipath = config.uipath ? resolvePath(config.uipath) : './webui/app';
	config.DATA_DIR = getDataDir(config.dataDirname);

	return config;
};<commit_msg>feature: debugMode<commit_after>var path = require('path');
var os = require('os');
var httpAgent = require('http').Agent;
var httpsAgent = require('https').Agent;
var fse = require('fs-extra');
var pkgConf = require('../package.json');
var config = require('util')._extend(exports, pkgConf);
var now = Date.now();
var variableProperties = ['port', 'sockets', 'timeout', 'dataDirname',
                 		 'username', 'password', 'uipath', 'debug', 'debugMode'];

config.WEINRE_HOST = 'weinre.' + config.localUIHost;
config.ASSESTS_PATH = path.join(__dirname, '../assets');
config.HTTPS_FIELD = 'x-' + config.name + '-https-' + now;
config.CLIENT_IP_HEAD = 'x-forwarded-for-' + config.name + '-' + now;
config.HTTPS_FLAG = config.whistleSsl + '.';

function getWhistlePath() {
	var homedir = typeof os.homedir == 'function' ? os.homedir() :
					process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
	return process.env.WHISTLE_PATH || path.join(homedir, '.WhistleAppData');
}

function getDataDir(dirname) {
	var dir = path.join(getWhistlePath(), dirname || '.' + config.name);
	fse.ensureDirSync(dir);
	return dir;
}

exports.getDataDir = getDataDir;

function createAgent(config, https) {
	return new (https ? httpsAgent : httpAgent)(config)
					.on('free', preventThrowOutError);
}

function preventThrowOutError(socket) {
	socket.removeListener('error', freeSocketErrorListener);
	socket.on('error', freeSocketErrorListener);
}

function freeSocketErrorListener(err) {
	var socket = this;
	socket.destroy();
	socket.emit('agentRemove');
	socket.removeListener('error', freeSocketErrorListener);
}

function noop() {}

function resolvePath(file) {
	if (!file || !(file = file.trim())) {
		return file;
	}

	return /^[\w-]+$/.test(file) ? file : path.resolve(file);
}

exports.extend = function extend(newConf) {
	if (newConf) {
		variableProperties.forEach(function(name) {
			config[name] = newConf[name] || pkgConf[name];
		});

		if (Array.isArray(newConf.ports)) {
			config.ports = pkgConf.ports.concat(newConf.ports);
		}

		if (typeof newConf.middlewares == 'string') {
			config.middlewares = newConf.middlewares.trim().split(/\s*,\s*/g);
		}
	}

	config.middlewares = Array.isArray(config.middlewares) ? config.middlewares.map(resolvePath) : [];

	var port = config.port;
	config.ports.forEach(function(name) {
		if (!/port$/.test(name) || name == 'port') {
			throw new Error('port name "' + name + '" must be end of "port", but not equals "port", like: ' + name + 'port');
		}
		config[name] = ++port;
	});

	var agentConfig = {
			maxSockets: config.sockets,
			keepAlive: config.keepAlive,
			keepAliveMsecs: config.keepAliveMsecs
		};
	config.httpAgent = config.debug ? false : createAgent(agentConfig);
	config.httpsAgent = config.debug ? false : createAgent(agentConfig, true);
	config.uipath = config.uipath ? resolvePath(config.uipath) : './webui/app';
	config.DATA_DIR = getDataDir(config.dataDirname);

	return config;
};<|endoftext|>


<commit_before>var JSONAPIClient = require('json-api-client');
var Model = JSONAPIClient.Model;
var makeHTTPRequest = JSONAPIClient.makeHTTPRequest;
var ls = require('local-storage');

var config = require('./config');
var apiClient = require('./api-client');

// Use this to override the default API-specific headers.
var JSON_HEADERS = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
};

// We don't want to wait until the token is already expired before refreshing it.
var TOKEN_EXPIRATION_ALLOWANCE = 5 * 60 * 1000;

// Save local storage stuff as something totally obvious
var LOCAL_STORAGE_PREFIX = 'panoptesClientOAuth_';

// Specify whether to use local or session storage for session data.
var SESSION_STORAGE = window.sessionStorage;

// Create our model, then do stuff with it later
module.exports = new Model({
  _bearerRefreshTimeout: NaN,
  _clientAppId: ls.get(LOCAL_STORAGE_PREFIX + 'clientAppId'),
  _currentSessionCheckPromise: null,
  _currentUserPromise: null,
  _tokenDetails: null,

  checkBearerToken: function() {
    var awaitBearerToken;
    if (this._bearerTokenIsExpired()) {
      awaitBearerToken = this._refreshBearerToken();
    } else {
      var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails'));
      awaitBearerToken = Promise.resolve(tokenDetails);
    }
    return awaitBearerToken;
  },

  checkCurrent: function() {
    console.log('Checking current user');

    // If we're checking for an existing session already, defer this until
    // it's finished
    var initialCheck = this._currentSessionCheckPromise || Promise.resolve();

    if (!this._currentUserPromise) {
      this.update({
        _currentUserPromise: initialCheck
          .then(this._getSession)
          .catch(function() {
            // Nobody's signed in. This isn't an error.
            console.info('No current user');
            return null;
          }),
      });
    }

    return this._currentUserPromise;
  },

  init: function (appID) {
    return new Promise(function(resolve, reject) {

      // Don't init if we're in an iFrame, as we could be the token refresh process
      if (window.frameElement) {
        return false;
      }

      console.log('Using OAuth (implicit grant) for login');
      console.info('Setting app ID to', appID);
      ls.get(LOCAL_STORAGE_PREFIX + 'clientAppId', appID);
      this._clientAppId = appID;

      // Handle new token details if we've completed a sign in
      if (checkUrlForToken(window.location.hash)) {
        console.log('Token found in URL');
        var tokenDetails = tokenFromLocation(window.location);
        this._handleNewBearerToken(tokenDetails);

        // And redirect to the desired page
        var url = ls.get(LOCAL_STORAGE_PREFIX + 'redirectUri');
        location.assign(url);
      }

      // If not, let's try and pick up an existing Panoptes session anyway
      this.checkBearerToken()
        .then(function (tokenDetails) {
          this._handleNewBearerToken(tokenDetails);
          resolve(tokenDetails);
        }.bind(this))
        .catch(function (error) {
          // We probably haven't signed in before
          console.info(error);
          resolve(null);
        });

    }.bind(this));

  },

  signIn: function(redirectUri) {
    console.log('Signing in with OAuth');
    var originalArguments = arguments;
    return this.checkCurrent()
      .then(function (token) {
        if (token) {
          return this.signOut().then(function() {
            return this.signIn.apply(this, originalArguments);
          }.bind(this));
        } else {
          this._saveRedirectUri(redirectUri);
          location.assign(this._createOAuthUrl(redirectUri));
        }
      }.bind(this));
  },

  signOut: function() {
    console.log('Signing out');
    return this.checkCurrent().then(function(user) {
      if (user) {
        return this._getAuthToken().then(function(token) {
          var url = config.oauthHost + '/users/sign_out';

          var deleteHeaders = Object.create(JSON_HEADERS);
          deleteHeaders['X-CSRF-Token'] = token;

          return makeHTTPRequest('DELETE', url, null, deleteHeaders)
            .then(function() {
              this._deleteBearerToken();
              this.update({
                _currentUserPromise: Promise.resolve(null),
              });
              console.info('Signed out');
              return null;
            }.bind(this))
            .catch(function(request) {
              console.error('Failed to sign out');
              return apiClient.handleError(request);
            }.bind(this));
        }.bind(this));
      } else {
        throw new Error('Failed to sign out; not signed in');
      }
    }.bind(this));
  },

  _createOAuthUrl: function(redirectUri) {
    if (!this._clientAppId) {
      throw new Error('Client app ID not set');
    }

    return [
      config.oauthHost,
      '/oauth/authorize',
      '?response_type=token',
      '&client_id=',
      this._clientAppId,
      '&redirect_uri=',
      redirectUri
    ].join('');
  },

  _bearerTokenIsExpired: function() {
    var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails'));
    if (tokenDetails) {
      return Date.now() >= tokenDetails.expires_at - TOKEN_EXPIRATION_ALLOWANCE;
    } else {
      return false;
    }
  },

  _checkForPanoptesSession: function() {
    var sessionTokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails'));
    var redirectUri = ls.get(LOCAL_STORAGE_PREFIX + 'redirectUri');
    this.update({
      _currentSessionCheckPromise: new Promise(function(resolve, reject) {
        if (sessionTokenDetails) {
          resolve(sessionTokenDetails);
        }

        if (!redirectUri) {
          reject(Error('No redirect URI found'));
        }

        // Create a new iFrame
        var url = this._createOAuthUrl(redirectUri);
        this._iframe = createIFrame(url);

        // Try and get the token details from our iFrame. If it throws an error,
        // it's because we're being redirected to the signin page (and therefore
        // there is no session) - so we should also replace the security error
        // with a more relevant one.
        this._iframe.onload = function() {
          try {
            var iframeLocation = this._iframe.contentWindow.location;
            if (checkUrlForToken(iframeLocation.hash)) {
              console.info('Found existing Panoptes session');
              var newTokenDetails = tokenFromLocation(iframeLocation);
              resolve(newTokenDetails);
            } else {
              throw new TypeError('Valid OAuth details not found in URL');
            }
          } catch (error) {
            if (error.name === 'SecurityError') {
              console.warn('No existing Panoptes session found');
            }
            reject(error);
          } finally {
            this._iframe = destroyIFrame(this._iframe);
          }
        }.bind(this);
      }.bind(this))
    });

    return this._currentSessionCheckPromise;
  },

  _deleteBearerToken: function() {
    console.log('Deleting bearer token');
    this._tokenDetails = null;
    delete apiClient.headers.Authorization;
    SESSION_STORAGE.removeItem(LOCAL_STORAGE_PREFIX + 'tokenDetails');
  },

  _getAuthToken: function() {
    console.log('Getting auth token');
    var url = config.oauthHost + '/users/sign_in/?now=' + Date.now();
    return makeHTTPRequest('GET', url, null, JSON_HEADERS)
      .then(function(response) {
        var authToken = response.header['x-csrf-token'];
        console.info('Got auth token', authToken.slice(-6));
        return authToken;
      })
      .catch(function(response) {
        console.error('Failed to get auth token');
        apiClient.handleError(response);
      });
  },

  _getSession: function() {
    console.log('Getting session');
    return apiClient.get('/me')
      .then(function(users) {
        var user = users[0];
        console.info('Got session', user.login, user.id);
        return user;
      })
      .catch(function(error) {
        console.error('Failed to get session');
        throw error;
      });
  },

  _handleNewBearerToken: function(tokenDetails) {
    if (tokenDetails && tokenDetails.access_token) {
      console.log('Got new bearer token', tokenDetails.access_token.slice(-6));
      this._tokenDetails = tokenDetails;
      apiClient.headers.Authorization = 'Bearer ' + tokenDetails.access_token;

      var refresh = this._refreshBearerToken.bind(this);
      var timeToRefresh = (tokenDetails.expires_in * 1000) - TOKEN_EXPIRATION_ALLOWANCE;
      this._bearerRefreshTimeout = setTimeout(refresh, timeToRefresh);
      tokenDetails.expires_at = Date.now() + (tokenDetails.expires_in * 1000);
      SESSION_STORAGE.setItem(LOCAL_STORAGE_PREFIX + 'tokenDetails', JSON.stringify(tokenDetails));
    }
    return tokenDetails;
  },

  _refreshBearerToken: function() {
    return this._checkForPanoptesSession()
      .then(function(tokenDetails) {
        return this._handleNewBearerToken(tokenDetails);
      }.bind(this))
      .catch(function (error) {
        console.info('Panoptes session has expired');
        console.log(error);
        this._deleteBearerToken();
        return null;
      });
  },

  _saveRedirectUri: function(redirectUri) {
    console.info('Saving redirectUri:', redirectUri);
    ls.set(LOCAL_STORAGE_PREFIX + 'redirectUri', redirectUri);
  }

});
/*******************************************
  Utility functions
*******************************************/
function checkUrlForToken(string) {
  return string.indexOf('access_token') !== -1 &&
    string.indexOf('token_type=bearer') !== -1;
}

function tokenFromLocation(loc) {
  var params = loc.hash.slice(1).split('&');
  var tokenDetails = {};
  params.forEach(function(paramString) {
    var param = paramString.split('=');
    tokenDetails[param[0]] = param[1];
  });
  return tokenDetails;
}

function createIFrame(url) {
  var iframe = document.createElement('iframe');
  iframe.setAttribute('src', url);
  iframe.setAttribute('style', 'display: none;');
  document.body.appendChild(iframe);
  return iframe;
}

function destroyIFrame(iframe) {
  iframe.parentNode.removeChild(iframe);
  return null;
}
<commit_msg>Replace _checkPanoptesSession with _getNewToken Replaces _checkPanoptesSession() with _getNewToken(), which attempts to get a new token from Panoptes via an iframe. Stored tokens are not returned, since we should only be calling this method when the stored token is about to expire.<commit_after>var JSONAPIClient = require('json-api-client');
var Model = JSONAPIClient.Model;
var makeHTTPRequest = JSONAPIClient.makeHTTPRequest;
var ls = require('local-storage');

var config = require('./config');
var apiClient = require('./api-client');

// Use this to override the default API-specific headers.
var JSON_HEADERS = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
};

// We don't want to wait until the token is already expired before refreshing it.
var TOKEN_EXPIRATION_ALLOWANCE = 5 * 60 * 1000;

// Save local storage stuff as something totally obvious
var LOCAL_STORAGE_PREFIX = 'panoptesClientOAuth_';

// Specify whether to use local or session storage for session data.
var SESSION_STORAGE = window.sessionStorage;

// Create our model, then do stuff with it later
module.exports = new Model({
  _bearerRefreshTimeout: NaN,
  _clientAppId: ls.get(LOCAL_STORAGE_PREFIX + 'clientAppId'),
  _currentSessionCheckPromise: null,
  _currentUserPromise: null,
  _tokenDetails: null,

  checkBearerToken: function() {
    var awaitBearerToken;
    if (this._bearerTokenIsExpired()) {
      awaitBearerToken = this._refreshBearerToken();
    } else {
      var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails'));
      awaitBearerToken = Promise.resolve(tokenDetails);
    }
    return awaitBearerToken;
  },

  checkCurrent: function() {
    console.log('Checking current user');

    // If we're checking for an existing session already, defer this until
    // it's finished
    var initialCheck = this._currentSessionCheckPromise || Promise.resolve();

    if (!this._currentUserPromise) {
      this.update({
        _currentUserPromise: initialCheck
          .then(this._getSession)
          .catch(function() {
            // Nobody's signed in. This isn't an error.
            console.info('No current user');
            return null;
          }),
      });
    }

    return this._currentUserPromise;
  },

  init: function (appID) {
    return new Promise(function(resolve, reject) {

      // Don't init if we're in an iFrame, as we could be the token refresh process
      if (window.frameElement) {
        return false;
      }

      console.log('Using OAuth (implicit grant) for login');
      console.info('Setting app ID to', appID);
      ls.get(LOCAL_STORAGE_PREFIX + 'clientAppId', appID);
      this._clientAppId = appID;

      // Handle new token details if we've completed a sign in
      if (checkUrlForToken(window.location.hash)) {
        console.log('Token found in URL');
        var tokenDetails = tokenFromLocation(window.location);
        this._handleNewBearerToken(tokenDetails);

        // And redirect to the desired page
        var url = ls.get(LOCAL_STORAGE_PREFIX + 'redirectUri');
        location.assign(url);
      }

      // If not, let's try and pick up an existing Panoptes session anyway
      this.checkBearerToken()
        .then(function (tokenDetails) {
          this._handleNewBearerToken(tokenDetails);
          resolve(tokenDetails);
        }.bind(this))
        .catch(function (error) {
          // We probably haven't signed in before
          console.info(error);
          resolve(null);
        });

    }.bind(this));

  },

  signIn: function(redirectUri) {
    console.log('Signing in with OAuth');
    var originalArguments = arguments;
    return this.checkCurrent()
      .then(function (token) {
        if (token) {
          return this.signOut().then(function() {
            return this.signIn.apply(this, originalArguments);
          }.bind(this));
        } else {
          this._saveRedirectUri(redirectUri);
          location.assign(this._createOAuthUrl(redirectUri));
        }
      }.bind(this));
  },

  signOut: function() {
    console.log('Signing out');
    return this.checkCurrent().then(function(user) {
      if (user) {
        return this._getAuthToken().then(function(token) {
          var url = config.oauthHost + '/users/sign_out';

          var deleteHeaders = Object.create(JSON_HEADERS);
          deleteHeaders['X-CSRF-Token'] = token;

          return makeHTTPRequest('DELETE', url, null, deleteHeaders)
            .then(function() {
              this._deleteBearerToken();
              this.update({
                _currentUserPromise: Promise.resolve(null),
              });
              console.info('Signed out');
              return null;
            }.bind(this))
            .catch(function(request) {
              console.error('Failed to sign out');
              return apiClient.handleError(request);
            }.bind(this));
        }.bind(this));
      } else {
        throw new Error('Failed to sign out; not signed in');
      }
    }.bind(this));
  },

  _createOAuthUrl: function(redirectUri) {
    if (!this._clientAppId) {
      throw new Error('Client app ID not set');
    }

    return [
      config.oauthHost,
      '/oauth/authorize',
      '?response_type=token',
      '&client_id=',
      this._clientAppId,
      '&redirect_uri=',
      redirectUri
    ].join('');
  },

  _bearerTokenIsExpired: function() {
    var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails'));
    if (tokenDetails) {
      return Date.now() >= tokenDetails.expires_at - TOKEN_EXPIRATION_ALLOWANCE;
    } else {
      return false;
    }
  },

  _getNewToken: function() {
    var redirectUri = ls.get(LOCAL_STORAGE_PREFIX + 'redirectUri');
    this.update({
      _currentSessionCheckPromise: new Promise(function(resolve, reject) {

        if (!redirectUri) {
          reject(Error('No redirect URI found'));
        }

        // Create a new iFrame
        var url = this._createOAuthUrl(redirectUri);
        this._iframe = createIFrame(url);

        // Try and get the token details from our iFrame. If it throws an error,
        // it's because we're being redirected to the signin page (and therefore
        // there is no session) - so we should also replace the security error
        // with a more relevant one.
        this._iframe.onload = function() {
          try {
            var iframeLocation = this._iframe.contentWindow.location;
            if (checkUrlForToken(iframeLocation.hash)) {
              console.info('Found existing Panoptes session');
              var newTokenDetails = tokenFromLocation(iframeLocation);
              resolve(newTokenDetails);
            } else {
              throw new TypeError('Valid OAuth details not found in URL');
            }
          } catch (error) {
            if (error.name === 'SecurityError') {
              console.warn('No existing Panoptes session found');
            }
            reject(error);
          } finally {
            this._iframe = destroyIFrame(this._iframe);
          }
        }.bind(this);
      }.bind(this))
    });

    return this._currentSessionCheckPromise;
  },

  _deleteBearerToken: function() {
    console.log('Deleting bearer token');
    this._tokenDetails = null;
    delete apiClient.headers.Authorization;
    SESSION_STORAGE.removeItem(LOCAL_STORAGE_PREFIX + 'tokenDetails');
  },

  _getAuthToken: function() {
    console.log('Getting auth token');
    var url = config.oauthHost + '/users/sign_in/?now=' + Date.now();
    return makeHTTPRequest('GET', url, null, JSON_HEADERS)
      .then(function(response) {
        var authToken = response.header['x-csrf-token'];
        console.info('Got auth token', authToken.slice(-6));
        return authToken;
      })
      .catch(function(response) {
        console.error('Failed to get auth token');
        apiClient.handleError(response);
      });
  },

  _getSession: function() {
    console.log('Getting session');
    return apiClient.get('/me')
      .then(function(users) {
        var user = users[0];
        console.info('Got session', user.login, user.id);
        return user;
      })
      .catch(function(error) {
        console.error('Failed to get session');
        throw error;
      });
  },

  _handleNewBearerToken: function(tokenDetails) {
    if (tokenDetails && tokenDetails.access_token) {
      console.log('Got new bearer token', tokenDetails.access_token.slice(-6));
      this._tokenDetails = tokenDetails;
      apiClient.headers.Authorization = 'Bearer ' + tokenDetails.access_token;

      var refresh = this._refreshBearerToken.bind(this);
      var timeToRefresh = (tokenDetails.expires_in * 1000) - TOKEN_EXPIRATION_ALLOWANCE;
      this._bearerRefreshTimeout = setTimeout(refresh, timeToRefresh);
      tokenDetails.expires_at = Date.now() + (tokenDetails.expires_in * 1000);
      SESSION_STORAGE.setItem(LOCAL_STORAGE_PREFIX + 'tokenDetails', JSON.stringify(tokenDetails));
    }
    return tokenDetails;
  },

  _refreshBearerToken: function() {
    return this._getNewToken()
      .then(function(tokenDetails) {
        return this._handleNewBearerToken(tokenDetails);
      }.bind(this))
      .catch(function (error) {
        console.info('Panoptes session has expired');
        console.log(error);
        this._deleteBearerToken();
        return null;
      });
  },

  _saveRedirectUri: function(redirectUri) {
    console.info('Saving redirectUri:', redirectUri);
    ls.set(LOCAL_STORAGE_PREFIX + 'redirectUri', redirectUri);
  }

});
/*******************************************
  Utility functions
*******************************************/
function checkUrlForToken(string) {
  return string.indexOf('access_token') !== -1 &&
    string.indexOf('token_type=bearer') !== -1;
}

function tokenFromLocation(loc) {
  var params = loc.hash.slice(1).split('&');
  var tokenDetails = {};
  params.forEach(function(paramString) {
    var param = paramString.split('=');
    tokenDetails[param[0]] = param[1];
  });
  return tokenDetails;
}

function createIFrame(url) {
  var iframe = document.createElement('iframe');
  iframe.setAttribute('src', url);
  iframe.setAttribute('style', 'display: none;');
  document.body.appendChild(iframe);
  return iframe;
}

function destroyIFrame(iframe) {
  iframe.parentNode.removeChild(iframe);
  return null;
}
<|endoftext|>


<commit_before>/**
 * @module ol
 */

import webgl from './webgl.js';

/**
 * Include debuggable shader sources.  Default is `true`. This should be set to
 * `false` for production builds.
 * TODO: move to a separate ol-webgl package
 * @type {boolean}
 */
export const DEBUG_WEBGL = true;

/**
 * TODO: move to a separate ol-webgl package
 * The maximum supported WebGL texture size in pixels. If WebGL is not
 * supported, the value is set to `undefined`.
 * @const
 * @type {number|undefined}
 */
let WEBGL_MAX_TEXTURE_SIZE; // value is set below

/**
 * TODO: move to a separate ol-webgl package
 * List of supported WebGL extensions.
 * @const
 * @type {Array.<string>}
 */
let WEBGL_EXTENSIONS; // value is set below

/**
 * TODO: move to a separate ol-webgl package
 * WebGL is available.
 * @type {boolean}
 */
let HAS_WEBGL = false;

if ('WebGLRenderingContext' in window) {
  try {
    const canvas = /** @type {HTMLCanvasElement} */
        (document.createElement('CANVAS'));
    const gl = webgl.getContext(canvas, {failIfMajorPerformanceCaveat: true});
    if (gl) {
      HAS_WEBGL = true;
      WEBGL_MAX_TEXTURE_SIZE = /** @type {number} */
        (gl.getParameter(gl.MAX_TEXTURE_SIZE));
      WEBGL_EXTENSIONS = gl.getSupportedExtensions();
    }
  } catch (e) {
    // pass
  }
}

export {HAS_WEBGL, WEBGL_MAX_TEXTURE_SIZE, WEBGL_EXTENSIONS};

/**
 * OpenLayers version.
 * @type {string}
 */
export const VERSION = 'v4.6.4';

/**
 * Inherit the prototype methods from one constructor into another.
 *
 * Usage:
 *
 *     function ParentClass(a, b) { }
 *     ParentClass.prototype.foo = function(a) { }
 *
 *     function ChildClass(a, b, c) {
 *       // Call parent constructor
 *       ParentClass.call(this, a, b);
 *     }
 *     inherits(ChildClass, ParentClass);
 *
 *     var child = new ChildClass('a', 'b', 'see');
 *     child.foo(); // This works.
 *
 * @param {!Function} childCtor Child constructor.
 * @param {!Function} parentCtor Parent constructor.
 * @function
 * @api
 */
export function inherits(childCtor, parentCtor) {
  childCtor.prototype = Object.create(parentCtor.prototype);
  childCtor.prototype.constructor = childCtor;
}

/**
 * A reusable function, used e.g. as a default for callbacks.
 *
 * @return {undefined} Nothing.
 */
export function nullFunction() {}

/**
 * Counter for getUid.
 * @type {number}
 * @private
 */
let uidCounter_ = 0;

/**
 * Gets a unique ID for an object. This mutates the object so that further calls
 * with the same object as a parameter returns the same value. Unique IDs are generated
 * as a strictly increasing sequence. Adapted from goog.getUid.
 *
 * @param {Object} obj The object to get the unique ID for.
 * @return {number} The unique ID for the object.
 */
export function getUid(obj) {
  return obj.ol_uid || (obj.ol_uid = ++uidCounter_);
}
<commit_msg>Use exported function from ol/webgl<commit_after>/**
 * @module ol
 */

import {getContext} from './webgl.js';

/**
 * Include debuggable shader sources.  Default is `true`. This should be set to
 * `false` for production builds.
 * TODO: move to a separate ol-webgl package
 * @type {boolean}
 */
export const DEBUG_WEBGL = true;

/**
 * TODO: move to a separate ol-webgl package
 * The maximum supported WebGL texture size in pixels. If WebGL is not
 * supported, the value is set to `undefined`.
 * @const
 * @type {number|undefined}
 */
let WEBGL_MAX_TEXTURE_SIZE; // value is set below

/**
 * TODO: move to a separate ol-webgl package
 * List of supported WebGL extensions.
 * @const
 * @type {Array.<string>}
 */
let WEBGL_EXTENSIONS; // value is set below

/**
 * TODO: move to a separate ol-webgl package
 * WebGL is available.
 * @type {boolean}
 */
let HAS_WEBGL = false;

if ('WebGLRenderingContext' in window) {
  try {
    const canvas = /** @type {HTMLCanvasElement} */
        (document.createElement('CANVAS'));
    const gl = getContext(canvas, {failIfMajorPerformanceCaveat: true});
    if (gl) {
      HAS_WEBGL = true;
      WEBGL_MAX_TEXTURE_SIZE = /** @type {number} */
        (gl.getParameter(gl.MAX_TEXTURE_SIZE));
      WEBGL_EXTENSIONS = gl.getSupportedExtensions();
    }
  } catch (e) {
    // pass
  }
}

export {HAS_WEBGL, WEBGL_MAX_TEXTURE_SIZE, WEBGL_EXTENSIONS};

/**
 * OpenLayers version.
 * @type {string}
 */
export const VERSION = 'v4.6.4';

/**
 * Inherit the prototype methods from one constructor into another.
 *
 * Usage:
 *
 *     function ParentClass(a, b) { }
 *     ParentClass.prototype.foo = function(a) { }
 *
 *     function ChildClass(a, b, c) {
 *       // Call parent constructor
 *       ParentClass.call(this, a, b);
 *     }
 *     inherits(ChildClass, ParentClass);
 *
 *     var child = new ChildClass('a', 'b', 'see');
 *     child.foo(); // This works.
 *
 * @param {!Function} childCtor Child constructor.
 * @param {!Function} parentCtor Parent constructor.
 * @function
 * @api
 */
export function inherits(childCtor, parentCtor) {
  childCtor.prototype = Object.create(parentCtor.prototype);
  childCtor.prototype.constructor = childCtor;
}

/**
 * A reusable function, used e.g. as a default for callbacks.
 *
 * @return {undefined} Nothing.
 */
export function nullFunction() {}

/**
 * Counter for getUid.
 * @type {number}
 * @private
 */
let uidCounter_ = 0;

/**
 * Gets a unique ID for an object. This mutates the object so that further calls
 * with the same object as a parameter returns the same value. Unique IDs are generated
 * as a strictly increasing sequence. Adapted from goog.getUid.
 *
 * @param {Object} obj The object to get the unique ID for.
 * @return {number} The unique ID for the object.
 */
export function getUid(obj) {
  return obj.ol_uid || (obj.ol_uid = ++uidCounter_);
}
<|endoftext|>


<commit_before><commit_msg>Made API Key configurable<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node
// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================

const {exec} = require('../../scripts/test-util');
const fs = require('fs');

function shouldRunIntegration() {
  if (process.env.NIGHTLY === 'true') {
    return true;
  }
  const diffFile = 'diff';
  if (!fs.existsSync(diffFile)) {
    return false;
  }
  let diffContents = `${fs.readFileSync(diffFile)}`;
  if (diffContents.indexOf('src/version.ts') === -1) {
    return false;
  }
  return true;
}

if (shouldRunIntegration()) {
  exec('./scripts/test-integration.sh');
}
<commit_msg>Change test-integration to look for 'run-ci' instead of 'diff'. (#2823)<commit_after>#!/usr/bin/env node
// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================

const {exec} = require('../../scripts/test-util');
const fs = require('fs');

function shouldRunIntegration() {
  if (process.env.NIGHTLY === 'true') {
    return true;
  }
  const diffFile = 'run-ci';
  if (!fs.existsSync(diffFile)) {
    return false;
  }
  let diffContents = `${fs.readFileSync(diffFile)}`;
  if (diffContents.indexOf('src/version.ts') === -1) {
    return false;
  }
  return true;
}

if (shouldRunIntegration()) {
  exec('./scripts/test-integration.sh');
}
<|endoftext|>


<commit_before>import Debug from "./framesynthesis/Debug";

export default class AudioManager {
	constructor(synthesizer, bufferSize = 1024) {
		this.synthesizer = synthesizer;
		this.bufferSize = bufferSize;

		try {
			this.context = new webkitAudioContext() || new AudioContext();
		} catch (e) {
			Debug.log("error: This browser does not support Web Audio API.");
			return;
		}

		this.buffer = new Float32Array(this.bufferSize);

		this.scriptProcessor = this.context.createScriptProcessor(this.bufferSize, 0, 2);
		this.scriptProcessor.onaudioprocess = e => this.process(e);
		this.scriptProcessor.connect(this.context.destination);

		// Prevent GC
		// ref. http://stackoverflow.com/questions/24338144/chrome-onaudioprocess-stops-getting-called-after-a-while
		window.savedReference = this.scriptProcessor;

		Debug.log("  Sampling rate : " + this.context.sampleRate + " Hz");
		Debug.log("  Buffer size   : " + this.scriptProcessor.bufferSize + " samples");
	}

	process(e) {
		let outL = e.outputBuffer.getChannelData(0);
		let outR = e.outputBuffer.getChannelData(1);

		this.synthesizer.render(this.buffer, this.context.sampleRate);

		for (let i = 0; i < this.bufferSize; i++) {
			outL[i] = this.buffer[i];
			outR[i] = this.buffer[i];
		}
	}
}

<commit_msg>Suppress warning on Chrome<commit_after>import Platform from "./framesynthesis/Platform";
import Debug from "./framesynthesis/Debug";

export default class AudioManager {
	constructor(synthesizer, bufferSize = 1024) {
		this.synthesizer = synthesizer;
		this.bufferSize = bufferSize;

		try {
			if (Platform.isiOS()) {
				this.context = new webkitAudioContext();
			} else {
				this.context = new AudioContext();
			}
		} catch (e) {
			Debug.log("error: This browser does not support Web Audio API.");
			return;
		}

		this.buffer = new Float32Array(this.bufferSize);

		this.scriptProcessor = this.context.createScriptProcessor(this.bufferSize, 0, 2);
		this.scriptProcessor.onaudioprocess = e => this.process(e);
		this.scriptProcessor.connect(this.context.destination);

		// Prevent GC
		// ref. http://stackoverflow.com/questions/24338144/chrome-onaudioprocess-stops-getting-called-after-a-while
		window.savedReference = this.scriptProcessor;

		Debug.log("  Sampling rate : " + this.context.sampleRate + " Hz");
		Debug.log("  Buffer size   : " + this.scriptProcessor.bufferSize + " samples");
	}

	process(e) {
		let outL = e.outputBuffer.getChannelData(0);
		let outR = e.outputBuffer.getChannelData(1);

		this.synthesizer.render(this.buffer, this.context.sampleRate);

		for (let i = 0; i < this.bufferSize; i++) {
			outL[i] = this.buffer[i];
			outR[i] = this.buffer[i];
		}
	}
}

<|endoftext|>


<commit_before>(function(){
  'use strict';

  // Chartist guy data chart data and options
  var optionsChartistGuy = {
    width: 195,
    height: 137,
    chartPadding: 10,
    axisX: {
      offset: 15,
      showLabel: true,
      showGrid: true,
      labelInterpolationFnc: function(n) {
        return n;
      }
    },
    axisY: {
      offset: 25,
      showLabel: true,
      showGrid: true,
      scaleMinSpace: 15,
      labelInterpolationFnc: function(n) {
        return Math.round(n / 100000) / 10 + 'm.';
      }
    }
  };

  var chartistGuyData = {
    labels: ['1st', '2nd', '3rd'],
    series: [
      {
        name: 'Workers',
        data: [1283000, 1500000, 5706000]
      },
      {
        name: 'Nobles',
        data: [1883000, 2050000, 3706000]
      }
    ]
  };

  var $chartistGuyElement = $('#chartist-guy');
  if($chartistGuyElement.length > 0) {

    // Create new snap object from SVG
    var chartistGuySnap = Snap($chartistGuyElement.get(0));
    // Load Chartist guy SVG
    Snap.load($chartistGuyElement.data('svgSrc'), function (fragment) {
      chartistGuySnap.append(fragment);

      // Add line chart to canvas of Chartist guy :-)
      window.Chartist.Line($chartistGuyElement.find('#chart-canvas').get(0), chartistGuyData, optionsChartistGuy);
    });
  }
}());
<commit_msg>documentation: fixed chart on landing page after new rendering order<commit_after>(function(){
  'use strict';

  // Chartist guy data chart data and options
  var optionsChartistGuy = {
    width: 195,
    height: 137,
    chartPadding: {
      top: 15,
      right: 10,
      bottom: 10,
      left: 10
    },
    axisX: {
      offset: 15,
      showLabel: true,
      showGrid: true,
      labelInterpolationFnc: function(n) {
        return n;
      }
    },
    axisY: {
      offset: 25,
      showLabel: true,
      labelOffset: {
        y: 5
      },
      showGrid: true,
      scaleMinSpace: 15,
      labelInterpolationFnc: function(n) {
        return Math.round(n / 100000) / 10 + 'm.';
      }
    }
  };

  var chartistGuyData = {
    labels: ['1st', '2nd', '3rd'],
    series: [
      {
        name: 'Workers',
        data: [1283000, 1500000, 5706000]
      },
      {
        name: 'Nobles',
        data: [1883000, 2050000, 3706000]
      }
    ]
  };

  var $chartistGuyElement = $('#chartist-guy');
  if($chartistGuyElement.length > 0) {

    // Create new snap object from SVG
    var chartistGuySnap = Snap($chartistGuyElement.get(0));
    // Load Chartist guy SVG
    Snap.load($chartistGuyElement.data('svgSrc'), function (fragment) {
      chartistGuySnap.append(fragment);

      // Add line chart to canvas of Chartist guy :-)
      window.Chartist.Line($chartistGuyElement.find('#chart-canvas').get(0), chartistGuyData, optionsChartistGuy);
    });
  }
}());
<|endoftext|>


<commit_before>'use strict';

var extend = require( 'extend' );
var _      = require('underscore');
var parse  = require('./parser');
var compile = require('./compiler');

module.exports = compile_agg;

function _parse(s, agg) {
  var p = s.split('@')[0];
  var n = s.split('@')[1];
  var name = p.split('.')[0].trim();
  var type = p.split('.')[1].trim();
  agg[name] = {};
  agg[name][type] = {};
  if (type == 'filter') {
    var esq = compile(parse(n));
    agg[name][type] = esq.query.filtered.filter[0];
  } else {
    _.each(n.split(','), function(t) {
      var tmp = t.split('==');
      var value = tmp[1].replace(/(^\s*)|(\s*$)/g, "");
      if (tmp[0] == 'size' || tmp[0] == 'precision_thresold'
         || tmp[0] == 'min_doc_count')
        value = parseInt(tmp[1])
      agg[name][type][tmp[0]] = value;
    })
  }
  return name
}

function compile_agg( tree ) {
    var arr = tree.trim().split(/side|dive/g);
    var op = [];
    _.each(tree.trim().split(' '), function(o) {
      if (o == 'side' || o == 'dive') op.push(o);
    });
    var agg = {};
    var s = agg;
    var len = arr.length;
    var i = 0, j = 0;
    var name;
    while (i < len) {
      var o = arr[i];
      if (!o.length) return;
      if (i > 0 && op[j] == 'dive') {
          agg[name]['aggs'] = {}
          agg = agg[name]['aggs']
      }
      name = _parse(o, agg);
      if (i > 0) j++;
      i++;
    }
    return {aggs: s};
}

//compile_agg('v3.value@field==v side total_user.cardinality@precision_thresold==4000,field==k.openid dive total.term@a==b dive t.terms@b==c')
<commit_msg>* Fix: add nested range support<commit_after>'use strict';

var extend = require( 'extend' );
var _      = require('underscore');
var parse  = require('./parser');
var compile = require('./compiler');

module.exports = compile_agg;

function _parse(s, agg) {
  var p = s.split('@')[0];
  var n = s.split('@')[1];
  var name = p.split('.')[0].trim();
  var type = p.split('.')[1].trim();
  agg[name] = {};
  agg[name][type] = {};
  if (type == 'filter') {
    var esq = compile(parse(n));
    agg[name][type] = esq.query.filtered.filter[0];
  } else {
    _.each(n.split(','), function(t) {
      var tmp = t.split('==');
      var value = tmp[1].replace(/(^\s*)|(\s*$)/g, "");
      if (tmp[0] == 'size' || tmp[0] == 'precision_thresold'
         || tmp[0] == 'min_doc_count')
        value = parseInt(tmp[1]);
      else if (tmp[0] == 'ranges') {
        var r = value.split('$');
        var range = [];
        _.each(r, function(item) {
          var temp = {};
          _.each(item.split('~'), function(o) {
            if (o[0] == 'k') temp.key = o.slice(1);
            if (o[0] == 'f') temp.from = parseFloat(o.slice(1));
            if (o[0] == 't') temp.to = parseFloat(o.slice(1));
          })
          range.push(temp);
        })
        value = range;
      }
      agg[name][type][tmp[0]] = value;
    })
  }
  return name
}

function compile_agg( tree ) {
    var arr = tree.trim().split(/side|dive/g);
    var op = [];
    _.each(tree.trim().split(' '), function(o) {
      if (o == 'side' || o == 'dive') op.push(o);
    });
    var agg = {};
    var s = agg;
    var len = arr.length;
    var i = 0, j = 0;
    var name;
    while (i < len) {
      var o = arr[i];
      if (!o.length) return;
      if (i > 0 && op[j] == 'dive') {
          agg[name]['aggs'] = {}
          agg = agg[name]['aggs']
      }
      name = _parse(o, agg);
      if (i > 0) j++;
      i++;
    }
    return {aggs: s};
}

//compile_agg('v3.value@field==v side total_user.cardinality@precision_thresold==4000,field==k.openid dive total.term@a==b dive t.terms@b==c')
<|endoftext|>


<commit_before>var Immutable = require("../seamless-immutable.js");
var JSC       = require("jscheck");
var TestUtils = require("../TestUtils.js");

var isEqual          = TestUtils.isEqual;
var throwsException  = TestUtils.throwsException;
var identityFunction = TestUtils.identityFunction;

var claims = {
  "it is an instanceof Array": {
    predicate: function(array, args) {
      return array instanceof Array;
    }
  },

  "it has the same length as the length of its constructor args": {
    predicate: function(array, args) {
      return array.length === args.length;
    }
  },

  "it supports accessing elements by index via []": {
    predicate: function(array, args, randomIndex) {
      return (typeof randomIndex === "number") &&
        isEqual(array[randomIndex], args[randomIndex]);
    },
    specifiers: [JSC.integer()]
  },

  "it works with for loops": {
    predicate: function(array, args) {
      for (var index=0; index < array.length; index++) {
        if (!isEqual(array[index], args[index])) {
          return false;
        }
      }

      return true;
    }
  },

  "it works with for..in loops": {
    predicate: function(array, args) {
      for (var index in array) {
        if (!isEqual(array[index], args[index])) {
          return false;
        }
      }

      return true;
    }
  },

  "it supports concat": {
    predicate: function(array, args, otherArray) {
      return isEqual(array.concat(otherArray), args.concat(otherArray));
    },
    specifiers: [JSC.array()]
  },

  "it supports being an argument to a normal array's concat": {
    predicate: function(array, args, otherArray) {
      return isEqual(otherArray.concat(array), otherArray.concat(args));
    },
    specifiers: [JSC.array()]
  },

  "it can be concatted to itself": {
    predicate: function(array, args) {
      return isEqual(array.concat(array), args.concat(args));
    }
  },

  "it has a toString() method that works like a regular array's toString()": {
    predicate: function(array, args) {
      return isEqual(array.toString(), args.toString());
    }
  },

  "it supports being passed to JSON.stringify": {
    predicate: function(array, args) {
      return isEqual(JSON.stringify(array), JSON.stringify(args));
    }
  },

  "it is frozen": {
    predicate: function(array, args) {
      return Object.isFrozen(array);
    }
  },

  "it is tagged as immutable": {
    predicate: function(array, args) {
      return Immutable.isImmutable(array);
    }
  },

  "it cannot have its elements directly mutated": {
    predicate: function(array, args, randomIndex, randomData) {
      array[randomIndex] = randomData;

      return (typeof randomIndex === "number") &&
        array.length === args.length &&
        isEqual(array[randomIndex], args[randomIndex]);
    },
    specifiers: [JSC.integer(), JSC.any()]
  },

  "it makes nested content immutable as well": {
    predicate: function(array, args, innerArray, obj) {
      args.push(innerArray); // Make a nested array
      args.push(obj); // Get an object in there too

      array = Immutable.Array.apply(Immutable.Array, args);

      if (array.length !== args.length) {
        return false;
      }

      for (var index in args) {
        if (!Immutable.isImmutable(array[index])) {
          return false;
        }
      }

      return true;
    },
    specifiers: [JSC.array(), JSC.object()]
  },

  // TODO this never fails under Node, even after removing Immutable.Array's
  // call to toImmutable(). Need to verify that it can fail in browsers.
  "it reuses existing immutables during construction": {
    predicate: function(array, args, innerArray, obj) {
      args.push(innerArray); // Make a nested array
      args.push(obj); // Get an object in there too

      array = Immutable.Array.apply(Immutable.Array, args);

      var copiedArray = Immutable.Array.apply(Immutable.Array, array);

      if (copiedArray.length !== array.length) {
        return false;
      }

      for (var index in copiedArray) {
        var expected = array[index];
        var actual   = copiedArray[index];

        if ((expected !== actual) &&
          (expected === expected) &&
          (actual === actual)) {
          return false;
        }
      }

      return true;
    },
    specifiers: [JSC.array(), JSC.object()]
  }
};

// Add a "returns immutable" claim for each non-mutating method on Array.
nonMutatingArrayMethods = {
  map:         [JSC.literal(identityFunction)],
  filter:      [JSC.literal(identityFunction)],
  reduce:      [JSC.literal(identityFunction), JSC.any()],
  reduceRight: [JSC.literal(identityFunction), JSC.any()],
  concat:      [JSC.array()],
  slice:       [JSC.integer(), JSC.integer()]
}

for (methodName in nonMutatingArrayMethods) {
  (function(methodName, specifiers) {
    var description = "it returns only immutables when you call its " +
      methodName + "() method";

    claims[description] = {
      predicate: function(array, args) {
        var methodArgs = Array.prototype.slice.call(arguments, 2);
        return TestUtils.returnsImmutable(methodName, array, args, methodArgs);
      },
      specifiers: specifiers
    };
  })(methodName, nonMutatingArrayMethods[methodName]);
}

[ // Add a "reports banned" claim for each mutating method on Array.
  "setPrototypeOf", "push", "pop", "sort", "splice", "shift", "unshift", "reverse"
].forEach(function(methodName) {
  var description = "it throws an ImmutableError when you try to call its " +
    methodName + "() method";

  claims[description] = {
    predicate: function(array, args, methodArgs) {
      return throwsException(Immutable.ImmutableError, function() {
        array[methodName].apply(array, methodArgs);
      });
    },
    specifiers: [JSC.any()]
  };
});

module.exports = TestUtils.testSuiteFromClaims(JSC, claims,
  function(claim) {
    return function(verdict, arrayConstructorArgs) {
      var argsWithoutVerdict = Array.prototype.slice.call(arguments, 1);
      var immutableArray = Immutable.Array.apply(Immutable.Array, arrayConstructorArgs);
      var newArgs = [immutableArray].concat(argsWithoutVerdict);
      var result = claim.predicate.apply(claim, newArgs);

      verdict(result);
    };
  });<commit_msg>Rename some test functions for clarity.<commit_after>var Immutable = require("../seamless-immutable.js");
var JSC       = require("jscheck");
var TestUtils = require("../TestUtils.js");

var isEqual          = TestUtils.isEqual;
var throwsException  = TestUtils.throwsException;
var identityFunction = TestUtils.identityFunction;

var claims = {
  "it is an instanceof Array": {
    predicate: function(immutable, mutable) {
      return immutable instanceof Array;
    }
  },

  "it has the same length as the length of its constructor mutable": {
    predicate: function(immutable, mutable) {
      return immutable.length === mutable.length;
    }
  },

  "it supports accessing elements by index via []": {
    predicate: function(immutable, mutable, randomIndex) {
      return (typeof randomIndex === "number") &&
        isEqual(immutable[randomIndex], mutable[randomIndex]);
    },
    specifiers: [JSC.integer()]
  },

  "it works with for loops": {
    predicate: function(immutable, mutable) {
      for (var index=0; index < immutable.length; index++) {
        if (!isEqual(immutable[index], mutable[index])) {
          return false;
        }
      }

      return true;
    }
  },

  "it works with for..in loops": {
    predicate: function(immutable, mutable) {
      for (var index in immutable) {
        if (!isEqual(immutable[index], mutable[index])) {
          return false;
        }
      }

      return true;
    }
  },

  "it supports concat": {
    predicate: function(immutable, mutable, otherArray) {
      return isEqual(immutable.concat(otherArray), mutable.concat(otherArray));
    },
    specifiers: [JSC.array()]
  },

  "it supports being an argument to a normal immutable's concat": {
    predicate: function(immutable, mutable, otherArray) {
      return isEqual(otherArray.concat(immutable), otherArray.concat(mutable));
    },
    specifiers: [JSC.array()]
  },

  "it can be concatted to itself": {
    predicate: function(immutable, mutable) {
      return isEqual(immutable.concat(immutable), mutable.concat(mutable));
    }
  },

  "it has a toString() method that works like a regular immutable's toString()": {
    predicate: function(immutable, mutable) {
      return isEqual(immutable.toString(), mutable.toString());
    }
  },

  "it supports being passed to JSON.stringify": {
    predicate: function(immutable, mutable) {
      return isEqual(JSON.stringify(immutable), JSON.stringify(mutable));
    }
  },

  "it is frozen": {
    predicate: function(immutable, mutable) {
      return Object.isFrozen(immutable);
    }
  },

  "it is tagged as immutable": {
    predicate: function(immutable, mutable) {
      return Immutable.isImmutable(immutable);
    }
  },

  "it cannot have its elements directly mutated": {
    predicate: function(immutable, mutable, randomIndex, randomData) {
      immutable[randomIndex] = randomData;

      return (typeof randomIndex === "number") &&
        immutable.length === mutable.length &&
        isEqual(immutable[randomIndex], mutable[randomIndex]);
    },
    specifiers: [JSC.integer(), JSC.any()]
  },

  "it makes nested content immutable as well": {
    predicate: function(immutable, mutable, innerArray, obj) {
      mutable.push(innerArray); // Make a nested immutable
      mutable.push(obj); // Get an object in there too

      immutable = Immutable.Array.apply(Immutable.Array, mutable);

      if (immutable.length !== mutable.length) {
        return false;
      }

      for (var index in mutable) {
        if (!Immutable.isImmutable(immutable[index])) {
          return false;
        }
      }

      return true;
    },
    specifiers: [JSC.array(), JSC.object()]
  },

  // TODO this never fails under Node, even after removing Immutable.Array's
  // call to toImmutable(). Need to verify that it can fail in browsers.
  "it reuses existing immutables during construction": {
    predicate: function(immutable, mutable, innerArray, obj) {
      mutable.push(innerArray); // Make a nested immutable
      mutable.push(obj); // Get an object in there too

      immutable = Immutable.Array.apply(Immutable.Array, mutable);

      var copiedArray = Immutable.Array.apply(Immutable.Array, immutable);

      if (copiedArray.length !== immutable.length) {
        return false;
      }

      for (var index in copiedArray) {
        var expected = immutable[index];
        var actual   = copiedArray[index];

        if ((expected !== actual) &&
          (expected === expected) &&
          (actual === actual)) {
          return false;
        }
      }

      return true;
    },
    specifiers: [JSC.array(), JSC.object()]
  }
};

// Add a "returns immutable" claim for each non-mutating method on Array.
nonMutatingArrayMethods = {
  map:         [JSC.literal(identityFunction)],
  filter:      [JSC.literal(identityFunction)],
  reduce:      [JSC.literal(identityFunction), JSC.any()],
  reduceRight: [JSC.literal(identityFunction), JSC.any()],
  concat:      [JSC.array()],
  slice:       [JSC.integer(), JSC.integer()]
}

for (methodName in nonMutatingArrayMethods) {
  (function(methodName, specifiers) {
    var description = "it returns only immutables when you call its " +
      methodName + "() method";

    claims[description] = {
      predicate: function(array, args) {
        var methodArgs = Array.prototype.slice.call(arguments, 2);
        return TestUtils.returnsImmutable(methodName, array, args, methodArgs);
      },
      specifiers: specifiers
    };
  })(methodName, nonMutatingArrayMethods[methodName]);
}

[ // Add a "reports banned" claim for each mutating method on Array.
  "setPrototypeOf", "push", "pop", "sort", "splice", "shift", "unshift", "reverse"
].forEach(function(methodName) {
  var description = "it throws an ImmutableError when you try to call its " +
    methodName + "() method";

  claims[description] = {
    predicate: function(array, args, methodArgs) {
      return throwsException(Immutable.ImmutableError, function() {
        array[methodName].apply(array, methodArgs);
      });
    },
    specifiers: [JSC.any()]
  };
});

module.exports = TestUtils.testSuiteFromClaims(JSC, claims,
  function(claim) {
    return function(verdict, arrayConstructorArgs) {
      var argsWithoutVerdict = Array.prototype.slice.call(arguments, 1);
      var immutableArray = Immutable.Array.apply(Immutable.Array, arrayConstructorArgs);
      var newArgs = [immutableArray].concat(argsWithoutVerdict);
      var result = claim.predicate.apply(claim, newArgs);

      verdict(result);
    };
  });<|endoftext|>


<commit_before>var xhr = new XMLHttpRequest(),
	stylesheet = 'stable.css';

if (/Chrome\/(\d\d)/.exec(navigator.userAgent)[1] > 41) {
	stylesheet = 'canary.css'
}

xhr.open("GET", "/" + stylesheet, false);
xhr.send();
chrome.devtools.panels.applyStyleSheet(xhr.responseText);
<commit_msg>version bump<commit_after>var xhr = new XMLHttpRequest(),
	stylesheet = 'stable.css';

if (/Chrome\/(\d\d)/.exec(navigator.userAgent)[1] > 43) {
	stylesheet = 'canary.css'
}

xhr.open("GET", "/" + stylesheet, false);
xhr.send();
chrome.devtools.panels.applyStyleSheet(xhr.responseText);
<|endoftext|>


<commit_before>var Bell 	= require("bell");
var Config 	= require("../config");
var Jobs 	= require("../models/jobs");
var Users 	= require("../models/users");
var Chat  	= require("../models/chat");
var Photos 	= require("../models/photos");
var Aws 	= require('aws-sdk');

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
				reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(fb.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Facebook",
							id: fb.id,
							username: fb.username,
							displayName: fb.displayName,
							firstName: fb.name.first,
							lastName: fb.name.last,
							email: fb.email,
							link: fb.raw.link,
							picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
							gender: fb.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					console.log("Found user in database");

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					reply.redirect("/dashboard");

				}
			});

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {

			var g = request.auth.credentials.profile;

			//Setup session with no usertype default
			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(g.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Google",
							id: g.id,
							username: g.username,
							displayName: g.displayName,
							firstName: g.name.first,
							lastName: g.name.last,
							email: g.email,
							link: g.raw.link,
							picture: g.raw.picture,
							gender: g.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					console.log("found user in database");
					reply.redirect("/dashboard");

				}
			});

		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			if(request.auth.isAuthenticated) {
				reply.view("signupIam");
			} else {
				reply.redirect("/");
			}
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "photographer");
			var id = request.auth.credentials.id;
			var update = {"usertype": "photographer"};

			Users.updateUser(id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "client");
			var profile = request.auth.credentials;
			var update = {"usertype": "client"};

			Users.updateUser(profile.id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	dashboard: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.auth.credentials);

			if(request.auth.isAuthenticated) {

				Jobs.getAllJobs(function(err, data) {
					reply.view("dashboard", {jobs: data});
				});
			} else {
				reply.redirect("/");
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var profile = request.auth.credentials;

				Photos.findGallery(profile.id, function(err, data){

					if(data === null) {

						reply.view("profile", {profile: profile});
					} else {

						var photos = data.photos;

						reply.view("profile", {profile: profile, photos: photos});
					}

				});

			} else {

				reply.redirect("/");
			}
		}
	},

	profileEdit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			reply.view("profileEdit", {profile: profile});
		}
	},

	profileEditP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var update = request.payload;
			console.log(update);

			profile.firstName = update.firstName;
			profile.lastName = update.lastName;
			profile.website = update.website;

			request.auth.session.set(profile);
			Users.updateUser(profile.id, update, function(err, data) {
				reply.redirect("/profile");
			});

		}
	},

	photoDelete: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var id = request.auth.credentials.id;

			Photos.deleteURL(id, request.payload, function(err, data) {
			});
			reply.redirect("/profile");
		}
	},

	newJobForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.view("newJob");
			} else {
				reply.redirect("/");
			}
		}
	},

	newJobPost: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {

			var user_id = request.auth.credentials.id;

			var new_job = {
				user: user_id,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

			} else {
				reply.redirect("/");
			}

		}
	},

	upload: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("upload");
		}
	},

	signS3: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var randomKey = Math.floor((Math.random() * 1000) + 1);
			//S3 setup
			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var s3_params = {
			    Bucket: Config.s3.bucket,
			    Key: request.auth.credentials.id + "/" + randomKey + "_" + request.query.file_name,
			    Expires: 60,
			    ContentType: request.query.file_type,
			    ACL: Config.s3.acl
			};
			// request.query.file_type (type of file you want to upload)

			s3.getSignedUrl('putObject', s3_params, function(err, data){
			    if(err){
			        console.log(err);
			    }
			    else{
			        var return_data = {
			            signed_request: data,
			            url: 'https://'+Config.s3.bucket+'.s3.amazonaws.com/'+request.auth.credentials.id+'/'+ randomKey + "_" + request.query.file_name
			        };
			        reply(JSON.stringify(return_data));
			    }
			});
		}
	},

	submitForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.payload);

			var id = request.auth.credentials.id;
			var update = { $push: {"photos": {
				"title": request.payload.title,
				"url": request.payload.photo_url,
			}}};

			Photos.findGallery(id, function(err, data) {
				if(data === null) {
					var object = {"user": id};
					Photos.newGallery(object, function(err, data) {
						Photos.newPhoto(id, update, function(err, data) {
							reply.redirect("/profile");
						});
					});
				} else {
					Photos.newPhoto(id, update, function(err, data) {
						reply.redirect("/profile");
					});
				}
			});

		}
	},

	users: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var myid = request.auth.credentials.id;

			Users.getAllUsers(function(err, data) {
				reply.view("users", {users: data, myid: myid});
			});
		}
	},

	chatWith: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = Object.keys(request.payload)[0];
			var users = {"users": [myid, chatWith]};

			profile.talkingTo = chatWith;
			request.auth.session.set(profile);

			Chat.findChat(myid, chatWith, function(err, data) {
				if(data.length === 0) {

					console.log("New chat");
					Chat.newChat(users, function(err, data){
						reply.redirect("/chat/" + chatWith);
					});

				} else {

					console.log("Chat exists");
					reply.redirect("/chat/" + chatWith);
				}
			});

		}
	},

	chat: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			Chat.findChat(myid, chatWith, function(err, data) {
				console.log(data[0]);

				Users.getUser(chatWith, function(err, result){
					console.log(result);
					reply.view("chat", {data: data[0], profile: profile, talkingTo: result});
				});
			});

		}
	},

	chatSubmit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			var chat = { $push: {"chat": {
				"sender": myid,
				"name": profile.firstName + " " + profile.lastName,
				"message": request.payload.chat,
				"time": Date()
			}}};

			Chat.addChat(myid, chatWith, chat, function(err, data) {
				reply.redirect("/chat/"+ profile.talkingTo);
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			reply.redirect("/");
		}
	}

};<commit_msg>delete s3 function<commit_after>var Bell 	= require("bell");
var Config 	= require("../config");
var Jobs 	= require("../models/jobs");
var Users 	= require("../models/users");
var Chat  	= require("../models/chat");
var Photos 	= require("../models/photos");
var Aws 	= require('aws-sdk');

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
				reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(fb.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Facebook",
							id: fb.id,
							username: fb.username,
							displayName: fb.displayName,
							firstName: fb.name.first,
							lastName: fb.name.last,
							email: fb.email,
							link: fb.raw.link,
							picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
							gender: fb.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					console.log("Found user in database");

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					reply.redirect("/dashboard");

				}
			});

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {

			var g = request.auth.credentials.profile;

			//Setup session with no usertype default
			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(g.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Google",
							id: g.id,
							username: g.username,
							displayName: g.displayName,
							firstName: g.name.first,
							lastName: g.name.last,
							email: g.email,
							link: g.raw.link,
							picture: g.raw.picture,
							gender: g.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					console.log("found user in database");
					reply.redirect("/dashboard");

				}
			});

		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			if(request.auth.isAuthenticated) {
				reply.view("signupIam");
			} else {
				reply.redirect("/");
			}
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "photographer");
			var id = request.auth.credentials.id;
			var update = {"usertype": "photographer"};

			Users.updateUser(id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "client");
			var profile = request.auth.credentials;
			var update = {"usertype": "client"};

			Users.updateUser(profile.id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	dashboard: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.auth.credentials);

			if(request.auth.isAuthenticated) {

				Jobs.getAllJobs(function(err, data) {
					reply.view("dashboard", {jobs: data});
				});
			} else {
				reply.redirect("/");
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var profile = request.auth.credentials;

				Photos.findGallery(profile.id, function(err, data){

					if(data === null) {

						reply.view("profile", {profile: profile});
					} else {

						var photos = data.photos;

						reply.view("profile", {profile: profile, photos: photos});
					}

				});

			} else {

				reply.redirect("/");
			}
		}
	},

	profileEdit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			reply.view("profileEdit", {profile: profile});
		}
	},

	profileEditP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var update = request.payload;
			console.log(update);

			profile.firstName = update.firstName;
			profile.lastName = update.lastName;
			profile.website = update.website;

			request.auth.session.set(profile);
			Users.updateUser(profile.id, update, function(err, data) {
				reply.redirect("/profile");
			});

		}
	},

	photoDelete: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var id = request.auth.credentials.id;
			var url = Object.keys(request.payload)[0];
			var file = url.split('/').slice(4)[0];

			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var params = {
			  Bucket: Config.s3.bucket,
			  Key: id + "/" + file,
			};
			s3.deleteObject(params, function(err, data) {

			  	if (err) {
			  		console.log("Error deleting from S3", err, err.stack);
			  	} else{
			  		console.log("Deleted from S3");
			  	}
			});

			Photos.deleteURL(id, request.payload, function(err, data) {
				reply.redirect("/profile");
			});
		}
	},

	newJobForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.view("newJob");
			} else {
				reply.redirect("/");
			}
		}
	},

	newJobPost: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {

			var user_id = request.auth.credentials.id;

			var new_job = {
				user: user_id,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

			} else {
				reply.redirect("/");
			}

		}
	},

	upload: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("upload");
		}
	},

	signS3: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var randomKey = Math.floor((Math.random() * 1000) + 1);
			//S3 setup
			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var s3_params = {
			    Bucket: Config.s3.bucket,
			    Key: request.auth.credentials.id + "/" + randomKey + "_" + request.query.file_name,
			    Expires: 60,
			    ContentType: request.query.file_type,
			    ACL: Config.s3.acl
			};
			// request.query.file_type (type of file you want to upload)

			s3.getSignedUrl('putObject', s3_params, function(err, data){
			    if(err){
			        console.log(err);
			    }
			    else{
			        var return_data = {
			            signed_request: data,
			            url: 'https://'+Config.s3.bucket+'.s3.amazonaws.com/'+request.auth.credentials.id+'/'+ randomKey + "_" + request.query.file_name
			        };
			        reply(JSON.stringify(return_data));
			    }
			});
		}
	},

	submitForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.payload);

			var id = request.auth.credentials.id;
			var update = { $push: {"photos": {
				"title": request.payload.title,
				"url": request.payload.photo_url,
			}}};

			Photos.findGallery(id, function(err, data) {
				if(data === null) {
					var object = {"user": id};
					Photos.newGallery(object, function(err, data) {
						Photos.newPhoto(id, update, function(err, data) {
							reply.redirect("/profile");
						});
					});
				} else {
					Photos.newPhoto(id, update, function(err, data) {
						reply.redirect("/profile");
					});
				}
			});

		}
	},

	users: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var myid = request.auth.credentials.id;

			Users.getAllUsers(function(err, data) {
				reply.view("users", {users: data, myid: myid});
			});
		}
	},

	chatWith: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = Object.keys(request.payload)[0];
			var users = {"users": [myid, chatWith]};

			profile.talkingTo = chatWith;
			request.auth.session.set(profile);

			Chat.findChat(myid, chatWith, function(err, data) {
				if(data.length === 0) {

					console.log("New chat");
					Chat.newChat(users, function(err, data){
						reply.redirect("/chat/" + chatWith);
					});

				} else {

					console.log("Chat exists");
					reply.redirect("/chat/" + chatWith);
				}
			});

		}
	},

	chat: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			Chat.findChat(myid, chatWith, function(err, data) {
				console.log(data[0]);

				Users.getUser(chatWith, function(err, result){
					console.log(result);
					reply.view("chat", {data: data[0], profile: profile, talkingTo: result});
				});
			});

		}
	},

	chatSubmit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			var chat = { $push: {"chat": {
				"sender": myid,
				"name": profile.firstName + " " + profile.lastName,
				"message": request.payload.chat,
				"time": Date()
			}}};

			Chat.addChat(myid, chatWith, chat, function(err, data) {
				reply.redirect("/chat/"+ profile.talkingTo);
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			reply.redirect("/");
		}
	}

};<|endoftext|>


<commit_before>'use strict';

var packageJson = require('../package.json');
var path = require('path');
var util = require('util');
var os = require('os');

var arch = os.arch();
var platform = os.platform();
var is64 = /x64/i.test(arch);
var isWin = /^win/i.test(platform);
var isMac = /^dar/i.test(platform);

var SELENIUM_BINARIES_HOME = process.env.SELENIUM_BINARIES_HOME;
var SELENIUM_BINARIES_SERVER_STANDALONE_VERSION = process.env.SELENIUM_BINARIES_SERVER_STANDALONE_VERSION || '2.53.1';
var SELENIUM_BINARIES_CHROMEDRIVER_VERSION = process.env.SELENIUM_BINARIES_CHROMEDRIVER_VERSION || '2.22';
var SELENIUM_BINARIES_GECKODRIVER_VERSION = process.env.SELENIUM_BINARIES_GECKODRIVER_VERSION || '0.9.0';
var SELENIUM_BINARIES_IEDRIVER_VERSION = process.env.SELENIUM_BINARIES_IEDRIVER_VERSION || '2.53.1';

if (typeof process.env.SELENIUM_BINARIES_FORCE_32BITS !== 'undefined') {
  is64 = is64 && !(/^1|true$/i).test('' + process.env.SELENIUM_BINARIES_FORCE_32BITS);
}

function getMajorMinorVersion(semVer) {
  return semVer.substring(0, semVer.lastIndexOf('.'));
}

module.exports = {
  version: packageJson.version,
  binariesPath: SELENIUM_BINARIES_HOME,
  is64: is64,
  isWin: isWin,
  isMac: isMac,
  binaries: {
    seleniumserver: {
      version: SELENIUM_BINARIES_SERVER_STANDALONE_VERSION,
      url: util.format(
        'http://selenium-release.storage.googleapis.com/%s/',
        getMajorMinorVersion(SELENIUM_BINARIES_SERVER_STANDALONE_VERSION)
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'selenium',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      ),
      archiveName: util.format(
        'selenium-server-standalone-%s.jar',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      ),
      binaryName: util.format(
        'selenium-server-standalone-%s.jar',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      )
    },
    chromedriver: {
      version: SELENIUM_BINARIES_CHROMEDRIVER_VERSION,
      url: util.format(
        'http://chromedriver.storage.googleapis.com/%s/',
        SELENIUM_BINARIES_CHROMEDRIVER_VERSION
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'chromedriver',
        SELENIUM_BINARIES_CHROMEDRIVER_VERSION
      ),
      archiveName: util.format(
        'chromedriver_%s.zip',
        (isWin ? 'win32' : (isMac ? 'mac32' : (is64 ? 'linux64' : 'linux32')))),
      binaryName: 'chromedriver' + (isWin ? '.exe' : '')
    },
    geckodriver: {
      version: SELENIUM_BINARIES_GECKODRIVER_VERSION,
      url: util.format(
        'http://github.com/mozilla/geckodriver/releases/download/v%s/',
        SELENIUM_BINARIES_GECKODRIVER_VERSION
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'geckodriver',
        SELENIUM_BINARIES_GECKODRIVER_VERSION
      ),
      archiveName: util.format(
        'geckodriver-v%s-%s',
        SELENIUM_BINARIES_GECKODRIVER_VERSION,
        (isWin ? 'win64.zip' : (isMac ? 'mac.tar.gz' : 'linux64.tar.gz'))
      ),
      binaryName: 'geckodriver' + (isWin ? '.exe' : '')
    },
    iedriver: {
      version: SELENIUM_BINARIES_IEDRIVER_VERSION,
      url: util.format(
        'http://selenium-release.storage.googleapis.com/%s/',
        getMajorMinorVersion(SELENIUM_BINARIES_IEDRIVER_VERSION)
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'iedriver',
        SELENIUM_BINARIES_IEDRIVER_VERSION
      ),
      archiveName: util.format(
        'IEDriverServer_%s_%s.zip',
        (is64 ? 'x64' : 'Win32'),
        SELENIUM_BINARIES_IEDRIVER_VERSION
      ),
      binaryName: 'IEDriverServer.exe'
    }
  }
};
<commit_msg>Enabling 64-bit download for mac (#21)<commit_after>'use strict';

var packageJson = require('../package.json');
var path = require('path');
var util = require('util');
var os = require('os');

var arch = os.arch();
var platform = os.platform();
var is64 = /x64/i.test(arch);
var isWin = /^win/i.test(platform);
var isMac = /^dar/i.test(platform);

var SELENIUM_BINARIES_HOME = process.env.SELENIUM_BINARIES_HOME;
var SELENIUM_BINARIES_SERVER_STANDALONE_VERSION = process.env.SELENIUM_BINARIES_SERVER_STANDALONE_VERSION || '2.53.1';
var SELENIUM_BINARIES_CHROMEDRIVER_VERSION = process.env.SELENIUM_BINARIES_CHROMEDRIVER_VERSION || '2.24';
var SELENIUM_BINARIES_GECKODRIVER_VERSION = process.env.SELENIUM_BINARIES_GECKODRIVER_VERSION || '0.9.0';
var SELENIUM_BINARIES_IEDRIVER_VERSION = process.env.SELENIUM_BINARIES_IEDRIVER_VERSION || '2.53.1';

if (typeof process.env.SELENIUM_BINARIES_FORCE_32BITS !== 'undefined') {
  is64 = is64 && !(/^1|true$/i).test('' + process.env.SELENIUM_BINARIES_FORCE_32BITS);
}

function getMajorMinorVersion(semVer) {
  return semVer.substring(0, semVer.lastIndexOf('.'));
}

module.exports = {
  version: packageJson.version,
  binariesPath: SELENIUM_BINARIES_HOME,
  is64: is64,
  isWin: isWin,
  isMac: isMac,
  binaries: {
    seleniumserver: {
      version: SELENIUM_BINARIES_SERVER_STANDALONE_VERSION,
      url: util.format(
        'http://selenium-release.storage.googleapis.com/%s/',
        getMajorMinorVersion(SELENIUM_BINARIES_SERVER_STANDALONE_VERSION)
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'selenium',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      ),
      archiveName: util.format(
        'selenium-server-standalone-%s.jar',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      ),
      binaryName: util.format(
        'selenium-server-standalone-%s.jar',
        SELENIUM_BINARIES_SERVER_STANDALONE_VERSION
      )
    },
    chromedriver: {
      version: SELENIUM_BINARIES_CHROMEDRIVER_VERSION,
      url: util.format(
        'http://chromedriver.storage.googleapis.com/%s/',
        SELENIUM_BINARIES_CHROMEDRIVER_VERSION
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'chromedriver',
        SELENIUM_BINARIES_CHROMEDRIVER_VERSION
      ),
      archiveName: util.format(
        'chromedriver_%s.zip',
        (isWin ? 'win32' : (isMac ? (is64 ? 'mac64' : 'mac32') : (is64 ? 'linux64' : 'linux32')))),
      binaryName: 'chromedriver' + (isWin ? '.exe' : '')
    },
    geckodriver: {
      version: SELENIUM_BINARIES_GECKODRIVER_VERSION,
      url: util.format(
        'http://github.com/mozilla/geckodriver/releases/download/v%s/',
        SELENIUM_BINARIES_GECKODRIVER_VERSION
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'geckodriver',
        SELENIUM_BINARIES_GECKODRIVER_VERSION
      ),
      archiveName: util.format(
        'geckodriver-v%s-%s',
        SELENIUM_BINARIES_GECKODRIVER_VERSION,
        (isWin ? 'win64.zip' : (isMac ? 'mac.tar.gz' : 'linux64.tar.gz'))
      ),
      binaryName: 'geckodriver' + (isWin ? '.exe' : '')
    },
    iedriver: {
      version: SELENIUM_BINARIES_IEDRIVER_VERSION,
      url: util.format(
        'http://selenium-release.storage.googleapis.com/%s/',
        getMajorMinorVersion(SELENIUM_BINARIES_IEDRIVER_VERSION)
      ),
      path: path.resolve(
        SELENIUM_BINARIES_HOME,
        'iedriver',
        SELENIUM_BINARIES_IEDRIVER_VERSION
      ),
      archiveName: util.format(
        'IEDriverServer_%s_%s.zip',
        (is64 ? 'x64' : 'Win32'),
        SELENIUM_BINARIES_IEDRIVER_VERSION
      ),
      binaryName: 'IEDriverServer.exe'
    }
  }
};
<|endoftext|>