<commit_before>function createWorkspace(path, collectionId, menu, stopEventListener) {
  var safePath;
  $("#working-on").on('click', function () {}); // add event listener to mainNav

  if(stopEventListener) {
    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
          iframeEvent.removeEventListener('click', Florence.Handler, true);
    };
    return false;
  } else {
    var currentPath = '';
    if (path) {
      currentPath = path;
      safePath = checkPathSlashes(currentPath);
    }

    Florence.globalVars.pagePath = safePath;

    Florence.refreshAdminMenu();

    var workSpace = templates.workSpace(Florence.tredegarBaseUrl + safePath);
     $('.section').html(workSpace);

    //click handlers
    $('.nav--workspace > li').click(function () {
      menu = '';
      if (Florence.Editor.isDirty) {
        var result = confirm("You have unsaved changes. Are you sure you want to continue");
        if (result === true) {
          Florence.Editor.isDirty = false;
          processMenuClick(this);
        } else {
          return false;
        }
      } else {
        processMenuClick(this);
      }
    });

    function processMenuClick(clicked) {
      var menuItem = $(clicked);

      $('.nav--workspace li').removeClass('selected');
      menuItem.addClass('selected');

      if (menuItem.is('#browse')) {
        loadBrowseScreen(collectionId, 'click');
      } else if (menuItem.is('#create')) {
        loadCreateScreen(collectionId);
      } else if (menuItem.is('#edit')) {
        Florence.globalVars.pagePath = getPathName();
        loadPageDataIntoEditor(Florence.globalVars.pagePath, Florence.collection.id);
      } else {
        loadBrowseScreen(collectionId);
      }
    }

    $('.workspace-menu').on('click', '.btn-browse-create', function () {
      var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
      //console.log(dest);
      viewWorkspace(dest, Florence.collection.id, 'create');
    });

    $('.workspace-menu').on('click', '.btn-browse-edit', function () {
      var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
      viewWorkspace(dest, Florence.collection.id, 'edit');
    });

    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.addEventListener('click', Florence.Handler, true);
    };

    viewWorkspace(safePath, collectionId, menu);

  }
}

<commit_msg>Initialise variable to prevent undefined error.<commit_after>function createWorkspace(path, collectionId, menu, stopEventListener) {
  var safePath = '';
  $("#working-on").on('click', function () {}); // add event listener to mainNav

  if(stopEventListener) {
    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
          iframeEvent.removeEventListener('click', Florence.Handler, true);
    };
    return false;
  } else {
    var currentPath = '';
    if (path) {
      currentPath = path;
      safePath = checkPathSlashes(currentPath);
    }

    Florence.globalVars.pagePath = safePath;

    Florence.refreshAdminMenu();

    var workSpace = templates.workSpace(Florence.tredegarBaseUrl + safePath);
     $('.section').html(workSpace);

    //click handlers
    $('.nav--workspace > li').click(function () {
      menu = '';
      if (Florence.Editor.isDirty) {
        var result = confirm("You have unsaved changes. Are you sure you want to continue");
        if (result === true) {
          Florence.Editor.isDirty = false;
          processMenuClick(this);
        } else {
          return false;
        }
      } else {
        processMenuClick(this);
      }
    });

    function processMenuClick(clicked) {
      var menuItem = $(clicked);

      $('.nav--workspace li').removeClass('selected');
      menuItem.addClass('selected');

      if (menuItem.is('#browse')) {
        loadBrowseScreen(collectionId, 'click');
      } else if (menuItem.is('#create')) {
        loadCreateScreen(collectionId);
      } else if (menuItem.is('#edit')) {
        Florence.globalVars.pagePath = getPathName();
        loadPageDataIntoEditor(Florence.globalVars.pagePath, Florence.collection.id);
      } else {
        loadBrowseScreen(collectionId);
      }
    }

    $('.workspace-menu').on('click', '.btn-browse-create', function () {
      var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
      //console.log(dest);
      viewWorkspace(dest, Florence.collection.id, 'create');
    });

    $('.workspace-menu').on('click', '.btn-browse-edit', function () {
      var dest = $('.tree-nav-holder ul').find('.selected').attr('data-url');
      viewWorkspace(dest, Florence.collection.id, 'edit');
    });

    document.getElementById('iframe').onload = function () {
      var browserLocation = document.getElementById('iframe').contentWindow.location.href;
      $('.browser-location').val(browserLocation);
      var iframeEvent = document.getElementById('iframe').contentWindow;
      iframeEvent.addEventListener('click', Florence.Handler, true);
    };

    viewWorkspace(safePath, collectionId, menu);

  }
}

<|endoftext|>


<commit_before>import Ember from 'ember';

/**
  * @overview OAuth2 library for Emberjs that stores tokens in the browsers localStorage
  * @license   Licensed under MIT license
  *            See https://raw.github.com/amkirwan/ember-oauth2/master/LICENSE
  * @version   0.7.0
  *
  * @module ember-oauth2
  * @class ember-oauth2
  */
