<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */

/**
 * PreferenceStorage defines an interface for persisting preference data as
 * name/value pairs for a module or plugin.
 */
define(function (require, exports, module) {
    "use strict";

    var _ = require("thirdparty/lodash");

    var PreferencesManager = require("preferences/PreferencesManager");

    /**
     * @private
     * Validate JSON keys and values.
     */
    function _validateJSONPair(key, value) {
        if (typeof key === "string") {
            // validate temporary JSON
            var temp = {},
                error = null;
            temp[key] = value;

            try {
                temp = JSON.parse(JSON.stringify(temp));
            } catch (err) {
                error = err;
            }

            // set value to JSON storage if no errors occurred
            if (!error && (temp[key] !== undefined)) {
                return true;
            } else {
                console.error("Value '" + value + "' for key '" + key + "' must be a valid JSON value");
                return false;
            }
        } else {
            console.error("Preference key '" + key + "' must be a string");
            return false;
        }
    }

    /**
     * @private
     * Save to persistent storage.
     */
    function _commit() {
        PreferencesManager.savePreferences();
    }

    /**
     * Creates a new PreferenceStorage object.
     * @param {!string} clientID Unique identifier for PreferencesManager to
     *  associate this PreferenceStorage data with.
     * @param {!object} json JSON object to persist preference data.
     */
    function PreferenceStorage(clientID, json) {
        this._clientID = clientID;
        this._json = json;
    }

    /**
     * Unique clientID for this PreferenceStorage object.
     * @return {!string} clientID
     */
    PreferenceStorage.prototype.getClientID = function () {
        return this._clientID;
    };

    /**
     * Removes a preference from this PreferenceStorage object.
     * @param {!string} key A unique identifier
     */
    PreferenceStorage.prototype.remove = function (key) {
        // remove value from JSON storage
        delete this._json[key];
        _commit();
    };

    /**
     * Assigns a value for a key. Overwrites existing value if present.
     * @param {!string} key A unique identifier
     * @param {object} value A valid JSON value
     */
    PreferenceStorage.prototype.setValue = function (key, value) {
        if (_validateJSONPair(key, value)) {
            this._json[key] = value;
            _commit();
        }
    };

    /**
     * Retreive the value associated with the specified key.
     * @param {!string} key Key name to lookup.
     * @return {object} Returns the value for the key or undefined.
     */
    PreferenceStorage.prototype.getValue = function (key) {
        return this._json[key];
    };

    /**
     * Return all name-value pairs as a single JSON object.
     * @return {!object} JSON object containing name/value pairs for all keys
     *  in this PreferenceStorage object.
     */
    PreferenceStorage.prototype.getAllValues = function () {
        return JSON.parse(JSON.stringify(this._json));
    };

    /**
     * Writes name-value pairs from a JSON object as preference properties.
     * Invalid JSON values report an error and all changes are discarded.
     *
     * @param {!object} obj A JSON object with zero or more preference properties to write.
     * @param {boolean} append Defaults to false. When true, properties in the JSON object
     *  overwrite and/or append to the existing set of preference properties. When false,
     *  all existing preferences are deleted before writing new properties from the JSON object.
     */
    PreferenceStorage.prototype.setAllValues = function (obj, append) {
        var self = this,
            error = null;

        // validate all name/value pairs before committing
        _.some(obj, function (value, key) {
            try {
                _validateJSONPair(key, value);
            } catch (err) {
                // fail fast
                error = err;
                return true;
            }
        });

        // skip changes if any error is detected
        if (error) {
            console.error(error);
            return;
        }

        // delete all exiting properties if not appending
        if (!append) {
            _.forEach(this._json, function (value, key) {
                delete self._json[key];
            });
        }

        // copy properties from incoming JSON object
        _.forEach(obj, function (value, key) {
            self._json[key] = value;
        });

        _commit();
    };

    /**
     * Converts preferences to the new-style file-based preferences according to the
     * rules. (See PreferencesManager.ConvertSettings for information about the rules).
     *
     * @param {Object} rules Conversion rules.
     * @param {Array.<string>} convertedKeys List of keys that were previously converted
     *                                      (will not be reconverted)
     * @return {Promise} promise that is resolved once the conversion is done. Callbacks are given a
     *                      `complete` flag that denotes whether everything from this object
     *                      was converted (making it safe to delete entirely).
     */
    PreferenceStorage.prototype.convert = function (rules, convertedKeys) {
        var prefs = this._json,
            self,
            complete = true,
            deferred = new $.Deferred();

        if (!convertedKeys) {
            convertedKeys = [];
        }

        Object.keys(prefs).forEach(function (key) {
            if (convertedKeys.indexOf(key) > -1) {
                return;
            }

            var rule = rules[key];
            if (!rule) {
                console.warn("Preferences conversion for ", self._clientID, " has no rule for", key);
                complete = false;
            } else if (_.isString(rule)) {
                var parts = rule.split(" ");
                if (parts[0] === "user") {
                    var newKey = parts.length > 1 ? parts[1] : key;
                    PreferencesManager.set(newKey, prefs[key]);
                    convertedKeys.push(key);
                }
            } else {
                complete = false;
            }
        });

        if (convertedKeys.length > 0) {
            PreferencesManager.save().done(function () {
                _commit();
                deferred.resolve(complete, convertedKeys);
            }).fail(function (error) {
                deferred.reject(error);
            });
        } else {
            deferred.resolve(complete, convertedKeys);
        }

        return deferred.promise();
    };

    exports.PreferenceStorage = PreferenceStorage;
});<commit_msg>Define self to prevent exception, for #6607<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */

/**
 * PreferenceStorage defines an interface for persisting preference data as
 * name/value pairs for a module or plugin.
 */