export default Ember.Object.extend(Ember.Evented, {
  /**
   * Initializes the Ember.OAuth2 object when using Ember.OAuth2.create({providerId: 'providerId'}). The following options are available for the configuring a provider: clientId, authBaseUri, redirectUri, scope, statePrefix and tokenPrefix. The clientId, authBaseUri and redirectUri are required. The statePrefix has a default value of 'state' and the tokenPrefix has a default value of 'token'.
   *
   * @method init
   */
  init: function() {
    this._super();
    /**
     * The configuration object for the given provider id.
     *  @property {Object} providerConfig
     *  @property {Object} providerConfig.providerId **Required**
     *  @property {String} providerConfig.providerId.clientId **Required**
     *  @property {String} providerConfig.providerId.authBaseUri **Required**
     *  @property {String} providerConfig.providerId.redirectUri **Required**
     *  @property {String} providerConfig.providerId.scope **Optional**
     *  @property {String} providerConfig.providerId.responseType **Default:** "token", **Optional**
     *  @property {String} providerConfig.providerId.statePrefix **Default:** "state", **Optional**
     *  @property {String} providerConfig.providerId.tokenPrefix **Default:** "prefix", **Optional**
     *  @example
     *    App.oauth = Ember.OAuth2.create({providerId: 'google'});
     */

    // if Ember.OAuth2.config has keys use it instead of window.ENV
    if (Ember.OAuth2 && Ember.OAuth2.config && Object.keys(Ember.OAuth2.config).length) {
      Ember.Logger.warn("Ember.OAuth2.config is deprecated and will be removed in future versions. Set the config using window.ENV['ember-oauth2']");
      this.set('config', Ember.OAuth2.config);
    } else if (window.EmberENV && window.EmberENV['ember-oauth2']) {
      this.set('config', window.EmberENV['ember-oauth2']);
    } else if (window.ENV && window.ENV['ember-oauth2']) {
      this.set('config', window.ENV['ember-oauth2']);
    } else {
      throw new Error('Cannot find the ember-oauth2 config.');
    }

    if (!this.get('config')[this.get('providerId')]) {
      throw new Error("Cannot find the providerId: '" + this.get('providerId') + "' in the config.");
    }

    this.set('providerConfig', this.get('config')[this.get('providerId')]);

    /**
     * The prefix name for the state key stored in the localStorage.
     *
     * @property statePrefix
     * @type String
     * @default "state"
     */
    this.set('statePrefix', 'state');
    /**
     * The prefix name for the token key stored in the localStorage.
     *
     * @property tokenPrefix
     * @type String
     * @default "token"
     */
    this.set('tokenPrefix', 'token');

    /**
     * The response type for the authorization request.
     *
     * @property responseType
     * @type String
     * @default "token"
     */
    this.set('responseType', 'token');

    /**
     * @property {String} clientId
     */
    /**
     * @property {String} authBaseUri
     */
    /**
     * @property {String} redirectUri
     */
    /**
     * @property {String} scope
     */
    // sets the properties from the providerConfig and overrides any default settings.
    this.setProperties(this.providerConfig);

    /**
     * @event redirect
     * @param {function} The function that handles the redirect.
     */
    this.on('redirect', this.handleRedirect);
  },

  /**
   * @method version
   * @return {String} The current version number of Ember.OAuth2
   */
  version: function() {
    return VERSION;
  },

  /**
   * @method uuid
   * @return {String} A pseudo random uuid
   */
  uuid: function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
              return v.toString(16);
    });
  },

  /**
   * @method now
   * @return {Number} The current time in seconds rounded
   */
  now: function() {
    return Math.round(new Date().getTime()/1000.0);
  },

  /**
   * Creates and returns the request object.
   *
   * @method requestObj
   * @return {Object} request object
   */
  requestObj: function() {
    var request = {};
    request.response_type = this.get('responseType');
    request.providerId = this.get('providerId');
    request.state = this.get('state');
    request.client_id = this.get('clientId');
    request.state = this.get('state');
    if (this.get('scope')) request.scope = this.get('scope');
    return request;
  },

  /**
   * @method authUri
   * @return {String} Authorization uri for generating an OAuth2 token
   */
  authUri: function() {
    if (!this.get('state')) { this.set('state', this.uuid()); }
    var uri = this.get('authBaseUri');
    uri += '?response_type=' + encodeURIComponent(this.get('responseType')) +
        '&redirect_uri=' + encodeURIComponent(this.get('redirectUri')) +
        '&client_id=' + encodeURIComponent(this.get('clientId')) +
        '&state=' + encodeURIComponent(this.get('state'));
    if (this.get('scope')) uri += '&scope=' + encodeURIComponent(this.get('.scope')).replace('%20', '+');
    return uri;
  },

  /**
   * Open authorize window if the configuration object is valid.
   *
   * @method authorize
   * @return {Promise}
   */
  authorize: function() {
    if (!this.get('providerId')) throw new Error('No provider id given.');
    if (!this.get('clientId')) throw new Error('No client id given.');
    if (!this.get('authBaseUri')) throw new Error('No auth base uri given.');
    if (!this.get('redirectUri')) throw new Error('No redirect uri given.');
    var authorizeUri = this.authUri();
    this.clearStates();
    this.saveState(this.get('state'), this.requestObj());
    return this.openWindow(authorizeUri);
  },

  /**
   * Isolated function responsible for opening windows, to make it
   * easier to override this part in some environments (e.g. Phonegap)

    @param {String} url
    @return {Object} On resolve returns reference to the opened window.
                    On reject returns Object with reference to dialog and error.
   */
  openWindow: function(url) {
    var dialog = window.open(url, 'Authorize', 'height=600, width=450');
    if (window.focus && dialog) { dialog.focus(); }
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (dialog) { resolve(dialog); }
      else { reject(new Error('Opening dialog login window failed.')); }
    });
  },

  /**
   @method authSuccess
    @param {Object} The params returned from the OAuth2 callback
    @return {String} the access_token from the params
  */
  authSuccess: function(params) {
    return (this.get('responseType') === 'token' && params.access_token) ||
            (this.get('responseType') === 'code' && params.code);
  },

  /**
   * Token properties
   * providerId
   * expiresIn
   * scope
   * token

    @method generateToken
    @return {Object} The access_token object with info about the token
   */
  generateToken: function(params) {
    var token = {};
    token.provider_id = this.get('providerId');
    token.expires_in = this.expiresIn(params.expires_in);
    token.scope = this.get('scope');
    token.access_token = params.access_token;
    return token;
  },

  /**
    @method expiresIn
    @return {Number} When the token expires in seconds.
  */
  expiresIn: function(expires) {
    return this.now() + parseInt(expires, 10);
  },

  /**
   * call on redirect from OAuth2 provider response
    @method onRedirect
    @deprecated Use `.trigger('redirect')` instead.
   */
  onRedirect: function(hash, callback) {
    Ember.Logger.warn("Ember.OAuth2.onRedirect is deprecated and will be removed in future versions. Please use .trigger('redirect') instead.");
    this.trigger('redirect', hash, callback);
  },

  /*
   * proxy functions for old event handlers
   *
   * Check if the token returned is valid and if so trigger `success` event else trigger `error`
   *
   * @method handleRedirect
   */
  handleRedirect: function(hash, callback) {
    var params = this.parseCallback(hash);

    if (this.authSuccess(params)) {
      var stateObj = this.getState(params.state);
      this.checkState(stateObj);

      if (this.get('responseType') === "token") {
        this.saveToken(this.generateToken(params));
        this.trigger('success', stateObj);
      }
      else {
        this.trigger('success', params.code);
      }
    } else {
      this.trigger('error', params);
    }

    if (callback && typeof(callback) === "function") {
      callback();
    }
  },

  /**
   * Checks if the State returned from the server matches the state that was generated in the original request and saved in the browsers localStorage.
   *
   * @method checkState
   * @param {Object} stateObj The object returned from localStorage
   */
  checkState: function(stateObj) {
    if (!stateObj) throw new Error("Could not find state.");
    if (stateObj.state !== this.get('state')) throw new Error("State returned from the server did not match the local saved state.");
  },

  /**
   * Parse the callback function from the OAuth2 provider
   *
   * callback should have the following params if authentication is successful
   * state
   * access_token
   * token_type
   * expires_in
   *
   * @method parseCalback
   * @param {String} locationHash
   * @return {Object} The params returned from the OAuth2 provider
   */
  parseCallback: function(locationHash) {
    var oauthParams = {};
    var queryString = locationHash.substring(locationHash.indexOf('?'));
    var regex = /([^#?&=]+)=([^&]*)/g;
    var match;
    while ((match = regex.exec(queryString)) !== null) {
      oauthParams[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
    }
    return oauthParams;
  },

  /**
   * @method saveState
   * @param {String} state The state uuid
   * @param {Object} requestObj Properties of the request state to save in localStorage
   */
  saveState: function(state, requestObj) {
    window.localStorage.setItem(this.stateKeyName(), JSON.stringify(requestObj));
  },

  /**
   * Return the saved state and remove it from the localStoage.
   *
   * @method getState
   * @param {String} state The state uuid to retreive from localStorage
   * @return {Object} Properties of the request state
   */
  getState: function(state) {
    var keyName = state || this.stateKeyName();
    var obj = JSON.parse(window.localStorage.getItem(keyName));
    this.removeState();

    return obj;
  },

  /**
    * Remove any states from localStorage if they exist
    * @method clearStates
    * @return {Array} Keys used to remove states from localStorage
    */
  clearStates: function() {
    var regex = new RegExp( '^' + this.get('statePrefix') + '-.*', 'g');

    var name;
    var toRemove = [];
    for(var i = 0, l = window.localStorage.length; i < l; i++) {
      name = window.localStorage.key(i);
      if (name.match(regex)) {
        toRemove.push(name);
      }
    }

    for(var j = 0, len = toRemove.length; j < len; j++) {
      name = toRemove[j];
      this.removeState(name);
    }
    return toRemove;
  },

  /**
   * The key name to use for saving state to localstorage
   *
   * @method stateKeyName
   */
  stateKeyName: function() {
    return this.get('statePrefix') + '-' + this.get('state');
  },

  /**
   * The key name to use for saving the token to localstorage
   *
   * @method tokenKeyName
   */
  tokenKeyName: function() {
    return this.get('tokenPrefix') + '-' + this.get('providerId');
  },

  /**
   * saveToken stores the token by the tokenPrefix and the providerId
   * access_token
   * expires : time that the token expires
   * providerId: the providerId
   * scopes: array of scopes
   *
   * @method saveToken
   * @param {Object} token Saves the params in the response from the OAuth2 server to localStorage with the key 'tokenPrefix-providerId
   */
  saveToken: function(token) {
    window.localStorage.setItem(this.tokenKeyName(), JSON.stringify(token));
  },

  /**
   * remove the state from localstorage
   */
  removeState: function(stateName) {
    if (stateName) {
      return window.localStorage.removeItem(stateName);
    } else {
      return window.localStorage.removeItem(this.stateKeyName());
    }
  },

  /**
   * remove the token from localstorage
   */
  removeToken: function() {
    return window.localStorage.removeItem(this.tokenKeyName());
  },

  /**
   * @method getToken
   * @return {Object} The params from the OAuth2 response from localStorage with the key 'tokenPrefix-providerId'.
   */
  getToken: function() {
    var token = JSON.parse(window.localStorage.getItem(this.tokenKeyName()));
    if (!token) return null;
    if (!token.access_token) return null;
    return token;
  },

  /**
   * @method getAccessToken
   * @return {Object} The access_token param from the OAuth2 response from localStorage with the key 'tokenPrefix-providerId'.
   */
  getAccessToken: function() {
    var token = this.getToken();
    if (!token) return null;
    return token.access_token;
  },

  /**
   * @method accessTokenIsExpired
   * @return {Boolean} Check if the access_token is expired.
   */
  accessTokenIsExpired: function() {
    var token = this.getToken();
    if (!token) return true;
    if (this.now() >= token.expires_in) {
      return true;
    } else {
      return false;
    }
  },

  /**
   * Sets the access token expires_in time to 0 and saves the token to localStorage
   * @method expireAccessToken
   */
  expireAccessToken: function() {
    var token = this.getToken();
    if (!token) return null;
    token.expires_in = 0;
    this.saveToken(token);
  }
});

/**
 * @property {String} VERSION
 * @final
*/
var VERSION = "0.7.0";

/**
 * @method version
 * @static
 */
if (Ember.OAuth2) {
 Ember.OAuth2.version = VERSION;
}
<commit_msg>remove deprecated onRedirect callback<commit_after>import Ember from 'ember';

/**
  * @overview OAuth2 library for Emberjs that stores tokens in the browsers localStorage
  * @license   Licensed under MIT license
  *            See https://raw.github.com/amkirwan/ember-oauth2/master/LICENSE
  * @version   0.7.0
  *
  * @module ember-oauth2
  * @class ember-oauth2
  */
export default Ember.Object.extend(Ember.Evented, {
  /**
   * Initializes the Ember.OAuth2 object when using Ember.OAuth2.create({providerId: 'providerId'}). The following options are available for the configuring a provider: clientId, authBaseUri, redirectUri, scope, statePrefix and tokenPrefix. The clientId, authBaseUri and redirectUri are required. The statePrefix has a default value of 'state' and the tokenPrefix has a default value of 'token'.
   *
   * @method init
   */
  init: function() {
    this._super();
    /**
     * The configuration object for the given provider id.
     *  @property {Object} providerConfig
     *  @property {Object} providerConfig.providerId **Required**
     *  @property {String} providerConfig.providerId.clientId **Required**
     *  @property {String} providerConfig.providerId.authBaseUri **Required**
     *  @property {String} providerConfig.providerId.redirectUri **Required**
     *  @property {String} providerConfig.providerId.scope **Optional**
     *  @property {String} providerConfig.providerId.responseType **Default:** "token", **Optional**
     *  @property {String} providerConfig.providerId.statePrefix **Default:** "state", **Optional**
     *  @property {String} providerConfig.providerId.tokenPrefix **Default:** "prefix", **Optional**
     *  @example
     *    App.oauth = Ember.OAuth2.create({providerId: 'google'});
     */

    // if Ember.OAuth2.config has keys use it instead of window.ENV
    if (Ember.OAuth2 && Ember.OAuth2.config && Object.keys(Ember.OAuth2.config).length) {
      Ember.Logger.warn("Ember.OAuth2.config is deprecated and will be removed in future versions. Set the config using window.ENV['ember-oauth2']");
      this.set('config', Ember.OAuth2.config);
    } else if (window.EmberENV && window.EmberENV['ember-oauth2']) {
      this.set('config', window.EmberENV['ember-oauth2']);
    } else if (window.ENV && window.ENV['ember-oauth2']) {
      this.set('config', window.ENV['ember-oauth2']);
    } else {
      throw new Error('Cannot find the ember-oauth2 config.');
    }

    if (!this.get('config')[this.get('providerId')]) {
      throw new Error("Cannot find the providerId: '" + this.get('providerId') + "' in the config.");
    }

    this.set('providerConfig', this.get('config')[this.get('providerId')]);

    /**
     * The prefix name for the state key stored in the localStorage.
     *
     * @property statePrefix
     * @type String
     * @default "state"
     */
    this.set('statePrefix', 'state');
    /**
     * The prefix name for the token key stored in the localStorage.
     *
     * @property tokenPrefix
     * @type String
     * @default "token"
     */
    this.set('tokenPrefix', 'token');

    /**
     * The response type for the authorization request.
     *
     * @property responseType
     * @type String
     * @default "token"
     */
    this.set('responseType', 'token');

    /**
     * @property {String} clientId
     */
    /**
     * @property {String} authBaseUri
     */
    /**
     * @property {String} redirectUri
     */
    /**
     * @property {String} scope
     */
    // sets the properties from the providerConfig and overrides any default settings.
    this.setProperties(this.providerConfig);

    /**
     * @event redirect
     * @param {function} The function that handles the redirect.
     */
    this.on('redirect', this.handleRedirect);
  },

  /**
   * @method version
   * @return {String} The current version number of Ember.OAuth2
   */
  version: function() {
    return VERSION;
  },

  /**
   * @method uuid
   * @return {String} A pseudo random uuid
   */
  uuid: function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
              return v.toString(16);
    });
  },

  /**
   * @method now
   * @return {Number} The current time in seconds rounded
   */
  now: function() {
    return Math.round(new Date().getTime()/1000.0);
  },

  /**
   * Creates and returns the request object.
   *
   * @method requestObj
   * @return {Object} request object
   */
  requestObj: function() {
    var request = {};
    request.response_type = this.get('responseType');
    request.providerId = this.get('providerId');
    request.state = this.get('state');
    request.client_id = this.get('clientId');
    request.state = this.get('state');
    if (this.get('scope')) request.scope = this.get('scope');
    return request;
  },

  /**
   * @method authUri
   * @return {String} Authorization uri for generating an OAuth2 token
   */
  authUri: function() {
    if (!this.get('state')) { this.set('state', this.uuid()); }
    var uri = this.get('authBaseUri');
    uri += '?response_type=' + encodeURIComponent(this.get('responseType')) +
        '&redirect_uri=' + encodeURIComponent(this.get('redirectUri')) +
        '&client_id=' + encodeURIComponent(this.get('clientId')) +
        '&state=' + encodeURIComponent(this.get('state'));
    if (this.get('scope')) uri += '&scope=' + encodeURIComponent(this.get('.scope')).replace('%20', '+');
    return uri;
  },

  /**
   * Open authorize window if the configuration object is valid.
   *
   * @method authorize
   * @return {Promise}
   */
  authorize: function() {
    if (!this.get('providerId')) throw new Error('No provider id given.');
    if (!this.get('clientId')) throw new Error('No client id given.');
    if (!this.get('authBaseUri')) throw new Error('No auth base uri given.');
    if (!this.get('redirectUri')) throw new Error('No redirect uri given.');
    var authorizeUri = this.authUri();
    this.clearStates();
    this.saveState(this.get('state'), this.requestObj());
    return this.openWindow(authorizeUri);
  },

  /**
   * Isolated function responsible for opening windows, to make it
   * easier to override this part in some environments (e.g. Phonegap)

    @param {String} url
    @return {Object} On resolve returns reference to the opened window.
                    On reject returns Object with reference to dialog and error.
   */
  openWindow: function(url) {
    var dialog = window.open(url, 'Authorize', 'height=600, width=450');
    if (window.focus && dialog) { dialog.focus(); }
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (dialog) { resolve(dialog); }
      else { reject(new Error('Opening dialog login window failed.')); }
    });
  },

  /**
   @method authSuccess
    @param {Object} The params returned from the OAuth2 callback
    @return {String} the access_token from the params
  */
  authSuccess: function(params) {
    return (this.get('responseType') === 'token' && params.access_token) ||
            (this.get('responseType') === 'code' && params.code);
  },

  /**
   * Token properties
   * providerId
   * expiresIn
   * scope
   * token

    @method generateToken
    @return {Object} The access_token object with info about the token
   */
  generateToken: function(params) {
    var token = {};
    token.provider_id = this.get('providerId');
    token.expires_in = this.expiresIn(params.expires_in);
    token.scope = this.get('scope');
    token.access_token = params.access_token;
    return token;
  },

  /**
    @method expiresIn
    @return {Number} When the token expires in seconds.
  */
  expiresIn: function(expires) {
    return this.now() + parseInt(expires, 10);
  },

  /**
   * proxy functions for old event handlers
   *
   * Check if the token returned is valid and if so trigger `success` event else trigger `error`
   *
   * @method handleRedirect
   */
  handleRedirect: function(hash, callback) {
    var params = this.parseCallback(hash);

    if (this.authSuccess(params)) {
      var stateObj = this.getState(params.state);
      this.checkState(stateObj);

      if (this.get('responseType') === "token") {
        this.saveToken(this.generateToken(params));
        this.trigger('success', stateObj);
      }
      else {
        this.trigger('success', params.code);
      }
    } else {
      this.trigger('error', params);
    }

    if (callback && typeof(callback) === "function") {
      callback();
    }
  },

  /**
   * Checks if the State returned from the server matches the state that was generated in the original request and saved in the browsers localStorage.
   *
   * @method checkState
   * @param {Object} stateObj The object returned from localStorage
   */
  checkState: function(stateObj) {
    if (!stateObj) throw new Error("Could not find state.");
    if (stateObj.state !== this.get('state')) throw new Error("State returned from the server did not match the local saved state.");
  },

  /**
   * Parse the callback function from the OAuth2 provider
   *
   * callback should have the following params if authentication is successful
   * state
   * access_token
   * token_type
   * expires_in
   *
   * @method parseCalback
   * @param {String} locationHash
   * @return {Object} The params returned from the OAuth2 provider
   */
  parseCallback: function(locationHash) {
    var oauthParams = {};
    var queryString = locationHash.substring(locationHash.indexOf('?'));
    var regex = /([^#?&=]+)=([^&]*)/g;
    var match;
    while ((match = regex.exec(queryString)) !== null) {
      oauthParams[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
    }
    return oauthParams;
  },

  /**
   * @method saveState
   * @param {String} state The state uuid
   * @param {Object} requestObj Properties of the request state to save in localStorage
   */
  saveState: function(state, requestObj) {
    window.localStorage.setItem(this.stateKeyName(), JSON.stringify(requestObj));
  },

  /**
   * Return the saved state and remove it from the localStoage.
   *
   * @method getState
   * @param {String} state The state uuid to retreive from localStorage
   * @return {Object} Properties of the request state
   */
  getState: function(state) {
    var keyName = state || this.stateKeyName();
    var obj = JSON.parse(window.localStorage.getItem(keyName));
    this.removeState();

    return obj;
  },

  /**
    * Remove any states from localStorage if they exist
    * @method clearStates
    * @return {Array} Keys used to remove states from localStorage
    */
  clearStates: function() {
    var regex = new RegExp( '^' + this.get('statePrefix') + '-.*', 'g');

    var name;
    var toRemove = [];
    for(var i = 0, l = window.localStorage.length; i < l; i++) {
      name = window.localStorage.key(i);
      if (name.match(regex)) {
        toRemove.push(name);
      }
    }

    for(var j = 0, len = toRemove.length; j < len; j++) {
      name = toRemove[j];
      this.removeState(name);
    }
    return toRemove;
  },

  /**
   * The key name to use for saving state to localstorage
   *
   * @method stateKeyName
   */
  stateKeyName: function() {
    return this.get('statePrefix') + '-' + this.get('state');
  },

  /**
   * The key name to use for saving the token to localstorage
   *
   * @method tokenKeyName
   */
  tokenKeyName: function() {
    return this.get('tokenPrefix') + '-' + this.get('providerId');
  },

  /**
   * saveToken stores the token by the tokenPrefix and the providerId
   * access_token
   * expires : time that the token expires
   * providerId: the providerId
   * scopes: array of scopes
   *
   * @method saveToken
   * @param {Object} token Saves the params in the response from the OAuth2 server to localStorage with the key 'tokenPrefix-providerId
   */
  saveToken: function(token) {
    window.localStorage.setItem(this.tokenKeyName(), JSON.stringify(token));
  },

  /**
   * remove the state from localstorage
   */
  removeState: function(stateName) {
    if (stateName) {
      return window.localStorage.removeItem(stateName);
    } else {
      return window.localStorage.removeItem(this.stateKeyName());
    }
  },

  /**
   * remove the token from localstorage
   */
  removeToken: function() {
    return window.localStorage.removeItem(this.tokenKeyName());
  },

  /**
   * @method getToken
   * @return {Object} The params from the OAuth2 response from localStorage with the key 'tokenPrefix-providerId'.
   */
  getToken: function() {
    var token = JSON.parse(window.localStorage.getItem(this.tokenKeyName()));
    if (!token) return null;
    if (!token.access_token) return null;
    return token;
  },

  /**
   * @method getAccessToken
   * @return {Object} The access_token param from the OAuth2 response from localStorage with the key 'tokenPrefix-providerId'.
   */
  getAccessToken: function() {
    var token = this.getToken();
    if (!token) return null;
    return token.access_token;
  },

  /**
   * @method accessTokenIsExpired
   * @return {Boolean} Check if the access_token is expired.
   */
  accessTokenIsExpired: function() {
    var token = this.getToken();
    if (!token) return true;
    if (this.now() >= token.expires_in) {
      return true;
    } else {
      return false;
    }
  },

  /**
   * Sets the access token expires_in time to 0 and saves the token to localStorage
   * @method expireAccessToken
   */
  expireAccessToken: function() {
    var token = this.getToken();
    if (!token) return null;
    token.expires_in = 0;
    this.saveToken(token);
  }
});

/**
 * @property {String} VERSION
 * @final
*/
var VERSION = "0.7.0";

/**
 * @method version
 * @static
 */
if (Ember.OAuth2) {
 Ember.OAuth2.version = VERSION;
}
<|endoftext|>


<commit_before>window.fbAsyncInit = function() {
    FB.init({
        appId      : '1673441282934020',
        xfbml      : true,
        version    : 'v2.5'
    });

};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Check if the current user is logged in and has authorized the app
      FB.getLoginStatus(checkLoginStatus);

      // Login in the current user via Facebook and ask for email permission
      function authUser() {
        FB.login(checkLoginStatus, {scope:'email'});
      }

      // Check the result of the user status and display login button if necessary
      function checkLoginStatus(response) {
        if(response && response.status == 'connected') {
          alert('User is authorized');

          // Hide the login button
          document.getElementById('loginButton').style.display = 'none';

          // Now Personalize the User Experience
          console.log('Access Token: ' + response.authResponse.accessToken);
        } else {
          alert('User is not authorized');

          // Display the login button
          console.log("display the login button");
            document.getElementById('loginButton').style.display = 'block';
        }
      }
<commit_msg>um FB<commit_after>window.fbAsyncInit = function() {
    FB.init({
        appId      : '1673441282934020',
        xfbml      : true,
        version    : 'v2.5'
    });

// Check if the current user is logged in and has authorized the app
      FB.getLoginStatus(checkLoginStatus);
};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

      // Login in the current user via Facebook and ask for email permission
      function authUser() {
        FB.login(checkLoginStatus, {scope:'email'});
      }

      // Check the result of the user status and display login button if necessary
      function checkLoginStatus(response) {
        if(response && response.status == 'connected') {
          alert('User is authorized');

          // Hide the login button
          document.getElementById('loginButton').style.display = 'none';

          // Now Personalize the User Experience
          console.log('Access Token: ' + response.authResponse.accessToken);
        } else {
          alert('User is not authorized');

          // Display the login button
          console.log("display the login button");
            document.getElementById('loginButton').style.display = 'block';
        }
      }
<|endoftext|>


<commit_before>//

// The not-one-file source code can be found at:
// https://github.com/SanguPackage/Script

//
	//var start_time = new Date();
	//console.time("SanguPackage");
    var /**
         * When game_data.majorVersion is different from Sangu version then activate sangu 'compatibility' mode (gray icon)
         */
        sangu_version = '//',
        /**
         * true: popup with crash dump, false: don't show the popup
         */
        sangu_crash = sangu_version.split(".").length === 4,
        /**
         * jQuery element of the cell (td) that contains all page specific widgets
         */
        content_value = $("#content_value"),
        /**
         * config/ Configuration per server (nl, de). Contains stuff like ajaxAllowed, etc
         */
            server_settings = {},
        /**
         * config/ Contains all translations except for the setting related translations in sangu_trans
         */
        trans = {},
        /**
         * config/ Contains all user settings
         */
        user_data = {},
        /**
         * config/ The current world configuration. settings like hasArchers, nightbonus, etc
         */
         world_config = {},
        /**
         * config/ Contains all data for this world (resources, units, buildings, units_off, unitsSize, ...)
         * What's in this variable depends on world_config.
         * This variable is a complete and utter mess :)
         */
        world_data = {},
        /**
         * Identifies the current page based on the querystring
         */
        current_page = {
            screen: game_data.screen,
            mode: game_data.mode
        },
        keyCodeMap = {
            8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pausebreak", 20: "capslock", 27: "escape", 32: " ",
            33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "arrow left", 38: "arrow up", 39: "arrow right", 40: "arrow down", 43: "+",
            44: "printscreen", 45: "insert", 46: "delete", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9",
            59: ";", 61: "=", 65: "a",  66: "b", 67: "c", 68: "d", 69: "e", 70: "f", 71: "g", 72: "h", 73: "i", 74: "j", 75: "k", 76: "l", 77: "m",
            78: "n", 79: "o", 80: "p", 81: "q", 82: "r", 83: "s", 84: "t", 85: "u", 86: "v", 87: "w", 88: "x", 89: "y", 90: "z", 96: "0", 97: "1",
            98: "2", 99: "3", 100: "4", 101: "5",  102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1",
            113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6",  118: "f7", 119: "f8", 120: "f9",  121: "f10", 122: "f11", 123: "f12", 144: "numlock",
            145: "scrolllock", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"
        };

    //
    //

	//
	//
	//
	//

    //

    // User config
    //

    if (isSanguActive) {
		//
        //

        //
        //
		//

		//
		//

		q("-------------------------------------------------------------------- Start: "+sangu_version);

        // BEGIN PAGE PROCESSING
        switch (current_page.screen) {
            case "overview":
                // MAIN VILLAGE OVERVIEW
                (function() {
                    /**
                     * The slowest unit in the village in the form unit_spear
                     */
                    var slowest_unit = null;

                    //
                    //
                    //
                }());
                break;

            case "map":
                //
                break;

            case "report":
                if (current_page.mode === 'publish') {
                    //
                }
                break;

            case "main":
                //
                //
                //
                break;

            case "snob":
                if (current_page.mode === "train" || current_page.mode === null || current_page.mode === "produce") {
                    //
                }
                break;

            case "info_command":
                //
                break;

            case "market":
                //
                break;

            case "settings":
                // Add sangu to the menu
                //

                switch (current_page.mode) {
                    case "vacation":
                        //
                        break;

                    case "quickbar_edit":
                        //
                        break;
                }

                // SANGU SETTING EDITOR
                if (location.href.indexOf('mode=sangu') > -1) {
                    //
                    //
                    //
                    //
                }
                break;

            case "place":
                /**
                 * {spVillage} The current village
                 */
                var vilHome = getVillageFromCoords(game_data.village.coord);
                if ($("#attack_name").size() > 0) {
                    // RALLYPOINT CONFIRM
                    //
                }
                // RALLYPOINT UNITS THERE
                else if (current_page.mode === 'units' && location.href.indexOf('try=back') == -1) {
                    //
                }
                // RALLY POINT (DEFAULT)
                else {
                    //
                }
                break;

            case "overview_villages":
                break;
        }

		// USERPROFIEL++ // INFO_ ALLY/PLAYER
        if ((current_page.screen === 'info_ally' || current_page.screen === 'info_player' || current_page.screen === 'info_village')
            || (current_page.screen === "ally" && current_page.mode === "profile")) {

			//
        }
		if (current_page.screen === 'info_village') {
			//
		}

		// ALL OVERVIEW PAGES
        if (current_page.screen === 'overview_villages') {
			var overviewTable;
			//

			// PRODUCTION OVERVIEW
            if (location.href.indexOf('mode=prod') > -1) {
				//
            }
			// TROOPS OVERVIEW
            else if (location.href.indexOf('mode=units') > -1
						&& (location.href.indexOf('type=own_home') > -1 || location.href.indexOf('type=there') > -1)) {
                //
            }
			// BUILDINGS OVERVIEW
            else if (location.href.indexOf('mode=buildings') > -1) {
                //
            }
			// TECHS OVERVIEW // SMEDERIJ OVERVIEW // SMITHY OVERVIEW
            else if (location.href.indexOf('mode=tech') > -1) {
                //
            }
			// GROUPS OVERVIEW
            else if (location.href.indexOf('mode=groups') > -1) {
                //
            }
            // SUPPORT OVERVIEW
            else if (location.href.indexOf('type=support_detail') > -1
                || location.href.indexOf('type=away_detail') > -1) {

                //
            }
			// COMMANDS OVERVIEW
            else if (location.href.indexOf('mode=commands') > -1) {
                //
            }
			// INCOMINGS OVERVIEW
            else if (location.href.indexOf('mode=incomings') > -1) {
                //
            }

			//
        }

		var logoffLink = $("#linkContainer a:last");
        if (user_data.global.duplicateLogoffLink) {
            $("#linkContainer a:first").after(" - ").after(logoffLink.clone());
        }

        logoffLink.before(""+trans.sp.sp.moreScripts+"")
            .before(" - Sangu Package - ");

        (function() {
            var position = $("#sanguPackageEditSettingsLink").position(),
                options = {
                    left: position.left,
                    top: ($(window).height() - 100)
                },
                content = {
                    body: trans.sp.sp.firstTimeRunEditSettings
                };

            createFixedTooltip("sanguActivatorSettingsTooltip", content, options);
        }());

        //
		//
		//

		//var end_time = new Date();
		//console.timeEnd("SanguPackage");
		//q("" + pad(Math.abs(start_time.getTime() - end_time.getTime()), 3) + " -> " + location.search);
    }
//

if (location.href.indexOf('sangu.be') !== -1) {
    // sangu.be
    //

} else if (location.href.indexOf('tribalwars.nl') !== -1) {
    // TribalWars page
    //
}

<commit_msg>Update start.user.js<commit_after>//

// The not-one-file source code can be found at:
// https://github.com/SanguPackage/Script

//
	//var start_time = new Date();
	//console.time("SanguPackage");
    var /**
         * When game_data.majorVersion is different from Sangu version then activate sangu 'compatibility' mode (gray icon)
         */
        sangu_version = '//',
        /**
         * true: popup with crash dump, false: don't show the popup
         */
        sangu_crash = sangu_version.split(".").length === 4,
        /**
         * jQuery element of the cell (td) that contains all page specific widgets
         */
        content_value = $("#content_value"),
        /**
         * config/ Configuration per server (nl, de). Contains stuff like ajaxAllowed, etc
         */
            server_settings = {},
        /**
         * config/ Contains all translations except for the setting related translations in sangu_trans
         */
        trans = {},
        /**
         * config/ Contains all user settings
         */
        user_data = {},
        /**
         * config/ The current world configuration. settings like hasArchers, nightbonus, etc
         */
         world_config = {},
        /**
         * config/ Contains all data for this world (resources, units, buildings, units_off, unitsSize, ...)
         * What's in this variable depends on world_config.
         * This variable is a complete and utter mess :)
         */
        world_data = {},
        /**
         * Identifies the current page based on the querystring
         */
        current_page = {
            screen: game_data.screen,
            mode: game_data.mode
        },
        keyCodeMap = {
            8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pausebreak", 20: "capslock", 27: "escape", 32: " ",
            33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "arrow left", 38: "arrow up", 39: "arrow right", 40: "arrow down", 43: "+",
            44: "printscreen", 45: "insert", 46: "delete", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9",
            59: ";", 61: "=", 65: "a",  66: "b", 67: "c", 68: "d", 69: "e", 70: "f", 71: "g", 72: "h", 73: "i", 74: "j", 75: "k", 76: "l", 77: "m",
            78: "n", 79: "o", 80: "p", 81: "q", 82: "r", 83: "s", 84: "t", 85: "u", 86: "v", 87: "w", 88: "x", 89: "y", 90: "z", 96: "0", 97: "1",
            98: "2", 99: "3", 100: "4", 101: "5",  102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1",
            113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6",  118: "f7", 119: "f8", 120: "f9",  121: "f10", 122: "f11", 123: "f12", 144: "numlock",
            145: "scrolllock", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"
        };

    //
    //

	//
	//
	//
	//

    //

    // User config
    //

    if (isSanguActive) {
		//
        //

        //
        //
		//

		//
		//

		q("-------------------------------------------------------------------- Start: "+sangu_version);

        // BEGIN PAGE PROCESSING
        switch (current_page.screen) {
            case "overview":
                // MAIN VILLAGE OVERVIEW
                (function() {
                    /**
                     * The slowest unit in the village in the form unit_spear
                     */
                    var slowest_unit = null;

                    //
                    //
                    //
                }());
                break;

            case "map":
                //
                break;

            case "report":
                if (current_page.mode === 'publish') {
                    //
                }
                break;

            case "main":
                //
                //
                //
                break;

            case "snob":
                if (current_page.mode === "train" || current_page.mode === null || current_page.mode === "produce") {
                    //
                }
                break;

            case "info_command":
                //
                break;

            case "market":
                //
                break;

            case "settings":
                // Add sangu to the menu
                //

                switch (current_page.mode) {
                    case "vacation":
                        //
                        break;

                    case "quickbar_edit":
                        //
                        break;
                }

                // SANGU SETTING EDITOR
                if (location.href.indexOf('mode=sangu') > -1) {
                    //
                    //
                    //
                    //
                }
                break;

            case "place":
                /**
                 * {spVillage} The current village
                 */
                var vilHome = getVillageFromCoords(game_data.village.coord);
                if ($("#attack_name").size() > 0) {
                    // RALLYPOINT CONFIRM
                    //
                }
                // RALLYPOINT UNITS THERE
                else if (current_page.mode === 'units' && location.href.indexOf('try=back') == -1) {
                    //
                }
                // RALLY POINT (DEFAULT)
                else {
                    //
                }
                break;

            case "overview_villages":
                break;
        }

		// USERPROFIEL++ // INFO_ ALLY/PLAYER
        if ((current_page.screen === 'info_ally' || current_page.screen === 'info_player' || current_page.screen === 'info_village')
            || (current_page.screen === "ally" && current_page.mode === "profile")) {

			//
        }
		if (current_page.screen === 'info_village') {
			//
		}

		// ALL OVERVIEW PAGES
        if (current_page.screen === 'overview_villages') {
			var overviewTable;
			//

			// PRODUCTION OVERVIEW
            if (location.href.indexOf('mode=prod') > -1) {
				//
            }
			// TROOPS OVERVIEW
            else if (location.href.indexOf('mode=units') > -1
						&& (location.href.indexOf('type=own_home') > -1 || location.href.indexOf('type=there') > -1)) {
                //
            }
			// BUILDINGS OVERVIEW
            else if (location.href.indexOf('mode=buildings') > -1) {
                //
            }
			// TECHS OVERVIEW // SMEDERIJ OVERVIEW // SMITHY OVERVIEW
            else if (location.href.indexOf('mode=tech') > -1) {
                //
            }
			// GROUPS OVERVIEW
            else if (location.href.indexOf('mode=groups') > -1) {
                //
            }
            // SUPPORT OVERVIEW
            else if (location.href.indexOf('type=support_detail') > -1
                || location.href.indexOf('type=away_detail') > -1) {

                //
            }
			// COMMANDS OVERVIEW
            else if (location.href.indexOf('mode=commands') > -1) {
                //
            }
			// INCOMINGS OVERVIEW
            else if (location.href.indexOf('mode=incomings') > -1) {
                //
            }

			//
        }

		var logoffLink = $("#linkContainer a:last");
        if (user_data.global.duplicateLogoffLink) {
            $("#linkContainer a:first").after(" - ").after(logoffLink.clone());
        }

        logoffLink.before(" - "+trans.sp.sp.moreScripts+"")
            .before(" - Sangu Package - ");

        (function() {
            var position = $("#sanguPackageEditSettingsLink").position(),
                options = {
                    left: position.left,
                    top: ($(window).height() - 100)
                },
                content = {
                    body: trans.sp.sp.firstTimeRunEditSettings
                };

            createFixedTooltip("sanguActivatorSettingsTooltip", content, options);
        }());

        //
		//
		//

		//var end_time = new Date();
		//console.timeEnd("SanguPackage");
		//q("" + pad(Math.abs(start_time.getTime() - end_time.getTime()), 3) + " -> " + location.search);
    }
//

if (location.href.indexOf('sangu.be') !== -1) {
    // sangu.be
    //

} else if (location.href.indexOf('tribalwars.nl') !== -1) {
    // TribalWars page
    //
}

<|endoftext|>


<commit_before>var Address4 = require("ip-address").Address4;
var Address6 = require("ip-address").Address6;

var config = require("../helpers/config");
var controller = require("../helpers/controller");
var Tools = require("../helpers/tools");

module.exports = function(req, res, next) {
    if (req.socket.ip) {
        Object.defineProperty(req, "ip", { value: req.socket.ip });
        next();
        return;
    }
    var trueIp = Tools.correctAddress(req.ip || req.connection.remoteAddress);
    if (!trueIp)
        return res.sendStatus(500);
    if (config("system.detectRealIp", true)) {
        var ip = req.headers["x-forwarded-for"];
        if (!ip)
            ip = req.headers["x-client-ip"];
        if (ip) {
            var address = Tools.correctAddress(ip);
            if (!address)
                return res.sendStatus(500);
            trueIp = address;
        }
    }
    if (config("system.useXRealIp", false)) {
        var ip = req.headers["x-real-ip"];
        var address = Tools.correctAddress(ip);
        if (!address)
            return res.sendStatus(500);
        trueIp = address;
    }
    Object.defineProperty(req, "ip", { value: trueIp });
    Object.defineProperty(req.socket, "ip", { value: trueIp });
    next();
};
<commit_msg>Debug<commit_after>var Address4 = require("ip-address").Address4;
var Address6 = require("ip-address").Address6;

var config = require("../helpers/config");
var controller = require("../helpers/controller");
var Tools = require("../helpers/tools");

module.exports = function(req, res, next) {
    console.log(req.ip, req.connection.remoteAddress, req.socket.ip);
    if (req.socket.ip) {
        Object.defineProperty(req, "ip", { value: req.socket.ip });
        next();
        return;
    }
    var trueIp = Tools.correctAddress(req.ip || req.connection.remoteAddress);
    if (!trueIp)
        return res.sendStatus(500);
    if (config("system.detectRealIp", true)) {
        var ip = req.headers["x-forwarded-for"];
        if (!ip)
            ip = req.headers["x-client-ip"];
        if (ip) {
            var address = Tools.correctAddress(ip);
            if (!address)
                return res.sendStatus(500);
            trueIp = address;
        }
    }
    if (config("system.useXRealIp", false)) {
        var ip = req.headers["x-real-ip"];
        var address = Tools.correctAddress(ip);
        if (!address)
            return res.sendStatus(500);
        trueIp = address;
    }
    Object.defineProperty(req, "ip", { value: trueIp });
    Object.defineProperty(req.socket, "ip", { value: trueIp });
    next();
};
<|endoftext|>


<commit_before>const path = require('path')
//const process = require('process')
//const util = require('util')
const lambda = require(path.resolve(`./build/lambdas/${process.argv[2]}/index`))

// Build context object for Lambda
const context = {
  succeed: (result) => process.send({ type: 'success', output: result }),
  fail: (error) => process.send({ type: 'error', output: error })
}

//console.log(util.inspect(process.memoryUsage())

// Call lambda's handler
lambda.handler(JSON.parse(process.env.event), context)<commit_msg>Ensuring child proc exit<commit_after>/* eslint no-process-exit: 0 */
const path = require('path')
//const process = require('process')
//const util = require('util')
const lambda = require(path.resolve(`./build/lambdas/${process.argv[2]}/index`))

// Build context object for Lambda
const context = {
  succeed: (result) => {
    process.send({ type: 'success', output: result })
    context.done()
  },
  fail: (error) => {
    process.send({ type: 'error', output: error })
    context.done()
  },
  done: () => {
    process.exit()
  }
}

//setInterval(() => process.send({ output: util.inspect(process.memoryUsage()) }), 1)

//console.log(util.inspect(process.memoryUsage())

// Call lambda's handler
lambda.handler(JSON.parse(process.env.event), context)<|endoftext|>


<commit_before>'use strict';

let five = require('johnny-five');
let board = new five.Board();

board.on('ready', () => {
  let temperature = new five.Thermometer({
    controller: 'TMP36',
    pin: 'A0'
  });

  let piezo = new five.Piezo(9);
  let led = new five.Led(13);
  let button = new five.Button(5);

  let buttonPressed = false;

  temperature.on('data', function() {
    if (this.celsius > 50) {
      console.log('temp > 50');
      if (!buttonPressed) {
        console.log('piezo on');
        piezo.play({
          song: 'C E G E C E G E',
          tempo: 100,
        });
        led.on();
      }
    } else {
      console.log('temp < 50');
      buttonPressed = false;
      console.log('piezo off');
      piezo.off();
      led.off();
    }
  });

  button.on('press', () => {
    buttonPressed = true;
    console.log('piezo off');
    piezo.off();
    led.off();
  });
});
<commit_msg>fire alarm fix<commit_after>'use strict';

let five = require('johnny-five');
let board = new five.Board();

board.on('ready', () => {
  let temperature = new five.Thermometer({
    controller: 'TMP36',
    pin: 'A0'
  });

  let piezo = new five.Piezo(9);
  let led = new five.Led(13);
  let button = new five.Button(5);

  let buttonPressed = false;
  let alarmOn = false;

  function turnOff() {
    if (alarmOn) {
      console.log('turning off');
      piezo.off();
      led.off();
      alarmOn = false;
    }
  }

  temperature.on('data', function() {
    if (this.celsius > 50) {
      if (!buttonPressed && !alarmOn) {
        console.log('turning on');
        alarmOn = true;
        piezo.frequency(587, 1000000);
        led.on();
      }
    } else {
      turnOff();
      if (buttonPressed) {
        console.log('temp < 50, canceling button-mode');
        buttonPressed = false;
      }
    }
  });

  button.on('press', () => {
    buttonPressed = true;
    turnOff();
  });
});
<|endoftext|>


<commit_before>/**
 * Posts schema
 * @type {SimpleSchema}
 */
Posts.schema = new SimpleSchema({
  /**
    ID
  */
  _id: {
    type: String,
    optional: true
  },
  /**
    Timetstamp of post creation
  */
  createdAt: {
    type: Date,
    optional: true
  },
  /**
    Timestamp of post first appearing on the site (i.e. being approved)
  */
  postedAt: {
    type: Date,
    optional: true,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      type: "bootstrap-datetimepicker"
    }
  },
  /**
    Title
  */
  Title: {
    type: String,
    optional: false,
    editableBy: ["member", "admin"]
  },
  /**
    Count of how many times the post's page was viewed
  */
  viewCount: {
    type: Number,
    optional: true
  },
  /**
    Count of the post's comments
  */
  commentCount: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of commenters
  */
  commenters: {
    type: [String],
    optional: true
  },
  /**
    Timestamp of the last comment
  */
  lastCommentedAt: {
    type: Date,
    optional: true
  },
  /**
    Count of how many times the post's link was clicked
  */
  clickCount: {
    type: Number,
    optional: true
  },
  /**
    The post's base score (not factoring in the post's age)
  */
  baseScore: {
    type: Number,
    decimal: true,
    optional: true
  },
  /**
    How many upvotes the post has received
  */
  upvotes: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of the post's upvoters
  */
  upvoters: {
    type: [String],
    optional: true
  },
  /**
    How many downvotes the post has received
  */
  downvotes: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of the post's downvoters
  */
  downvoters: {
    type: [String],
    optional: true
  },
  /**
    The post's current score (factoring in age)
  */
  score: {
    type: Number,
    decimal: true,
    optional: true
  },
  /**
    The post's status. One of pending (`1`), approved (`2`), or deleted (`3`)
  */
  status: {
    type: Number,
    optional: true,
    editableBy: ["admin"],
    autoValue: function () {
      // only provide a default value
      // 1) this is an insert operation
      // 2) status field is not set in the document being inserted
      var user = Meteor.users.findOne(this.userId);
      if (this.isInsert && !this.isSet)
        return Posts.getDefaultStatus(user);
    },
    autoform: {
      noselect: true,
      options: Posts.config.postStatuses,
      group: 'admin'
    }
  },
  /**
    Whether the post is sticky (pinned to the top of posts lists)
  */
  sticky: {
    type: Boolean,
    optional: true,
    defaultValue: false,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      leftLabel: "Sticky"
    }
  },
  /**
    Whether the post is inactive. Inactive posts see their score recalculated less often
  */
  inactive: {
    type: Boolean,
    optional: true
  },
  /**
    The post author's name
  */
  author: {
    type: String,
    optional: true
  },
  /**
    The post author's `_id`.
  */
  userId: {
    type: String, // XXX
    optional: true,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      options: function () {
        return Meteor.users.find().map(function (user) {
          return {
            value: user._id,
            label: Users.getDisplayName(user)
          };
        });
      }
    }
  }
});

// schema transforms
Posts.schema.internationalize();

/**
 * Attach schema to Posts collection
 */
Posts.attachSchema(Posts.schema);

Posts.allow({
  update: _.partial(Telescope.allowCheck, Posts),
  remove: _.partial(Telescope.allowCheck, Posts)
});
<commit_msg>ghetto undo of bad change<commit_after>/**
 * Posts schema
 * @type {SimpleSchema}
 */
Posts.schema = new SimpleSchema({
  /**
    ID
  */
  _id: {
    type: String,
    optional: true
  },
  /**
    Timetstamp of post creation
  */
  createdAt: {
    type: Date,
    optional: true
  },
  /**
    Timestamp of post first appearing on the site (i.e. being approved)
  */
  postedAt: {
    type: Date,
    optional: true,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      type: "bootstrap-datetimepicker"
    }
  },
  /**
    Title
  */
  title: {
    type: String,
    optional: false,
    editableBy: ["member", "admin"]
  },
  /**
    Count of how many times the post's page was viewed
  */
  viewCount: {
    type: Number,
    optional: true
  },
  /**
    Count of the post's comments
  */
  commentCount: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of commenters
  */
  commenters: {
    type: [String],
    optional: true
  },
  /**
    Timestamp of the last comment
  */
  lastCommentedAt: {
    type: Date,
    optional: true
  },
  /**
    Count of how many times the post's link was clicked
  */
  clickCount: {
    type: Number,
    optional: true
  },
  /**
    The post's base score (not factoring in the post's age)
  */
  baseScore: {
    type: Number,
    decimal: true,
    optional: true
  },
  /**
    How many upvotes the post has received
  */
  upvotes: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of the post's upvoters
  */
  upvoters: {
    type: [String],
    optional: true
  },
  /**
    How many downvotes the post has received
  */
  downvotes: {
    type: Number,
    optional: true
  },
  /**
    An array containing the `_id`s of the post's downvoters
  */
  downvoters: {
    type: [String],
    optional: true
  },
  /**
    The post's current score (factoring in age)
  */
  score: {
    type: Number,
    decimal: true,
    optional: true
  },
  /**
    The post's status. One of pending (`1`), approved (`2`), or deleted (`3`)
  */
  status: {
    type: Number,
    optional: true,
    editableBy: ["admin"],
    autoValue: function () {
      // only provide a default value
      // 1) this is an insert operation
      // 2) status field is not set in the document being inserted
      var user = Meteor.users.findOne(this.userId);
      if (this.isInsert && !this.isSet)
        return Posts.getDefaultStatus(user);
    },
    autoform: {
      noselect: true,
      options: Posts.config.postStatuses,
      group: 'admin'
    }
  },
  /**
    Whether the post is sticky (pinned to the top of posts lists)
  */
  sticky: {
    type: Boolean,
    optional: true,
    defaultValue: false,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      leftLabel: "Sticky"
    }
  },
  /**
    Whether the post is inactive. Inactive posts see their score recalculated less often
  */
  inactive: {
    type: Boolean,
    optional: true
  },
  /**
    The post author's name
  */
  author: {
    type: String,
    optional: true
  },
  /**
    The post author's `_id`.
  */
  userId: {
    type: String, // XXX
    optional: true,
    editableBy: ["admin"],
    autoform: {
      group: 'admin',
      options: function () {
        return Meteor.users.find().map(function (user) {
          return {
            value: user._id,
            label: Users.getDisplayName(user)
          };
        });
      }
    }
  }
});