define(function (require, exports, module) {
    "use strict";

    var _ = require("thirdparty/lodash");

    var PreferencesManager = require("preferences/PreferencesManager");

    /**
     * @private
     * Validate JSON keys and values.
     */
    function _validateJSONPair(key, value) {
        if (typeof key === "string") {
            // validate temporary JSON
            var temp = {},
                error = null;
            temp[key] = value;

            try {
                temp = JSON.parse(JSON.stringify(temp));
            } catch (err) {
                error = err;
            }

            // set value to JSON storage if no errors occurred
            if (!error && (temp[key] !== undefined)) {
                return true;
            } else {
                console.error("Value '" + value + "' for key '" + key + "' must be a valid JSON value");
                return false;
            }
        } else {
            console.error("Preference key '" + key + "' must be a string");
            return false;
        }
    }

    /**
     * @private
     * Save to persistent storage.
     */
    function _commit() {
        PreferencesManager.savePreferences();
    }

    /**
     * Creates a new PreferenceStorage object.
     * @param {!string} clientID Unique identifier for PreferencesManager to
     *  associate this PreferenceStorage data with.
     * @param {!object} json JSON object to persist preference data.
     */
    function PreferenceStorage(clientID, json) {
        this._clientID = clientID;
        this._json = json;
    }

    /**
     * Unique clientID for this PreferenceStorage object.
     * @return {!string} clientID
     */
    PreferenceStorage.prototype.getClientID = function () {
        return this._clientID;
    };

    /**
     * Removes a preference from this PreferenceStorage object.
     * @param {!string} key A unique identifier
     */
    PreferenceStorage.prototype.remove = function (key) {
        // remove value from JSON storage
        delete this._json[key];
        _commit();
    };

    /**
     * Assigns a value for a key. Overwrites existing value if present.
     * @param {!string} key A unique identifier
     * @param {object} value A valid JSON value
     */
    PreferenceStorage.prototype.setValue = function (key, value) {
        if (_validateJSONPair(key, value)) {
            this._json[key] = value;
            _commit();
        }
    };

    /**
     * Retreive the value associated with the specified key.
     * @param {!string} key Key name to lookup.
     * @return {object} Returns the value for the key or undefined.
     */
    PreferenceStorage.prototype.getValue = function (key) {
        return this._json[key];
    };

    /**
     * Return all name-value pairs as a single JSON object.
     * @return {!object} JSON object containing name/value pairs for all keys
     *  in this PreferenceStorage object.
     */
    PreferenceStorage.prototype.getAllValues = function () {
        return JSON.parse(JSON.stringify(this._json));
    };

    /**
     * Writes name-value pairs from a JSON object as preference properties.
     * Invalid JSON values report an error and all changes are discarded.
     *
     * @param {!object} obj A JSON object with zero or more preference properties to write.
     * @param {boolean} append Defaults to false. When true, properties in the JSON object
     *  overwrite and/or append to the existing set of preference properties. When false,
     *  all existing preferences are deleted before writing new properties from the JSON object.
     */
    PreferenceStorage.prototype.setAllValues = function (obj, append) {
        var self = this,
            error = null;

        // validate all name/value pairs before committing
        _.some(obj, function (value, key) {
            try {
                _validateJSONPair(key, value);
            } catch (err) {
                // fail fast
                error = err;
                return true;
            }
        });

        // skip changes if any error is detected
        if (error) {
            console.error(error);
            return;
        }

        // delete all exiting properties if not appending
        if (!append) {
            _.forEach(this._json, function (value, key) {
                delete self._json[key];
            });
        }

        // copy properties from incoming JSON object
        _.forEach(obj, function (value, key) {
            self._json[key] = value;
        });

        _commit();
    };

    /**
     * Converts preferences to the new-style file-based preferences according to the
     * rules. (See PreferencesManager.ConvertSettings for information about the rules).
     *
     * @param {Object} rules Conversion rules.
     * @param {Array.<string>} convertedKeys List of keys that were previously converted
     *                                      (will not be reconverted)
     * @return {Promise} promise that is resolved once the conversion is done. Callbacks are given a
     *                      `complete` flag that denotes whether everything from this object
     *                      was converted (making it safe to delete entirely).
     */
    PreferenceStorage.prototype.convert = function (rules, convertedKeys) {
        var prefs = this._json,
            self = this,
            complete = true,
            deferred = new $.Deferred();

        if (!convertedKeys) {
            convertedKeys = [];
        }

        Object.keys(prefs).forEach(function (key) {
            if (convertedKeys.indexOf(key) > -1) {
                return;
            }

            var rule = rules[key];
            if (!rule) {
                console.warn("Preferences conversion for ", self._clientID, " has no rule for", key);
                complete = false;
            } else if (_.isString(rule)) {
                var parts = rule.split(" ");
                if (parts[0] === "user") {
                    var newKey = parts.length > 1 ? parts[1] : key;
                    PreferencesManager.set(newKey, prefs[key]);
                    convertedKeys.push(key);
                }
            } else {
                complete = false;
            }
        });

        if (convertedKeys.length > 0) {
            PreferencesManager.save().done(function () {
                _commit();
                deferred.resolve(complete, convertedKeys);
            }).fail(function (error) {
                deferred.reject(error);
            });
        } else {
            deferred.resolve(complete, convertedKeys);
        }

        return deferred.promise();
    };

    exports.PreferenceStorage = PreferenceStorage;
});<|endoftext|>


<commit_before>const http = require('http');
const url = require('url');
const util = require('util');
const ProjectionCommandFailedError = require('../errors/projectionCommandFailedError');

const HTTP_OK = 200;
const HTTP_CREATED = 201;

function safeParseJson(json) {
  try {
    return JSON.parse(json);
  } catch(e) {
    return null;
  }
}

function ProjectionsClient(log, operationTimeout) {
  this._log = log;
  this._operationTimeout = operationTimeout;
}

ProjectionsClient.prototype.enable = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/enable', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.disable = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/disable', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.abort = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/abort', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.createOneTime = function(httpEndPoint, query, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/onetime?type=JS', query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.createTransient = function(httpEndPoint, name, query, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/transient?name=' + name + '&type=JS', query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.createContinuous = function(httpEndPoint, name, query, trackEmittedStreams, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/continuous?name=' + name + '&type=JS&emit=1&trackemittedstreams=' + trackEmittedStreams, query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.listAll = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/any', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.listOneTime = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/onetime', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.listContinuous = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/continuous', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.getStatus = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getState = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/state', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getPartitionState = function(httpEndPoint, name, partitionId, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/state?partition=' + partitionId, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getResult = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/result', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getPartitionResult = function(httpEndPoint, name, partitionId, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/result?partition=' + partitionId, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getStatistics = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/statistics', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getQuery = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/query', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.updateQuery = function(httpEndPoint, name, query, userCredentials) {
  return this.sendPut(httpEndPoint + '/projection/' + name + '/query?type=JS', query, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.delete = function(httpEndPoint, name, deleteEmittedStreams, deleteStateStream, deleteCheckpointStream, userCredentials) {
  return this.sendDelete(httpEndPoint + '/projection/' + name + '?deleteStateStream=' + stateStream + '&deleteCheckpointStream' + checkpointStream + '&deleteEmittedStreams=' + deleteEmittedStreams, '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.request = function(method, _url, data, userCredentials, expectedCode) {
  const options = url.parse(_url);
  options.method = method;
  if (userCredentials) {
    options.auth = [userCredentials.username, userCredentials.password].join(':');
  }
  var self = this;
  return new Promise(function (resolve, reject) {
    const timeout = setTimeout(function () {
      reject(new Error(util.format('Request timed out for %s on %s', method, _url)))
    }, self._operationTimeout);
    const req = http.request(options, function (res) {
      const hasExpectedCode = res.statusCode === expectedCode;
      var result = '';
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        result += chunk;
      });
      res.on('end', function () {
        if (hasExpectedCode) {
          clearTimeout(timeout);
          resolve(result);
        } else {
          clearTimeout(timeout);
          reject(new ProjectionCommandFailedError(
            res.statusCode,
            util.format('Server returned %d (%s) for %s on %s', res.statusCode, res.statusMessage, method, _url)
          ));
        }
      });
    });
    req.on('error', reject);
    if (data) {
      req.setHeader('Content-Length', data.length);
      req.setHeader('Content-Type', 'application/json');
      req.write(data);
    }
    req.end();
  });
};

function voidResult() {}

ProjectionsClient.prototype.sendGet = function(_url, userCredentials, expectedCode) {
  return this.request('GET', _url, null, userCredentials, expectedCode);
};

ProjectionsClient.prototype.sendPost = function(_url, data, userCredentials, expectedCode) {
  return this.request('POST', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

ProjectionsClient.prototype.sendPut = function(_url, data, userCredentials, expectedCode) {
  return this.request('PUT', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

ProjectionsClient.prototype.sendDelete = function(_url, data, userCredentials, expectedCode) {
  return this.request('DELETE', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

module.exports = ProjectionsClient;
<commit_msg>Fix incorrect variables used after undefined removal<commit_after>const http = require('http');
const url = require('url');
const util = require('util');
const ProjectionCommandFailedError = require('../errors/projectionCommandFailedError');

const HTTP_OK = 200;
const HTTP_CREATED = 201;

function safeParseJson(json) {
  try {
    return JSON.parse(json);
  } catch(e) {
    return null;
  }
}

function ProjectionsClient(log, operationTimeout) {
  this._log = log;
  this._operationTimeout = operationTimeout;
}

ProjectionsClient.prototype.enable = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/enable', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.disable = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/disable', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.abort = function(httpEndPoint, name, userCredentials) {
  return this.sendPost(httpEndPoint + '/projection/' + name + '/command/abort', '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.createOneTime = function(httpEndPoint, query, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/onetime?type=JS', query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.createTransient = function(httpEndPoint, name, query, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/transient?name=' + name + '&type=JS', query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.createContinuous = function(httpEndPoint, name, query, trackEmittedStreams, userCredentials) {
  return this.sendPost(httpEndPoint + '/projections/continuous?name=' + name + '&type=JS&emit=1&trackemittedstreams=' + trackEmittedStreams, query, userCredentials, HTTP_CREATED);
};

ProjectionsClient.prototype.listAll = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/any', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.listOneTime = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/onetime', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.listContinuous = function(httpEndPoint, userCredentials) {
  return this.sendGet(httpEndPoint + '/projections/continuous', userCredentials, HTTP_OK)
    .then(function (json) {
      var r = safeParseJson(json);
      if (r && r.projections) return r.projections;
      return null;
    });
};

ProjectionsClient.prototype.getStatus = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getState = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/state', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getPartitionState = function(httpEndPoint, name, partitionId, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/state?partition=' + partitionId, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getResult = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/result', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getPartitionResult = function(httpEndPoint, name, partitionId, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/result?partition=' + partitionId, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getStatistics = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/statistics', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.getQuery = function(httpEndPoint, name, userCredentials) {
  return this.sendGet(httpEndPoint + '/projection/' + name + '/query', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.updateQuery = function(httpEndPoint, name, query, userCredentials) {
  return this.sendPut(httpEndPoint + '/projection/' + name + '/query?type=JS', query, userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.delete = function(httpEndPoint, name, deleteEmittedStreams, deleteStateStream, deleteCheckpointStream, userCredentials) {
  return this.sendDelete(httpEndPoint + '/projection/' + name + '?deleteStateStream=' + deleteStateStream + '&deleteCheckpointStream' + deleteCheckpointStream + '&deleteEmittedStreams=' + deleteEmittedStreams, '', userCredentials, HTTP_OK);
};

ProjectionsClient.prototype.request = function(method, _url, data, userCredentials, expectedCode) {
  const options = url.parse(_url);
  options.method = method;
  if (userCredentials) {
    options.auth = [userCredentials.username, userCredentials.password].join(':');
  }
  var self = this;
  return new Promise(function (resolve, reject) {
    const timeout = setTimeout(function () {
      reject(new Error(util.format('Request timed out for %s on %s', method, _url)))
    }, self._operationTimeout);
    const req = http.request(options, function (res) {
      const hasExpectedCode = res.statusCode === expectedCode;
      var result = '';
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        result += chunk;
      });
      res.on('end', function () {
        if (hasExpectedCode) {
          clearTimeout(timeout);
          resolve(result);
        } else {
          clearTimeout(timeout);
          reject(new ProjectionCommandFailedError(
            res.statusCode,
            util.format('Server returned %d (%s) for %s on %s', res.statusCode, res.statusMessage, method, _url)
          ));
        }
      });
    });
    req.on('error', reject);
    if (data) {
      req.setHeader('Content-Length', data.length);
      req.setHeader('Content-Type', 'application/json');
      req.write(data);
    }
    req.end();
  });
};

function voidResult() {}

ProjectionsClient.prototype.sendGet = function(_url, userCredentials, expectedCode) {
  return this.request('GET', _url, null, userCredentials, expectedCode);
};

ProjectionsClient.prototype.sendPost = function(_url, data, userCredentials, expectedCode) {
  return this.request('POST', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

ProjectionsClient.prototype.sendPut = function(_url, data, userCredentials, expectedCode) {
  return this.request('PUT', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

ProjectionsClient.prototype.sendDelete = function(_url, data, userCredentials, expectedCode) {
  return this.request('DELETE', _url, data, userCredentials, expectedCode)
    .then(voidResult);
};

module.exports = ProjectionsClient;
<|endoftext|>


<commit_before>define(['durandal/app', 'knockout', 'mods/player', 'mods/format'], function (app, ko, player, format) {

    var timeline = undefined;
    var state = ko.observable(0);
    var ready = false;
    var data = undefined;
    var timelines = [];
    var datas = [];
    var cursorCentered = ko.observable(false);
    var onTimeChangeActive = false;

    var duration = ko.observable(0);
    var start = ko.observable(0);
    var end = ko.observable(0);

    var pos = 0;

    var loop_annotation = null;

    function initTimeline() {
        // Create and populate a data table.
        data = new google.visualization.DataTable();

        data.addColumn('datetime', 'start');
        data.addColumn('datetime', 'end');
        data.addColumn('string', 'content');
        data.addColumn('boolean', 'editable');
        data.addColumn('string', 'id');
        //data.addColumn('string', 'group');

        var date = new Date(2000, 1, 1, 0, 0, 0, 0);
        start(date.getTime());
        end(start() + duration());

        var options = {
            width: "100%",
            //height: "200px",
            //minHeight: "200px",
            editable: true,
            //style: "box",
            showCustomTime: true,
            cluster: true,
            axisOnTop: true,
            //dragAreaWidth: 20,
            showMajorLabels: true,
            //groupsOnRight: true,
            enableKeys: true,
            showNavigation: true,
            showButtonNew: false,
            animate: true,
            animateZoom: true,
            min: start(),
            max: end()
        };

        $("#timelinescroll").css("opacity", "1");
        $("#timelinescroll").scroll(ontimelinescrolling);

        // Instantiate our timeline object.
        $("#timelines").append('

');
        timeline = new links.Timeline(document.getElementById('timeline1'));

        // Add event listeners
        google.visualization.events.addListener(timeline, 'timechange', onTimeChange);
        google.visualization.events.addListener(timeline, 'timechanged', onTimeChanged);

        google.visualization.events.addListener(timeline, 'rangechange', onRangeChange);

        // Draw our timeline with the created data and options
        timeline.draw(data, options);

        timeline.setVisibleChartRange(start(), end());
        timeline.setCustomTime(start());

        // add, change, edit, delete, select
        //google.visualization.events.addListener(timeline, 'select', onannotationselect);
        google.visualization.events.addListener(timeline, 'edit', onannotationedit); // NOT FIRED!
        google.visualization.events.addListener(timeline, 'change', onannotationchange);
        //google.visualization.events.addListener(timeline, 'add', onannotationadd);

        google.visualization.events.addListener(timeline, 'dblclick', ondblclick);
        google.visualization.events.addListener(timeline, 'requestadd', onrequestadd);

        google.visualization.events.addListener(timeline, 'select', onselect);

        google.visualization.events.addListener(timeline, 'play', onplay);
        google.visualization.events.addListener(timeline, 'loop', onloop);
        google.visualization.events.addListener(timeline, 'viewmetadata', onviewmetadata);
        google.visualization.events.addListener(timeline, 'editmetadata', oneditmetadata);

        ready = true;
        state(1);
    }

    function onselect() {
    }

    function onplay() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                var s = format.getTimeStringFromDate(dat.start);
                s = format.getSecondsFromString(s);
                player.setProgramTimePos(s);
                player.play();
                //var e = format.getSecondsFromString(ann.endtime());
                //player.setProgramTimeLoop(s, e);
                //player.playLoop();
            }
        }

    }

    function onloop() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                if (loop_annotation !== null && loop_annotation.Id === dat.Id) {
                    // Cancel loop
                    loop_annotation = null;
                    player.clearLoop();
                    timeline.setLoop(null);
                } else {
                    // Do loop
                    loop_annotation = dat;
                    var s = format.getTimeStringFromDate(dat.start);
                    s = format.getSecondsFromString(s);
                    var e = format.getTimeStringFromDate(dat.end);
                    e = format.getSecondsFromString(e);
                    player.setProgramTimeLoop(s, e);
                    // Only play if cursor is outside annotation
                    if(!player.isCursorInsideLoop())
                        player.playLoop();
                    timeline.setLoop(dat.id);
                }

            }
        }
        //window.scrollTo(0, 0);
        //var s = format.getSecondsFromString(ann.starttime());
        //var e = format.getSecondsFromString(ann.endtime());
        //player.setProgramTimeLoop(s, e);
        //player.playLoop();
    }

    function onviewmetadata() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                app.trigger('annotation:metadataview', dat);
            }
        }
    }

    function oneditmetadata() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                app.trigger('metadata:edit', dat);
            }
        }
    }

    function onrequestadd() {
        app.trigger("annotation:add", {});
    }

    function ondblclick() {
        //var sel = timeline.getSelection();
        //if (sel.length) {
        //    if (sel[0].row != undefined) {
        //        var row = sel[0].row;
        //        var dat = timeline.getItem(row);
        //        app.trigger('metadata:edit', dat);
        //    }
        //}
    }

    function onannotationadd() {

        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                var amd = {
                    GUID: "02120d71-c88b-7523-273b-6790bf0b77a5",
                    MetadataSchemaGUID: "50ad46c4-eaf1-42f6-9361-3f6b56c5f320",
                    EditingUserGUID: "7d2db0e4-8cfd-4ecf-92e8-3eba34914011",
                    EditingUser: "Thomas Lynge",
                    DateCreated: "05-04-2013 09:07:15",
                    LanguageCode: "da",
                    StartTime: format.getTimeStringFromDate(dat.start),
                    EndTime: format.getTimeStringFromDate(dat.end),
                    Title: dat.content
                };

                var annedit = new metadatafac.MetadataView();
                annedit.setview("annotationedit", amd);
                metadataEditors.push(annedit);
            }
        }
    }

    function onannotationselect() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                //timeline.changeItem(row, { start: new Date(dat.start.getTime() - 1000) });

                //var evobj = timeline.getItemAndIndexByID("02120d71-c88b-7523-273b-6790bf0b77a5");
                //timeline.changeItem(evobj.index, { end: new Date(playertime_end) })

            }
        }
    }

    function onannotationedit() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                updateAnnotationLoop(dat);
            }
        }
    }

    function onannotationchange() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                updateAnnotationLoop(dat);
                app.trigger('metadata:changed_timeline', { data: dat });
            }
        }
    }

    function onTimeChange(event) {
        onTimeChangeActive = true;
    }

    function onTimeChanged(event) {
        var timediff = event.time - start();
        player.setProgramTimePos(timediff / 1000);
        onTimeChangeActive = false;
    }

    var ontimelinescrollingdisable = false;
    function ontimelinescrolling(e) {
        if (ontimelinescrollingdisable) {
            ontimelinescrollingdisable = false;
            return;
        }

        cursorCentered(false);

        var totalpixel = $("#timelinescrollcontent").width();
        var rangeobj = timeline.getVisibleChartRange();
        var rangevalue = rangeobj.end - rangeobj.start;

        var pixelpervalue = duration() / totalpixel;

        var scrollpos = $("#timelinescroll").scrollLeft();
        var res = totalpixel / (scrollpos);

        var starttime = start() + duration() / res;
        timeline.setVisibleChartRange(starttime, starttime + rangevalue);
    }

    function onRangeChange(event) {
        cursorCentered(false);
        var totalvalue = end() - start();
        var rangevalue = event.end - event.start;
        var totalpixel = $("#timelinescroll").width();

        var conwdt = (totalvalue / rangevalue) * totalpixel;

        $("#timelinescrollcontent").width(conwdt);

        var startdiff = event.start - start();

        ontimelinescrollingdisable = true;
        if (startdiff == 0)
            $("#timelinescroll").scrollLeft(0);
        else
            $("#timelinescroll").scrollLeft(conwdt / (totalvalue / startdiff));

        var range = timeline.getVisibleChartRange();
        //timeline2.setVisibleChartRange(range.start, range.end);

        return;

        var update = false;
        var ts = event.start;
        var te = event.end;
        if (event.start < playertime_start) {
            update = true;
            ts = playertime_start;
        }
        if (event.end > playertime_end) {
            update = true;
            te = playertime_end;
        }

        if (update)
            timeline.setVisibleChartRange(ts, te);

        //var range = timeline.getVisibleChartRange();
        //timeline2.setVisibleChartRange(range.start, range.end);
    }

    function getTimelineDate(d, millisecoffset) {
        var dt = new Date(d);
        dt.setMilliseconds(dt.getMilliseconds() + millisecoffset);
        return dt;
    }

    function isReady() {
        return ready;
    }

    function addData(datarows) {
        data.addRows(datarows);
        timeline.redraw();
    }

    function getAnnotation(guid) {

        var r = data.xf;
        for (var i = 0; i < r.length; i++) {
            if (r[i].c[4].v == guid) {
                return r[i].c;
            }
        }

        return null;
    }

    function updateAnnotationLoop(ann) {
        if (loop_annotation && ann) {
            if (loop_annotation.Id === ann.Id) {
                var s = format.getTimeStringFromDate(ann.start);
                s = format.getSecondsFromString(s);
                var e = format.getTimeStringFromDate(ann.end);
                e = format.getSecondsFromString(e);
                player.setProgramTimeLoop(s, e);
            }
        }
    }

    var prepos = 0;
    var mainloop = function () {

        if (!ready)
            return;

        //var position = Math.round(pos * 100) / 100;
        var position = pos; //Math.round(pos);
        if (prepos == position)
            return;

        prepos = position;
        timeline.setCustomTime(start() + position * 1000); // Convert to milliseconds
        //var r = timeline.getVisibleChartRange();
        //playerdebug(timestr(r.start) + " - " + timestr(r.end));

        if (cursorCentered()) {
            timeline.centerTimeline();
        }

    };

    var animFrame = window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            null;

    if (animFrame !== null) {
        var recursiveAnim = function () {
            mainloop();
            animFrame(recursiveAnim);
        };

        // start the mainloop
        animFrame(recursiveAnim);
    } else {
        var ONE_FRAME_TIME = 1000.0 / 60.0;
        setInterval(mainloop, ONE_FRAME_TIME);
    }

    return {
        state: state,
        start: start,
        end: end,
        // dur = duration in seconds
        init: function (dur) {
            duration(dur * 1000); // Convert to milliseconds
            google.load("visualization", "1", { "callback": initTimeline });
        },
        // setTime: time = Seconds
        setPosition: function (position) {
            if (!onTimeChangeActive) {
                pos = position;
            }
        },
        isReady: isReady,
        addData: addData,
        redraw: function () {
            if (timeline)
                timeline.redraw();
        },
        clearData: function () {
            data.removeRows(0, data.getNumberOfRows());
            timeline.redraw();
        },
        getAnnotation: getAnnotation,
        editItem: function (id) {
            timeline.editItem(id);
        },
        getSelection: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    return dat;
                }
            }
            return undefined;
        },
        changeItem: function (start, end, content) {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);

                    dat.start = start;
                    dat.end = end;
                    dat.content = content;

                    timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                    updateAnnotationLoop(dat);
                }
            }
        },
        selectItemById: function (id) {
            timeline.selectItemById(id);
        },
        unselectItem: function () {
            timeline.unselectItem();
            timeline.redraw();
        },
        addItemAtCursor: function (id) {
            timeline.addItemAtCursor(id);
        },
        deleteItemByID: function (id) {
            timeline.deleteItemByID(id);
        },
        cursorCentered: cursorCentered,
        setAnnotationStartToCursor: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    dat.start = timeline.customTime;
                    updateAnnotationLoop(dat);
                    if (dat.end > dat.start) {
                        timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                        updateAnnotationLoop(dat);
                    }
                }
            }
        },
        setAnnotationEndToCursor: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    dat.end = timeline.customTime;
                    if (dat.end > dat.start) {
                        timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                        updateAnnotationLoop(dat);
                    }
                }
            }
        },
        loopAnnotation: function (guid) {
            timeline.selectItemById(guid);
            onloop();
            setTimeout(function () {
                timeline.selectItemById(guid);
            }, 100);

        }
    };
});
<commit_msg>Deeplink select item refined.<commit_after>define(['durandal/app', 'knockout', 'mods/player', 'mods/format'], function (app, ko, player, format) {

    var timeline = undefined;
    var state = ko.observable(0);
    var ready = false;
    var data = undefined;
    var timelines = [];
    var datas = [];
    var cursorCentered = ko.observable(false);
    var onTimeChangeActive = false;

    var duration = ko.observable(0);
    var start = ko.observable(0);
    var end = ko.observable(0);

    var pos = 0;

    var loop_annotation = null;

    function initTimeline() {
        // Create and populate a data table.
        data = new google.visualization.DataTable();

        data.addColumn('datetime', 'start');
        data.addColumn('datetime', 'end');
        data.addColumn('string', 'content');
        data.addColumn('boolean', 'editable');
        data.addColumn('string', 'id');
        //data.addColumn('string', 'group');

        var date = new Date(2000, 1, 1, 0, 0, 0, 0);
        start(date.getTime());
        end(start() + duration());

        var options = {
            width: "100%",
            //height: "200px",
            //minHeight: "200px",
            editable: true,
            //style: "box",
            showCustomTime: true,
            cluster: true,
            axisOnTop: true,
            //dragAreaWidth: 20,
            showMajorLabels: true,
            //groupsOnRight: true,
            enableKeys: true,
            showNavigation: true,
            showButtonNew: false,
            animate: true,
            animateZoom: true,
            min: start(),
            max: end()
        };

        $("#timelinescroll").css("opacity", "1");
        $("#timelinescroll").scroll(ontimelinescrolling);

        // Instantiate our timeline object.
        $("#timelines").append('

');
        timeline = new links.Timeline(document.getElementById('timeline1'));

        // Add event listeners
        google.visualization.events.addListener(timeline, 'timechange', onTimeChange);
        google.visualization.events.addListener(timeline, 'timechanged', onTimeChanged);

        google.visualization.events.addListener(timeline, 'rangechange', onRangeChange);

        // Draw our timeline with the created data and options
        timeline.draw(data, options);

        timeline.setVisibleChartRange(start(), end());
        timeline.setCustomTime(start());

        // add, change, edit, delete, select
        //google.visualization.events.addListener(timeline, 'select', onannotationselect);
        google.visualization.events.addListener(timeline, 'edit', onannotationedit); // NOT FIRED!
        google.visualization.events.addListener(timeline, 'change', onannotationchange);
        //google.visualization.events.addListener(timeline, 'add', onannotationadd);

        google.visualization.events.addListener(timeline, 'dblclick', ondblclick);
        google.visualization.events.addListener(timeline, 'requestadd', onrequestadd);

        google.visualization.events.addListener(timeline, 'select', onselect);

        google.visualization.events.addListener(timeline, 'play', onplay);
        google.visualization.events.addListener(timeline, 'loop', onloop);
        google.visualization.events.addListener(timeline, 'viewmetadata', onviewmetadata);
        google.visualization.events.addListener(timeline, 'editmetadata', oneditmetadata);

        ready = true;
        state(1);
    }

    function onselect() {
    }

    function onplay() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                var s = format.getTimeStringFromDate(dat.start);
                s = format.getSecondsFromString(s);
                player.setProgramTimePos(s);
                player.play();
                //var e = format.getSecondsFromString(ann.endtime());
                //player.setProgramTimeLoop(s, e);
                //player.playLoop();
            }
        }

    }

    function onloop() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                if (loop_annotation !== null && loop_annotation.Id === dat.Id) {
                    // Cancel loop
                    loop_annotation = null;
                    player.clearLoop();
                    timeline.setLoop(null);
                } else {
                    // Do loop
                    loop_annotation = dat;
                    var s = format.getTimeStringFromDate(dat.start);
                    s = format.getSecondsFromString(s);
                    var e = format.getTimeStringFromDate(dat.end);
                    e = format.getSecondsFromString(e);
                    player.setProgramTimeLoop(s, e);
                    // Only play if cursor is outside annotation
                    if(!player.isCursorInsideLoop())
                        player.playLoop();
                    timeline.setLoop(dat.id);
                }

            }
        }
        //window.scrollTo(0, 0);
        //var s = format.getSecondsFromString(ann.starttime());
        //var e = format.getSecondsFromString(ann.endtime());
        //player.setProgramTimeLoop(s, e);
        //player.playLoop();
    }

    function onviewmetadata() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                app.trigger('annotation:metadataview', dat);
            }
        }
    }

    function oneditmetadata() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                app.trigger('metadata:edit', dat);
            }
        }
    }

    function onrequestadd() {
        app.trigger("annotation:add", {});
    }

    function ondblclick() {
        //var sel = timeline.getSelection();
        //if (sel.length) {
        //    if (sel[0].row != undefined) {
        //        var row = sel[0].row;
        //        var dat = timeline.getItem(row);
        //        app.trigger('metadata:edit', dat);
        //    }
        //}
    }

    function onannotationadd() {

        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);

                var amd = {
                    GUID: "02120d71-c88b-7523-273b-6790bf0b77a5",
                    MetadataSchemaGUID: "50ad46c4-eaf1-42f6-9361-3f6b56c5f320",
                    EditingUserGUID: "7d2db0e4-8cfd-4ecf-92e8-3eba34914011",
                    EditingUser: "Thomas Lynge",
                    DateCreated: "05-04-2013 09:07:15",
                    LanguageCode: "da",
                    StartTime: format.getTimeStringFromDate(dat.start),
                    EndTime: format.getTimeStringFromDate(dat.end),
                    Title: dat.content
                };

                var annedit = new metadatafac.MetadataView();
                annedit.setview("annotationedit", amd);
                metadataEditors.push(annedit);
            }
        }
    }

    function onannotationselect() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                //timeline.changeItem(row, { start: new Date(dat.start.getTime() - 1000) });

                //var evobj = timeline.getItemAndIndexByID("02120d71-c88b-7523-273b-6790bf0b77a5");
                //timeline.changeItem(evobj.index, { end: new Date(playertime_end) })

            }
        }
    }

    function onannotationedit() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                updateAnnotationLoop(dat);
            }
        }
    }

    function onannotationchange() {
        var sel = timeline.getSelection();
        if (sel.length) {
            if (sel[0].row != undefined) {
                var row = sel[0].row;
                var dat = timeline.getItem(row);
                updateAnnotationLoop(dat);
                app.trigger('metadata:changed_timeline', { data: dat });
            }
        }
    }

    function onTimeChange(event) {
        onTimeChangeActive = true;
    }

    function onTimeChanged(event) {
        var timediff = event.time - start();
        player.setProgramTimePos(timediff / 1000);
        onTimeChangeActive = false;
    }

    var ontimelinescrollingdisable = false;
    function ontimelinescrolling(e) {
        if (ontimelinescrollingdisable) {
            ontimelinescrollingdisable = false;
            return;
        }

        cursorCentered(false);

        var totalpixel = $("#timelinescrollcontent").width();
        var rangeobj = timeline.getVisibleChartRange();
        var rangevalue = rangeobj.end - rangeobj.start;

        var pixelpervalue = duration() / totalpixel;

        var scrollpos = $("#timelinescroll").scrollLeft();
        var res = totalpixel / (scrollpos);

        var starttime = start() + duration() / res;
        timeline.setVisibleChartRange(starttime, starttime + rangevalue);
    }

    function onRangeChange(event) {
        cursorCentered(false);
        var totalvalue = end() - start();
        var rangevalue = event.end - event.start;
        var totalpixel = $("#timelinescroll").width();

        var conwdt = (totalvalue / rangevalue) * totalpixel;

        $("#timelinescrollcontent").width(conwdt);

        var startdiff = event.start - start();

        ontimelinescrollingdisable = true;
        if (startdiff == 0)
            $("#timelinescroll").scrollLeft(0);
        else
            $("#timelinescroll").scrollLeft(conwdt / (totalvalue / startdiff));

        var range = timeline.getVisibleChartRange();
        //timeline2.setVisibleChartRange(range.start, range.end);

        return;

        var update = false;
        var ts = event.start;
        var te = event.end;
        if (event.start < playertime_start) {
            update = true;
            ts = playertime_start;
        }
        if (event.end > playertime_end) {
            update = true;
            te = playertime_end;
        }

        if (update)
            timeline.setVisibleChartRange(ts, te);

        //var range = timeline.getVisibleChartRange();
        //timeline2.setVisibleChartRange(range.start, range.end);
    }

    function getTimelineDate(d, millisecoffset) {
        var dt = new Date(d);
        dt.setMilliseconds(dt.getMilliseconds() + millisecoffset);
        return dt;
    }

    function isReady() {
        return ready;
    }

    function addData(datarows) {
        data.addRows(datarows);
        timeline.redraw();
    }

    function getAnnotation(guid) {

        var r = data.xf;
        for (var i = 0; i < r.length; i++) {
            if (r[i].c[4].v == guid) {
                return r[i].c;
            }
        }

        return null;
    }

    function updateAnnotationLoop(ann) {
        if (loop_annotation && ann) {
            if (loop_annotation.Id === ann.Id) {
                var s = format.getTimeStringFromDate(ann.start);
                s = format.getSecondsFromString(s);
                var e = format.getTimeStringFromDate(ann.end);
                e = format.getSecondsFromString(e);
                player.setProgramTimeLoop(s, e);
            }
        }
    }

    var prepos = 0;
    var mainloop = function () {

        if (!ready)
            return;

        //var position = Math.round(pos * 100) / 100;
        var position = pos; //Math.round(pos);
        if (prepos == position)
            return;

        prepos = position;
        timeline.setCustomTime(start() + position * 1000); // Convert to milliseconds
        //var r = timeline.getVisibleChartRange();
        //playerdebug(timestr(r.start) + " - " + timestr(r.end));

        if (cursorCentered()) {
            timeline.centerTimeline();
        }

    };

    var animFrame = window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            null;

    if (animFrame !== null) {
        var recursiveAnim = function () {
            mainloop();
            animFrame(recursiveAnim);
        };

        // start the mainloop
        animFrame(recursiveAnim);
    } else {
        var ONE_FRAME_TIME = 1000.0 / 60.0;
        setInterval(mainloop, ONE_FRAME_TIME);
    }

    return {
        state: state,
        start: start,
        end: end,
        // dur = duration in seconds
        init: function (dur) {
            duration(dur * 1000); // Convert to milliseconds
            google.load("visualization", "1", { "callback": initTimeline });
        },
        // setTime: time = Seconds
        setPosition: function (position) {
            if (!onTimeChangeActive) {
                pos = position;
            }
        },
        isReady: isReady,
        addData: addData,
        redraw: function () {
            if (timeline)
                timeline.redraw();
        },
        clearData: function () {
            data.removeRows(0, data.getNumberOfRows());
            timeline.redraw();
        },
        getAnnotation: getAnnotation,
        editItem: function (id) {
            timeline.editItem(id);
        },
        getSelection: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    return dat;
                }
            }
            return undefined;
        },
        changeItem: function (start, end, content) {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);

                    dat.start = start;
                    dat.end = end;
                    dat.content = content;

                    timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                    updateAnnotationLoop(dat);
                }
            }
        },
        selectItemById: function (id) {
            timeline.selectItemById(id);
        },
        unselectItem: function () {
            timeline.unselectItem();
            timeline.redraw();
        },
        addItemAtCursor: function (id) {
            timeline.addItemAtCursor(id);
        },
        deleteItemByID: function (id) {
            timeline.deleteItemByID(id);
        },
        cursorCentered: cursorCentered,
        setAnnotationStartToCursor: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    dat.start = timeline.customTime;
                    updateAnnotationLoop(dat);
                    if (dat.end > dat.start) {
                        timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                        updateAnnotationLoop(dat);
                    }
                }
            }
        },
        setAnnotationEndToCursor: function () {
            var sel = timeline.getSelection();
            if (sel.length) {
                if (sel[0].row != undefined) {
                    var row = sel[0].row;
                    var dat = timeline.getItem(row);
                    dat.end = timeline.customTime;
                    if (dat.end > dat.start) {
                        timeline.changeItem(row, { start: dat.start, end: dat.end, content: dat.content });
                        updateAnnotationLoop(dat);
                    }
                }
            }
        },
        loopAnnotation: function (guid) {
            timeline.selectItemById(guid);
            onloop();
            setTimeout(function () {
                timeline.selectItemById(guid);
            }, 500);

        }
    };
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Router, Route } from 'react-router-dom';