// schema transforms
Posts.schema.internationalize();

/**
 * Attach schema to Posts collection
 */
Posts.attachSchema(Posts.schema);

Posts.allow({
  update: _.partial(Telescope.allowCheck, Posts),
  remove: _.partial(Telescope.allowCheck, Posts)
});
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name openlmis-dashboard.NavigationService
     *
     * @description
     * Reads routes set in UI-Router and returns all routes that are visible to the user.
     *
     * When writting UI-Router routes, set the route with 'showInNavigation: true' which will add the route to the navigation service. The parent state from the UI-Router definition is used to create a hiearchy for navigation states.
     *
     * TODO: Check if a user has authorization to view the URL
     *
     */

    angular
        .module('openlmis-dashboard')
        .service('NavigationService', NavigationService);

    NavigationService.$inject = ['$rootScope', '$state', '$filter', 'AuthorizationService'];

    function NavigationService($rootScope, $state, $filter, AuthorizationService) {
        var roots = initialize();

        this.getRoot = getRoot;
        this.shouldDisplay = shouldDisplay;
        this.hasChildren = hasChildren;
        this.isSubmenu = isSubmenu;

		function hasChildren(state, visibleOnly) {
            var result = false;
            angular.forEach(state.children, function(child) {
                if (visibleOnly) {
                    result = result || shouldDisplay(child);
                } else {
                    result = result || (state.children && state.children.length);
                }
            })
			return result;
		}

		function isSubmenu(state){
			return !isRoot(state) && hasChildren(state);
		}

		function shouldDisplay(state) {
			return state.showInNavigation
                && (!state.accessRight || AuthorizationService.hasRights(state.accessRight))
                && (!state.abstract || hasChildren(state, true));
		}

        function initialize() {
            var roots = {}

            $state.get().forEach(function(state) {
                if (state.showInNavigation) {
                    var parentName = getParentStateName(state);

                    var filtered = $filter('filter')($state.get(), {
                        name: parentName
                    }, true);

                    var parent = filtered[0];
                    if (parent.showInNavigation) {
                        addChildState(parent, state);
                    } else {
                        addToRoots(roots, parentName, state);
                    }
                }
            });

            for (var root in roots) {
                roots[root] = sortStates(roots[root]);
            }

            return roots;
        }

        function getRoot(name) {
            return roots[name];
        }

        function getParentStateName(state) {
            var lastDot = state.name.lastIndexOf('.');
            return lastDot ? state.name.substring(0, lastDot) : '';
        }

        function addChildState(parent, state) {
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(state);
        }

        function addToRoots(roots, parentName, state) {
            if (!roots[parentName]) {
                roots[parentName] = [];
            }
            roots[parentName].push(state);
        }

        function sortStates(states) {
            var sorted = $filter('orderBy')(states, ['-priority', 'name']);
            sorted.forEach(function(state) {
                if (state.children) {
                    state.children = sortStates(state.children);
                }
            });
            return sorted;
        }

        function isRoot(state) {
            for (var root in roots) {
                if (roots[root].indexOf(state) !== -1) {
                    return true;
                }
            }
            return false;
        }
    }

})();
<commit_msg>OLMIS-1375: fixed missing 's' on accessRigth property<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name openlmis-dashboard.NavigationService
     *
     * @description
     * Reads routes set in UI-Router and returns all routes that are visible to the user.
     *
     * When writting UI-Router routes, set the route with 'showInNavigation: true' which will add the route to the navigation service. The parent state from the UI-Router definition is used to create a hiearchy for navigation states.
     *
     * TODO: Check if a user has authorization to view the URL
     *
     */

    angular
        .module('openlmis-dashboard')
        .service('NavigationService', NavigationService);

    NavigationService.$inject = ['$rootScope', '$state', '$filter', 'AuthorizationService'];

    function NavigationService($rootScope, $state, $filter, AuthorizationService) {
        var roots = initialize();

        this.getRoot = getRoot;
        this.shouldDisplay = shouldDisplay;
        this.hasChildren = hasChildren;
        this.isSubmenu = isSubmenu;

		function hasChildren(state, visibleOnly) {
            var result = false;
            angular.forEach(state.children, function(child) {
                if (visibleOnly) {
                    result = result || shouldDisplay(child);
                } else {
                    result = result || (state.children && state.children.length);
                }
            })
			return result;
		}

		function isSubmenu(state){
			return !isRoot(state) && hasChildren(state);
		}

		function shouldDisplay(state) {
			return state.showInNavigation
                && (!state.accessRights || AuthorizationService.hasRights(state.accessRights))
                && (!state.abstract || hasChildren(state, true));
		}

        function initialize() {
            var roots = {}

            $state.get().forEach(function(state) {
                if (state.showInNavigation) {
                    var parentName = getParentStateName(state);

                    var filtered = $filter('filter')($state.get(), {
                        name: parentName
                    }, true);

                    var parent = filtered[0];
                    if (parent.showInNavigation) {
                        addChildState(parent, state);
                    } else {
                        addToRoots(roots, parentName, state);
                    }
                }
            });

            for (var root in roots) {
                roots[root] = sortStates(roots[root]);
            }

            return roots;
        }

        function getRoot(name) {
            return roots[name];
        }

        function getParentStateName(state) {
            var lastDot = state.name.lastIndexOf('.');
            return lastDot ? state.name.substring(0, lastDot) : '';
        }

        function addChildState(parent, state) {
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(state);
        }

        function addToRoots(roots, parentName, state) {
            if (!roots[parentName]) {
                roots[parentName] = [];
            }
            roots[parentName].push(state);
        }

        function sortStates(states) {
            var sorted = $filter('orderBy')(states, ['-priority', 'name']);
            sorted.forEach(function(state) {
                if (state.children) {
                    state.children = sortStates(state.children);
                }
            });
            return sorted;
        }

        function isRoot(state) {
            for (var root in roots) {
                if (roots[root].indexOf(state) !== -1) {
                    return true;
                }
            }
            return false;
        }
    }

})();
<|endoftext|>