import webviewHandler from '../../lib/webview-handler';
import history from '../../history';
import { updateIconBadge } from './actions';

import AddAccount from '../AddAccount';
import Wrapper from '../../components/Wrapper';
import Sidebar from '../Sidebar';
import Settings from '../Settings';
import MailBox from '../MailBox';

class App extends React.Component {
  propTypes = {
    onMount: PropTypes.func.isRequired,
  };

  state = {
    webviewReady: false,
  };

  componentDidMount() {
    this.props.onMount();
  }

  setWebviewContainerElem(elem) {
    if (webviewHandler.container) return;
    webviewHandler.attachTo(elem);

    this.setState({
      webviewReady: true,
    });
  }

  render() {
    return (
      <Router history={history}>
        <Wrapper>
          <Sidebar />

          <Route path="/settings" component={Settings} />
          <Route path="/add-account" component={AddAccount} />
          <Route
            path="/mailbox/:username"
            render={props => this.state.webviewReady && <MailBox
              webviewHandler={webviewHandler}
              {...props.match.params}
            />}
          />

        </Wrapper>
      </Router>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  onMount: () => dispatch(updateIconBadge()),
});

export default connect(
  () => ({}),
  mapDispatchToProps,
)(App);
<commit_msg>feat(app): app icon badge<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Router, Route } from 'react-router-dom';

import webviewHandler from '../../lib/webview-handler';
import history from '../../history';
import { updateIconBadge } from './actions';

import AddAccount from '../AddAccount';
import Wrapper from '../../components/Wrapper';
import Sidebar from '../Sidebar';
import Settings from '../Settings';
import MailBox from '../MailBox';

class App extends React.Component {
  static propTypes = {
    onMount: PropTypes.func.isRequired,
  };

  state = {
    webviewReady: false,
  };

  componentDidMount() {
    this.props.onMount();
  }

  setWebviewContainerElem(elem) {
    if (webviewHandler.container) return;
    webviewHandler.attachTo(elem);

    this.setState({
      webviewReady: true,
    });
  }

  render() {
    return (
      <Router history={history}>
        <Wrapper>
          <Sidebar />

          <Route path="/settings" component={Settings} />
          <Route path="/add-account" component={AddAccount} />
          <Route
            path="/mailbox/:username"
            render={props => this.state.webviewReady && <MailBox
              webviewHandler={webviewHandler}
              {...props.match.params}
            />}
          />

        </Wrapper>
      </Router>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  onMount: () => dispatch(updateIconBadge()),
});

export default connect(
  () => ({}),
  mapDispatchToProps,
)(App);
<|endoftext|>


<commit_before>var constants = require('constants'),
    express = require('express'),
    http = require('http'),
    https = require('https'),
    path = require('path'),
    fs = require('fs'),
    morgan = require('morgan'),
    errorhandler = require('errorhandler'),
    modRewrite = require('connect-modrewrite'),
    timeout = require('connect-timeout');

var config;

try {
    // this should exist in prod environment. no need to create this file in dev as it will use the fallback (see catch)
    config = require('/etc/trafficops/conf/config');
}
catch(e) {
    // this is used for dev environment
    config = require('../conf/config');
}

var logStream = fs.createWriteStream(config.log.stream, { flags: 'a' });
var useSSL = config.useSSL;

// Disable for self-signed certs in dev/test
process.env.NODE_TLS_REJECT_UNAUTHORIZED = config.reject_unauthorized;

var app = express();
// Add a handler to inspect the req.secure flag (see
// http://expressjs.com/api#req.secure). This allows us
// to know whether the request was via http or https.
app.all ("/*", function (req, res, next) {
    if (useSSL && !req.secure) {
        var headersHost = req.headers.host.split(':');
        var httpsUrl = 'https://' + headersHost[0] + ':' +  config.sslPort + req.url;
        // request was via http, so redirect to https
        res.redirect(httpsUrl);
    } else {
        next();
    }
});

app.use(modRewrite([
        '^/api/(.*?)\\?(.*)$ ' + config.api.base_url + '/api/$1?$2&api_key=' + config.api.key + ' [P]', // match /api/{version}/foos?active=true and replace with api.base_url/api/{version}/foos?active=true&api_key=api.key
        '^/api/(.*)$ ' + config.api.base_url + '/api/$1?api_key=' + config.api.key + ' [P]' // match /api/{version}/foos and replace with api.base_url/api/{version}/foos?api_key=api.key
]));
app.use(express.static(config.files.static));
app.use(morgan('combined', {
    stream: logStream,
    skip: function (req, res) { return res.statusCode < 400 }
}));
app.use(errorhandler());
app.use(timeout(config.timeout));

if (app.get('env') === 'dev') {
    app.use(require('connect-livereload')({
        port: 35728,
        excludeList: ['.woff', '.flv']
    }));
} else {
    app.set('env', "production");
}

// Enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable('trust proxy');

// Startup HTTP Server
var httpServer = http.createServer(app);
httpServer.listen(config.port);

if (useSSL) {
    //
    // Supply `SSL_OP_NO_SSLv3` constant as secureOption to disable SSLv3
    // from the list of supported protocols that SSLv23_method supports.
    //
    var sslOptions = {};
    sslOptions['secureOptions'] = constants.SSL_OP_NO_SSLv3;

    sslOptions['key'] = fs.readFileSync(config.ssl.key);
    sslOptions['cert'] = fs.readFileSync(config.ssl.cert);
    sslOptions['ca'] = config.ssl.ca.map(function(cert){
        return fs.readFileSync(cert);
    });

    // Startup HTTPS Server
    var httpsServer = https.createServer(sslOptions, app);
    httpsServer.listen(config.sslPort);

    sslOptions.agent = new https.Agent(sslOptions);
}

console.log("Traffic Portal Port         : %s", config.port);
console.log("Traffic Portal Proxy Port   : %s", config.proxyPort);
console.log("Traffic Portal SSL Port     : %s", config.sslPort);
<commit_msg>fixes incorrect path to server config file<commit_after>var constants = require('constants'),
    express = require('express'),
    http = require('http'),
    https = require('https'),
    path = require('path'),
    fs = require('fs'),
    morgan = require('morgan'),
    errorhandler = require('errorhandler'),
    modRewrite = require('connect-modrewrite'),
    timeout = require('connect-timeout');

var config;

try {
    // this should exist in prod environment. no need to create this file in dev as it will use the fallback (see catch)
    config = require('/etc/traffic_ops_v2/conf/config');
}
catch(e) {
    // this is used for dev environment
    config = require('../conf/config');
}

var logStream = fs.createWriteStream(config.log.stream, { flags: 'a' });
var useSSL = config.useSSL;

// Disable for self-signed certs in dev/test
process.env.NODE_TLS_REJECT_UNAUTHORIZED = config.reject_unauthorized;

var app = express();
// Add a handler to inspect the req.secure flag (see
// http://expressjs.com/api#req.secure). This allows us
// to know whether the request was via http or https.
app.all ("/*", function (req, res, next) {
    if (useSSL && !req.secure) {
        var headersHost = req.headers.host.split(':');
        var httpsUrl = 'https://' + headersHost[0] + ':' +  config.sslPort + req.url;
        // request was via http, so redirect to https
        res.redirect(httpsUrl);
    } else {
        next();
    }
});

app.use(modRewrite([
        '^/api/(.*?)\\?(.*)$ ' + config.api.base_url + '/api/$1?$2&api_key=' + config.api.key + ' [P]', // match /api/{version}/foos?active=true and replace with api.base_url/api/{version}/foos?active=true&api_key=api.key
        '^/api/(.*)$ ' + config.api.base_url + '/api/$1?api_key=' + config.api.key + ' [P]' // match /api/{version}/foos and replace with api.base_url/api/{version}/foos?api_key=api.key
]));
app.use(express.static(config.files.static));
app.use(morgan('combined', {
    stream: logStream,
    skip: function (req, res) { return res.statusCode < 400 }
}));
app.use(errorhandler());
app.use(timeout(config.timeout));

if (app.get('env') === 'dev') {
    app.use(require('connect-livereload')({
        port: 35728,
        excludeList: ['.woff', '.flv']
    }));
} else {
    app.set('env', "production");
}

// Enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable('trust proxy');

// Startup HTTP Server
var httpServer = http.createServer(app);
httpServer.listen(config.port);

if (useSSL) {
    //
    // Supply `SSL_OP_NO_SSLv3` constant as secureOption to disable SSLv3
    // from the list of supported protocols that SSLv23_method supports.
    //
    var sslOptions = {};
    sslOptions['secureOptions'] = constants.SSL_OP_NO_SSLv3;

    sslOptions['key'] = fs.readFileSync(config.ssl.key);
    sslOptions['cert'] = fs.readFileSync(config.ssl.cert);
    sslOptions['ca'] = config.ssl.ca.map(function(cert){
        return fs.readFileSync(cert);
    });

    // Startup HTTPS Server
    var httpsServer = https.createServer(sslOptions, app);
    httpsServer.listen(config.sslPort);

    sslOptions.agent = new https.Agent(sslOptions);
}

console.log("Traffic Ops Port         : %s", config.port);
console.log("Traffic Ops Proxy Port   : %s", config.proxyPort);
console.log("Traffic Ops SSL Port     : %s", config.sslPort);
<|endoftext|>