<commit_before>const emoji_map = {
  "1 person": "👤",
  "2 people": "👥",
  "3 people": "👥",
  "4 people": "👥",
  "5 people": "👥",
  "6 people": "👥",
  "7 people": "👥",
  "baby": "🍼",
  "beach": "🏖",
  "beard": "👴",
  "bicycle": "🚲",
  "camera": "📷",
  "car": "🚗",
  "cat": "😺",
  "child": "👦",
  "christmas tree": "🎄",
  "closeup": "👀",
  "cloud": "☁",
  "crowd": "👥",
  "dog": "🐶",
  "drink": "🍹",
  "eating": "🍽",
  "eyeglasses": "👓",
  "flower": "🌻",
  "food": "🍎",
  "golf": "🏌",
  "grass": "🍃",
  "hat": "👒",
  "indoor": "🏠",
  "living room": "🏠",
  "meme": "👍",
  "mountain": "🌋",
  "nature": "🏞",
  "night": "🌃",
  "ocean": "🌊",
  "office": "💼",
  "one or more people": "👥",
  "outdoor": "🚵",
  "people eating": "🍽",
  "people sitting": "⑁",
  "people smiling": "😂",
  "people standing": "🕴",
  "phone": "📱",
  "plant": "🌿",
  "selfie": "🤳",
  "shoes": "👡",
  "sitting": "⑁",
  "sky": "☀",
  "skyscraper": "🏙",
  "sleeping": "😴",
  "smiling": "😋",
  "snow": "❄",
  "standing": "🕴",
  "stripes": "📶",
  "suit": "🕴",
  "sunglasses": "🕶",
  "swimming": "🏊",
  "table": "🍽",
  "text": "🔠",
  "tree": "🌴",
  "twilight": "🌃",
  "water": "💧"
}

const show_facebook_cv_tags = function() {
  const TAG_PREFIX = "Image may contain: ";
  const images = [...document.getElementsByTagName('img')];

  images.forEach(function(el) {
    if (el.hasAttribute("data-prev-alt") && el.getAttribute("data-prev-alt") === el.getAttribute("alt"))
      return;

    el.setAttribute("data-prev-alt", el.alt);

    const altText = el.alt;
    const isCVTag = altText.startsWith(TAG_PREFIX);

    if (isCVTag) {
      const tags = altText.slice(TAG_PREFIX.length).split(/, | and /);
      let html = "
";

      tags.forEach(function(tag){
        let prefix = "∙";

        if (tag in emoji_map)
          prefix = emoji_map[tag];

        html += `<li>${prefix} ${tag}</li>`;
      });

      html += "
";

      el.style.position = 'relative';
      el.insertAdjacentHTML('afterend', html);
    }
  });
};

const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        show_facebook_cv_tags();
    });
});

const config = { attributes: true, childList: true, characterData: false }

observer.observe(document.body, config);

show_facebook_cv_tags();
<commit_msg>Fix close-up and add somes emojis<commit_after>const emoji_map = {
  "1 person": "👤",
  "2 people": "👥",
  "3 people": "👥",
  "4 people": "👥",
  "5 people": "👥",
  "6 people": "👥",
  "7 people": "👥",
  "baby": "🍼",
  "beach": "🏖",
  "beard": "👴",
  "bedroom": "🛏",
  "bicycle": "🚲",
  "camera": "📷",
  "car": "🚗",
  "cat": "😺",
  "child": "👦",
  "christmas tree": "🎄",
  "close-up": "👀",
  "closeup": "👀",
  "cloud": "☁",
  "concert": "🎤",
  "crowd": "👥",
  "dancing": "💃",
  "dessert": "🍰",
  "dog": "🐶",
  "drink": "🍹",
  "eating": "🍽",
  "eyeglasses": "👓",
  "fireworks": "🎆",
  "flower": "🌻",
  "food": "🍎",
  "glasses": "🕶",
  "golf": "🏌",
  "grass": "🍃",
  "hat": "👒",
  "indoor": "🏠",
  "living room": "🏠",
  "meme": "👍",
  "mountain": "🌋",
  "nature": "🏞",
  "night": "🌃",
  "ocean": "🌊",
  "office": "💼",
  "one or more people": "👥",
  "outdoor": "🚵",
  "people eating": "🍽",
  "people on stage": "🎤",
  "people playing musical instruments": "🎸",
  "people playing sport": "🏀",
  "people sitting": "⑁",
  "people smiling": "😂",
  "people standing": "🕴",
  "phone": "📱",
  "plant": "🌿",
  "playing a musical instrument": "🎸",
  "selfie": "🤳",
  "shoes": "👡",
  "sitting": "⑁",
  "sky": "☀",
  "skyscraper": "🏙",
  "sleeping": "😴",
  "smiling": "😋",
  "snow": "❄",
  "standing": "🕴",
  "stripes": "📶",
  "suit": "🕴",
  "sunglasses": "🕶",
  "swimming": "🏊",
  "table": "🍽",
  "text": "🔠",
  "tree": "🌴",
  "twilight": "🌃",
  "water": "💧",
  "wedding": "💒"
}

const show_facebook_cv_tags = function() {
  const TAG_PREFIX = "Image may contain: ";
  const images = [...document.getElementsByTagName('img')];

  images.forEach(function(el) {
    if (el.hasAttribute("data-prev-alt") && el.getAttribute("data-prev-alt") === el.getAttribute("alt"))
      return;

    el.setAttribute("data-prev-alt", el.alt);

    const altText = el.alt;
    const isCVTag = altText.startsWith(TAG_PREFIX);

    if (isCVTag) {
      const tags = altText.slice(TAG_PREFIX.length).split(/, | and /);
      let html = "
";

      tags.forEach(function(tag){
        let prefix = "∙";

        if (tag in emoji_map)
          prefix = emoji_map[tag];

        html += `<li>${prefix} ${tag}</li>`;
      });

      html += "
";

      el.style.position = 'relative';
      el.insertAdjacentHTML('afterend', html);
    }
  });
};

const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        show_facebook_cv_tags();
    });
});

const config = { attributes: true, childList: true, characterData: false }

observer.observe(document.body, config);

show_facebook_cv_tags();
<|endoftext|>


<commit_before>import Cache from 'ember-orbit/cache';
import IdentityMap from 'ember-orbit/identity-map';
import OrbitStore from 'orbit-common/store';
import Query from 'orbit/query';
import objectValues from 'ember-orbit/utils/object-values';
import qb from 'orbit-common/query/builder';
import {
  addRecord,
  removeRecord
} from 'orbit-common/transform/operators';

/**
 @module ember-orbit
 */

const { assert } = Ember;

export default Ember.Object.extend({
  orbitStore: null,
  schema: null,
  cache: null,
  _identityMap: null,

  init() {
    this._super(...arguments);

    assert("`schema` must be injected onto a Store", this.schema);

    if (!this.orbitStore) {
      this.orbitStore = new OrbitStore({ schema: this.schema.orbitSchema });
    }

    const orbitCache = this.orbitStore.cache;

    assert("A Store's `orbitStore` must have its own `cache`", orbitCache);

    this._identityMap = IdentityMap.create({ _schema: this.schema, _orbitCache: orbitCache, _store: this });
    this.cache = Cache.create({ _orbitCache: orbitCache, _identityMap: this._identityMap });

    orbitCache.patches.subscribe(operation => this._didPatch(operation));
  },

  find(type, id) {
    if (id === undefined) {
      return this.query(qb.records(type));
    } else {
      return this.query(qb.record({type, id}));
    }
  },

  query(queryOrExpression) {
    const query = Query.from(queryOrExpression, this.orbitStore.queryBuilder);
    return this.orbitStore.query(query)
      .then(result => {
        switch(query.expression.op) {
          case 'record':  return this._identityMap.lookup(result);
          case 'records': return this._identityMap.lookupMany(objectValues(result));
          case 'filter':  return this._identityMap.lookupMany(objectValues(result));
          default:        return result;
        }
      });
  },

  update(...args) {
    return this.orbitStore.update(...args);
  },

  addRecord(properties = {}) {
    this._verifyType(properties.type);

    const record = this.schema.normalize(properties);
    return this.update(addRecord(record))
      .then(() => this._identityMap.lookup(record));
  },

  findRecord(type, id) {
    return this.query(qb.record({type, id}));
  },

  removeRecord(record) {
    return this.update(removeRecord(record));
  },

  _verifyType(type) {
    assert("`type` must be registered as a model in the store's schema", this.schema.modelFor(type));
  },

  _didPatch: function(operation) {
    // console.debug('didPatch', operation);
    const { type, id } = operation.record;
    const record = this._identityMap.lookup({ type, id });

    switch(operation.op) {
      case 'replaceAttribute': return record.propertyDidChange(operation.attribute);
      case 'replaceHasOne': return record.propertyDidChange(operation.relationship);
      case 'removeRecord': return record.disconnect();
    }
  }
});
<commit_msg>Orbit KeyMap has been extracted from the Store.<commit_after>import Cache from 'ember-orbit/cache';
import IdentityMap from 'ember-orbit/identity-map';
import KeyMap from 'orbit-common/key-map';
import OrbitStore from 'orbit-common/store';
import Query from 'orbit/query';
import objectValues from 'ember-orbit/utils/object-values';
import qb from 'orbit-common/query/builder';
import {
  addRecord,
  removeRecord
} from 'orbit-common/transform/operators';

/**
 @module ember-orbit
 */

const { assert } = Ember;

export default Ember.Object.extend({
  orbitStore: null,
  keyMap: null,
  schema: null,
  cache: null,
  _identityMap: null,

  init() {
    this._super(...arguments);

    assert("`schema` must be injected onto a Store", this.schema);

    if (!this.keyMap) {
      this.keyMap = this.orbitStore ? this.orbitStore.keyMap : new KeyMap();
    }

    if (!this.orbitStore) {
      this.orbitStore = new OrbitStore({ schema: this.schema.orbitSchema, keyMap: this.keyMap });
    }

    const orbitCache = this.orbitStore.cache;

    assert("A Store's `orbitStore` must have its own `cache`", orbitCache);

    this._identityMap = IdentityMap.create({ _schema: this.schema, _orbitCache: orbitCache, _store: this });
    this.cache = Cache.create({ _orbitCache: orbitCache, _identityMap: this._identityMap });

    orbitCache.patches.subscribe(operation => this._didPatch(operation));
  },

  find(type, id) {
    if (id === undefined) {
      return this.query(qb.records(type));
    } else {
      return this.query(qb.record({type, id}));
    }
  },

  query(queryOrExpression) {
    const query = Query.from(queryOrExpression, this.orbitStore.queryBuilder);
    return this.orbitStore.query(query)
      .then(result => {
        switch(query.expression.op) {
          case 'record':  return this._identityMap.lookup(result);
          case 'records': return this._identityMap.lookupMany(objectValues(result));
          case 'filter':  return this._identityMap.lookupMany(objectValues(result));
          default:        return result;
        }
      });
  },

  update(...args) {
    return this.orbitStore.update(...args);
  },

  addRecord(properties = {}) {
    this._verifyType(properties.type);

    const record = this.schema.normalize(properties);
    return this.update(addRecord(record))
      .then(() => this._identityMap.lookup(record));
  },

  findRecord(type, id) {
    return this.query(qb.record({type, id}));
  },

  removeRecord(record) {
    return this.update(removeRecord(record));
  },

  _verifyType(type) {
    assert("`type` must be registered as a model in the store's schema", this.schema.modelFor(type));
  },

  _didPatch: function(operation) {
    // console.debug('didPatch', operation);
    const { type, id } = operation.record;
    const record = this._identityMap.lookup({ type, id });

    switch(operation.op) {
      case 'replaceAttribute': return record.propertyDidChange(operation.attribute);
      case 'replaceHasOne': return record.propertyDidChange(operation.relationship);
      case 'removeRecord': return record.disconnect();
    }
  }
});
<|endoftext|>


<commit_before>/*
Language: Haml
Requires: ruby.js
Author: Dan Allen <dan.j.allen@gmail.com>
Website: http://google.com/profiles/dan.j.allen
*/

// TODO support filter tags like :javascript, support inline HTML
function(hljs) {
  return {
    case_insensitive: true,
    contains: [
      {
        className: 'doctype',
        begin: '^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$',
        relevance: 10
      },
      {
        className: 'comment',
        // FIXME these comments should be allowed to span indented lines
        begin: '^\\s*(-#|/).*$',
        relevance: 0
      },
      {
        begin: '^\\s*(-|=|!=)(?!#)',
        starts: {
          end: '\\n',
          subLanguage: 'ruby'
        },
        relevance: 0
      },
      {
        className: 'tag',
        begin: '^\\s*%',
        contains: [
          {
            className: 'title',
            begin: '\\w+',
            relevance: 0
          },
          {
            className: 'value',
            begin: '[#\\.]\\w+',
            relevance: 0
          },
          {
            begin: '{\\s*',
            end: '\\s*}',
            excludeEnd: true,
            contains: [
              {
                //className: 'attribute',
                begin: ':\\w+\\s*=>',
                end: ',\\s+',
                returnBegin: true,
                endsWithParent: true,
                relevance: 0,
                contains: [
                  {
                    className: 'symbol',
                    begin: ':\\w+',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '"',
                    end: '"',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '\'',
                    end: '\'',
                    relevance: 0
                  },
                  {
                    begin: '\\w+',
                    relevance: 0
                  }
                ]
              },
            ],
            relevance: 0
          },
          {
            begin: '\\(\\s*',
            end: '\\s*\\)',
            excludeEnd: true,
            contains: [
              {
                //className: 'attribute',
                begin: '\\w+\\s*=',
                end: '\\s+',
                returnBegin: true,
                endsWithParent: true,
                relevance: 0,
                contains: [
                  {
                    className: 'attribute',
                    begin: '\\w+',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '"',
                    end: '"',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '\'',
                    end: '\'',
                    relevance: 0
                  },
                  {
                    begin: '\\w+',
                    relevance: 0
                  }
                ]
              },
            ],
            relevance: 0
          }
        ],
        relevance: 10
      },
      {
        className: 'bullet',
        begin: '^\\s*[=~]\\s*',
        relevance: 0
      },
      {
        begin: '#{',
        starts: {
          end: '}',
          subLanguage: 'ruby'
        },
        relevance: 0
      }
    ]
  };
}
<commit_msg>Update haml comments with = and != prefix<commit_after>/*
Language: Haml
Requires: ruby.js
Author: Dan Allen <dan.j.allen@gmail.com>
Website: http://google.com/profiles/dan.j.allen
*/

// TODO support filter tags like :javascript, support inline HTML
function(hljs) {
  return {
    case_insensitive: true,
    contains: [
      {
        className: 'doctype',
        begin: '^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$',
        relevance: 10
      },
      {
        className: 'comment',
        // FIXME these comments should be allowed to span indented lines
        begin: '^\\s*(!=#|=#|-#|/).*$',
        relevance: 0
      },
      {
        begin: '^\\s*(-|=|!=)(?!#)',
        starts: {
          end: '\\n',
          subLanguage: 'ruby'
        },
        relevance: 0
      },
      {
        className: 'tag',
        begin: '^\\s*%',
        contains: [
          {
            className: 'title',
            begin: '\\w+',
            relevance: 0
          },
          {
            className: 'value',
            begin: '[#\\.]\\w+',
            relevance: 0
          },
          {
            begin: '{\\s*',
            end: '\\s*}',
            excludeEnd: true,
            contains: [
              {
                //className: 'attribute',
                begin: ':\\w+\\s*=>',
                end: ',\\s+',
                returnBegin: true,
                endsWithParent: true,
                relevance: 0,
                contains: [
                  {
                    className: 'symbol',
                    begin: ':\\w+',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '"',
                    end: '"',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '\'',
                    end: '\'',
                    relevance: 0
                  },
                  {
                    begin: '\\w+',
                    relevance: 0
                  }
                ]
              },
            ],
            relevance: 0
          },
          {
            begin: '\\(\\s*',
            end: '\\s*\\)',
            excludeEnd: true,
            contains: [
              {
                //className: 'attribute',
                begin: '\\w+\\s*=',
                end: '\\s+',
                returnBegin: true,
                endsWithParent: true,
                relevance: 0,
                contains: [
                  {
                    className: 'attribute',
                    begin: '\\w+',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '"',
                    end: '"',
                    relevance: 0
                  },
                  {
                    className: 'string',
                    begin: '\'',
                    end: '\'',
                    relevance: 0
                  },
                  {
                    begin: '\\w+',
                    relevance: 0
                  }
                ]
              },
            ],
            relevance: 0
          }
        ],
        relevance: 10
      },
      {
        className: 'bullet',
        begin: '^\\s*[=~]\\s*',
        relevance: 0
      },
      {
        begin: '#{',
        starts: {
          end: '}',
          subLanguage: 'ruby'
        },
        relevance: 0
      }
    ]
  };
}
<|endoftext|>