<commit_before>/**
 *
 * GPS Geolocation with device orientation in real-time
 */

(function () {
    /**constructor function**/
    function GPSController() {
        this._liveTrackingActivated = false;
        this._timer = undefined;
        this._timerMiliseconds = 500;
        this._savedAlpha = undefined;
        this.createGPSButton();
    }

    Object.defineProperties(GPSController.prototype, {
        liveTrackingActivated: {
            get: function () {
                return this._liveTrackingActivated;
            },
            set: function (value) {
                this._liveTrackingActivated = value;
            }
        },
        timer: {
            get: function () {
                return this._timer;
            },
            set: function (value) {
                this._timer = value;
            }
        },
        timerMiliseconds: {
            get: function () {
                return this._timerMiliseconds;
            },
            set: function (value) {
                this._timerMiliseconds = value;
            }
        },
        savedAlpha: {
            get: function () {
                return this._savedAlpha;
            },
            set: function (value) {
                this._savedAlpha = value;
            }
        }
    });

    GPSController.prototype.createGPSButton = function () {
        var scope = this;

        var button = document.getElementById("gpsButton");
        button.className = "cesium-button cesium-toolbar-button tracking-deactivated";
        button.title = "View GPS (single-click: one time, double-click: real-time)";

        // replace the 3D/2D button with this GPS button
        var customCesiumViewerToolbar = document.getElementsByClassName("cesium-viewer-toolbar")[0];
        var customGlobeButton = customCesiumViewerToolbar.getElementsByClassName("cesium-sceneModePicker-wrapper cesium-toolbar-button")[0];
        customCesiumViewerToolbar.replaceChild(button, customGlobeButton);
    }

    GPSController.prototype.handleDclick = function () {
        var scope = this;
        if (scope._liveTrackingActivated) {
            scope._liveTrackingActivated = false;
            scope.stopTracking();
        } else {
            scope._liveTrackingActivated = true;
            // tracking in intervals of miliseconds
            scope.startTracking();
        }
    }

    GPSController.prototype.handleClick = function () {
        var scope = this;
        if (scope._liveTrackingActivated) {
            scope._liveTrackingActivated = false;
            scope.stopTracking();
        } else {
            // one time tracking
            scope.startTracking();
        }
    }

    GPSController.prototype.startTracking = function () {
        var scope = this;

        if (scope._liveTrackingActivated) {
            var button = document.getElementById("gpsButton");
            button.classList.remove("tracking-deactivated");
            button.classList.add("tracking-activated");
        }

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            CitydbUtil.showAlertWindow("OK", "Error", "Geolocation is not supported by this browser.");
        }

        function showPosition(position) {
            getLocation();

            function getLocation() {
                if (window.DeviceOrientationEvent) {
                    window.addEventListener('deviceorientation', function auxOrientation(event) {
                        flyToLocationWithOrientation(position, event);
                        setTimeout(function () {
                            // one-time event
                            window.removeEventListener('deviceorientation', auxOrientation, false);
                        }, scope._timerMiliseconds);
                    }, false);
                } else {
                    CitydbUtil.showAlertWindow("OK", "Error", "Exact geolocation is not supported by this device.");
                    flyToLocationWithOrientation(position, event);
                }
            }

            function flyToLocationWithOrientation(position, ori) {
                var oriAlpha = 0;
                var oriBeta = 0;
                var oriGamma = 0;

//                if (Cesium.defined(ori)) {
//                    var mobileOS = getMobileOperatingSystem();
//                    // ALPHA
//                    if (mobileOS === "iOS" && ori.webkitCompassHeading) {
//                        oriAlpha = ori.webkitCompassHeading;
//                        // webkitCompassHeading is in [0, 360] degrees positive clockwise (non negative)
//                        // while heading is [-pi,pi), where positive points eastward
//                        if (oriAlpha < 180) {
//                            oriAlpha = Cesium.Math.toRadians(oriAlpha);
//                        } else {
//                            oriAlpha = Cesium.Math.toRadians(oriAlpha - 360);
//                        }
//                    } else if (Cesium.defined(ori.alpha)) {
//                        oriAlpha = ori.alpha;
//                        // alpha is in [0,360) degrees positive counterclockwise (non negative)
//                        // while heading is [-pi,pi), where positive points eastward
//                        if (oriAlpha < 180) {
//                            oriAlpha = Cesium.Math.toRadians(-oriAlpha);
//                        } else {
//                            oriAlpha = Cesium.Math.toRadians(180 - (oriAlpha - 180));
//                        }
//                    }
//
//                    // BETA
////                    if (Cesium.defined(ori.beta)) {
////                        oriBeta = Cesium.Math.toRadians(ori.beta - 90);
////                    }
//                }

                var angle = 0;
                if (ori.webkitCompassHeading) {
                    angle = ori.webkitCompassHeading;
                } else {
                    angle = 360 - ori.alpha;
                }

                if (typeof scope._savedAlpha !== "undefined") {
                    var diffAngle = angle - scope._savedAlpha;
                    if (diffAngle > 180) {
                        angle -= 360;
                    } else if (diffAngle < -180) {
                        angle += 360;
                    }
                }

                oriAlpha = Cesium.Math.toRadians(angle);
                scope._savedAlpha = oriAlpha;

                cesiumCamera.flyTo({
                    destination: Cesium.Cartesian3.fromDegrees(position.coords.longitude, position.coords.latitude, 150),
                    orientation: {
                        heading: oriAlpha,
                        pitch: Cesium.Math.toRadians(-90),
                        roll: oriGamma
                    },
                    complete: function () {
                        if (scope._liveTrackingActivated) {
                            // real-time tracking
                            scope._timer = setTimeout(function () {
                                // only check orientation in real-time
                                showPosition(position);
                                // also check position in real-time
                                // scope.startTracking();
                            }, scope._timerMiliseconds);
                        }
                    }
                });
            }
        }

        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    CitydbUtil.showAlertWindow("OK", "Error", "Geolocation denied by user.");
                    break;
                case error.POSITION_UNAVAILABLE:
                    CitydbUtil.showAlertWindow("OK", "Error", "Location information is unavailable.");
                    break;
                case error.TIMEOUT:
                    CitydbUtil.showAlertWindow("OK", "Error", "Location request has timed out.");
                    break;
                case error.UNKNOWN_ERROR:
                    CitydbUtil.showAlertWindow("OK", "Error", "An unknown error has occurred while requesting location information.");
                    break;
            }
        }
    }

    GPSController.prototype.stopTracking = function () {
        var scope = this;

        var button = document.getElementById("gpsButton");
        button.classList.remove("tracking-activated");
        button.classList.add("tracking-deactivated");

        clearTimeout(scope._timer);
    }

    window.GPSController = GPSController;
})();
<commit_msg>Adjusted orientations.<commit_after>/**
 *
 * GPS Geolocation with device orientation in real-time
 */

(function () {
    /**constructor function**/
    function GPSController() {
        this._liveTrackingActivated = false;
        this._timer = undefined;
        this._timerMiliseconds = 350;
        this._savedAlpha = undefined;
        this.createGPSButton();
    }

    Object.defineProperties(GPSController.prototype, {
        liveTrackingActivated: {
            get: function () {
                return this._liveTrackingActivated;
            },
            set: function (value) {
                this._liveTrackingActivated = value;
            }
        },
        timer: {
            get: function () {
                return this._timer;
            },
            set: function (value) {
                this._timer = value;
            }
        },
        timerMiliseconds: {
            get: function () {
                return this._timerMiliseconds;
            },
            set: function (value) {
                this._timerMiliseconds = value;
            }
        },
        savedAlpha: {
            get: function () {
                return this._savedAlpha;
            },
            set: function (value) {
                this._savedAlpha = value;
            }
        }
    });

    GPSController.prototype.createGPSButton = function () {
        var scope = this;

        var button = document.getElementById("gpsButton");
        button.className = "cesium-button cesium-toolbar-button tracking-deactivated";
        button.title = "View GPS (single-click: one time, double-click: real-time)";

        // replace the 3D/2D button with this GPS button
        var customCesiumViewerToolbar = document.getElementsByClassName("cesium-viewer-toolbar")[0];
        var customGlobeButton = customCesiumViewerToolbar.getElementsByClassName("cesium-sceneModePicker-wrapper cesium-toolbar-button")[0];
        customCesiumViewerToolbar.replaceChild(button, customGlobeButton);
    }

    GPSController.prototype.handleDclick = function () {
        var scope = this;
        if (scope._liveTrackingActivated) {
            scope._liveTrackingActivated = false;
            scope.stopTracking();
        } else {
            scope._liveTrackingActivated = true;
            // tracking in intervals of miliseconds
            scope.startTracking();
        }
    }

    GPSController.prototype.handleClick = function () {
        var scope = this;
        if (scope._liveTrackingActivated) {
            scope._liveTrackingActivated = false;
            scope.stopTracking();
        } else {
            // one time tracking
            scope.startTracking();
        }
    }

    GPSController.prototype.startTracking = function () {
        var scope = this;

        if (scope._liveTrackingActivated) {
            var button = document.getElementById("gpsButton");
            button.classList.remove("tracking-deactivated");
            button.classList.add("tracking-activated");
        }

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            CitydbUtil.showAlertWindow("OK", "Error", "Geolocation is not supported by this browser.");
        }

        function showPosition(position) {
            getLocation();

            function getLocation() {
                if (window.DeviceOrientationEvent) {
                    window.addEventListener('deviceorientation', function auxOrientation(event) {
                        flyToLocationWithOrientation(position, event);
                        setTimeout(function () {
                            // one-time event
                            window.removeEventListener('deviceorientation', auxOrientation, false);
                        }, scope._timerMiliseconds);
                    }, false);
                } else {
                    CitydbUtil.showAlertWindow("OK", "Error", "Exact geolocation is not supported by this device.");
                    flyToLocationWithOrientation(position, event);
                }
            }

            function flyToLocationWithOrientation(position, ori) {
                var oriAlpha = 0;
                var oriBeta = 0;
                var oriGamma = 0;

//                if (Cesium.defined(ori)) {
//                    var mobileOS = getMobileOperatingSystem();
//                    // ALPHA
//                    if (mobileOS === "iOS" && ori.webkitCompassHeading) {
//                        oriAlpha = ori.webkitCompassHeading;
//                        // webkitCompassHeading is in [0, 360] degrees positive clockwise (non negative)
//                        // while heading is [-pi,pi), where positive points eastward
//                        if (oriAlpha < 180) {
//                            oriAlpha = Cesium.Math.toRadians(oriAlpha);
//                        } else {
//                            oriAlpha = Cesium.Math.toRadians(oriAlpha - 360);
//                        }
//                    } else if (Cesium.defined(ori.alpha)) {
//                        oriAlpha = ori.alpha;
//                        // alpha is in [0,360) degrees positive counterclockwise (non negative)
//                        // while heading is [-pi,pi), where positive points eastward
//                        if (oriAlpha < 180) {
//                            oriAlpha = Cesium.Math.toRadians(-oriAlpha);
//                        } else {
//                            oriAlpha = Cesium.Math.toRadians(180 - (oriAlpha - 180));
//                        }
//                    }
//
//                    // BETA
////                    if (Cesium.defined(ori.beta)) {
////                        oriBeta = Cesium.Math.toRadians(ori.beta - 90);
////                    }
//                }

                var angle = 0;
                if (ori.webkitCompassHeading) {
                    angle = ori.webkitCompassHeading;
                } else {
                    angle = 360 - ori.alpha;
                }

                if (typeof scope._savedAlpha !== "undefined") {
                    var diffAngle = angle - scope._savedAlpha;
                    if (diffAngle > 180) {
                        angle -= 360;
                    } else if (diffAngle < -180) {
                        angle += 360;
                    }
                }

                oriAlpha = Cesium.Math.toRadians(angle);
                scope._savedAlpha = oriAlpha;

                cesiumCamera.flyTo({
                    destination: Cesium.Cartesian3.fromDegrees(position.coords.longitude, position.coords.latitude, 150),
                    orientation: {
                        heading: oriAlpha,
                        pitch: Cesium.Math.toRadians(-90),
                        roll: oriGamma
                    },
                    complete: function () {
                        if (scope._liveTrackingActivated) {
                            // real-time tracking
                            scope._timer = setTimeout(function () {
                                // only check orientation in real-time
                                showPosition(position);
                                // also check position in real-time
                                // scope.startTracking();
                            }, scope._timerMiliseconds);
                        }
                    }
                });
            }
        }

        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    CitydbUtil.showAlertWindow("OK", "Error", "Geolocation denied by user.");
                    break;
                case error.POSITION_UNAVAILABLE:
                    CitydbUtil.showAlertWindow("OK", "Error", "Location information is unavailable.");
                    break;
                case error.TIMEOUT:
                    CitydbUtil.showAlertWindow("OK", "Error", "Location request has timed out.");
                    break;
                case error.UNKNOWN_ERROR:
                    CitydbUtil.showAlertWindow("OK", "Error", "An unknown error has occurred while requesting location information.");
                    break;
            }
        }
    }

    GPSController.prototype.stopTracking = function () {
        var scope = this;

        var button = document.getElementById("gpsButton");
        button.classList.remove("tracking-activated");
        button.classList.add("tracking-deactivated");

        clearTimeout(scope._timer);
    }

    window.GPSController = GPSController;
})();
<|endoftext|>


<commit_before>#!/usr/bin/nodejs

const yaml = require('js-yaml');
const pathLib = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const _ = require('underscore');
const qidx = require('quadtile-index');
const core = require('@kartotherian/core');
const yargs = require('yargs');
const checkType = require('@kartotherian/input-validator');
const jplib = require('@kartotherian/jobprocessor');
const tilerator = require('../routes/tilerator');
const Queue = require('../lib/Queue');
const common = require('../lib/common');

const { JobProcessor } = jplib;

/**
 * Convert relative path to absolute, assuming current file is one
 * level below the project root
 * @param path
 * @returns {*}
 */
function normalizePath(path) {
  return pathLib.resolve(require.resolve('../package.json'), '..', path);
}

function loadYamlFile(arg) {
  const filename = normalizePath(arg);
  return yaml.safeLoad(fs.readFileSync(filename, 'utf8'), { filename });
}

function exit(message) {
  // eslint-disable-next-line no-console
  console.error(message);
  yargs.showHelp();
  process.exit(-1);
}

function dumpTiles(opt) {
  return opt.iterator().then((iterValue) => {
    if (iterValue !== undefined) {
      let val;
      if (opt.rawidx) {
        val = iterValue.idx.toString();
      } else {
        const xy = qidx.indexToXY(iterValue.idx);
        val = `${opt.zoom}/${xy[0]}/${xy[1]}`;
      }
      opt.outputStream.write(val);
      opt.outputStream.write('\n');
      return dumpTiles(opt);
    }
    return undefined;
  });
}

const args = yargs
  .usage('Usage: $0 [options]')
  .options({
    config: {
      describe: 'YAML-formatted configuration file',
      type: 'string',
      nargs: 1,
      coerce(arg) {
        return loadYamlFile(arg).services[0].conf;
      },
    },
    source: {
      // default: 'sources.prod.yaml',
      describe: 'YAML-formatted sources file',
      type: 'string',
      nargs: 1,
      coerce: normalizePath,
    },
    url: {
      describe: 'Source URL',
      type: 'string',
      nargs: 1,
      coerce: checkType.normalizeUrl,
    },
    v: {
      describe: 'Additional variable in YAML form. Use -v.varname value',
      type: 'string',
      nargs: 1,
      coerce: yaml.safeLoad,
    },
    p: {
      describe: 'Additional param in YAML form. Use -p.paramname value',
      type: 'string',
      nargs: 1,
    },
    j: {
      describe: 'Use -j.jobparam value to enque a job into the que, or if dumptiles is set, to output list of tiles',
      type: 'string',
      nargs: 1,
    },
    dumptiles: {
      describe: 'output tile indexes to this file',
      type: 'string',
    },
    dumprawidx: {
      describe: 'forces file output to a single zoom, index only format',
      type: 'boolean',
      implies: 'dumptiles',
      check: qidx.isValidZoom,
    },
    dumpoverride: {
      default: false,
      describe: 'override file output if exists',
      implies: 'dumptiles',
      type: 'boolean',
    },
    verbose: {
      default: false,
      describe: 'be verbose',
      type: 'boolean',
    },
  })
  .help('h')
  .alias('h', 'help')
  .argv;

if (args.p && (!_.isObject(args.p) || _.isEmpty(args.p))) {
  exit('-p must be used with the parameter name, e.g.   -p.paramname value');
}
if (args.v && (!_.isObject(args.v) || _.isEmpty(args.v))) {
  exit('-v must be used with variable name, e.g.   -v.varname value');
}
if (args.j && (!_.isObject(args.j) || _.isEmpty(args.j))) {
  exit('-j must be used with job parameter name, e.g.   -j.paramname value');
}

const app = {
  logger: {
    log(level, msg) {
      // eslint-disable-next-line no-console
      console.log(level, msg);
    },
  },
  metrics: {
    endTiming() {},
  },
  conf: args.config || {},
};

if (args.source) {
  app.conf.sources = args.source;
}
if (!_.isArray(app.conf.sources)) {
  app.conf.sources = [app.conf.sources];
}
if (app.conf.variables) {
  if (!_.isArray(app.conf.variables)) {
    app.conf.variables = [app.conf.variables];
  }
} else {
  app.conf.variables = [];
}
if (args.v) {
  app.conf.variables.push(args.v);
}
if (args.dumptiles) {
  if (!args.j || !_.isObject(args.j) || _.isArray(args.j)) {
    exit('A job must be specified using -j.<param> <value> parameters');
  }
  // We can reuse the same source, as we are
  // guaranteed that it exists, and we won't
  // execute this job
  if (!args.j.storageId) {
    args.j.storageId = args.j.generatorId;
  }
}

tilerator.bootstrap(app).then(() => {
  const sources = new core.Sources();
  return sources.init(app.conf.variables, app.conf.sources);
}).then((sources) => {
  core.setSources(sources);
  if (args.j) {
    const job = common.paramsToJob(args.j, sources);

    if (args.dumptiles) {
      const jp = new JobProcessor(sources, { data: job }, app.metrics);

      const outputStream = fs.createWriteStream(args.dumptiles, { flags: args.dumpoverride ? 'w' : 'wx' });

      jp.initSources();
      const iterator = jp.createMainIterator();

      const opt = {
        iterator, outputStream, zoom: job.zoom, rawidx: args.dumprawidx,
      };
      return dumpTiles(opt).then(() => outputStream.endAsync());
    }

    // Make sure not to start the kueui
    app.conf.daemonOnly = true;
    const queue = new Queue(app);

    return common.enqueJob(queue, job, args.j);
  }
  return undefined;
}).catch((err) => {
  // eslint-disable-next-line no-console
  console.log(err);
  // eslint-disable-next-line no-console
  console.log(err.stack);
  process.exit(-2);
})
  .then(() => {
    // eslint-disable-next-line no-console
    console.log('done');
    process.exit(0);
  });
<commit_msg>Update tileshell for new Core configuration<commit_after>#!/usr/bin/nodejs

const yaml = require('js-yaml');
const pathLib = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const _ = require('underscore');
const qidx = require('quadtile-index');
const core = require('@kartotherian/core');
const yargs = require('yargs');
const checkType = require('@kartotherian/input-validator');
const jplib = require('@kartotherian/jobprocessor');
const tilerator = require('../routes/tilerator');
const Queue = require('../lib/Queue');
const common = require('../lib/common');

const { JobProcessor } = jplib;

/**
 * Convert relative path to absolute, assuming current file is one
 * level below the project root
 * @param path
 * @returns {*}
 */
function normalizePath(path) {
  return pathLib.resolve(require.resolve('../package.json'), '..', path);
}

function loadYamlFile(arg) {
  const filename = normalizePath(arg);
  return yaml.safeLoad(fs.readFileSync(filename, 'utf8'), { filename });
}

function exit(message) {
  // eslint-disable-next-line no-console
  console.error(message);
  yargs.showHelp();
  process.exit(-1);
}

function dumpTiles(opt) {
  return opt.iterator().then((iterValue) => {
    if (iterValue !== undefined) {
      let val;
      if (opt.rawidx) {
        val = iterValue.idx.toString();
      } else {
        const xy = qidx.indexToXY(iterValue.idx);
        val = `${opt.zoom}/${xy[0]}/${xy[1]}`;
      }
      opt.outputStream.write(val);
      opt.outputStream.write('\n');
      return dumpTiles(opt);
    }
    return undefined;
  });
}

const args = yargs
  .usage('Usage: $0 [options]')
  .options({
    config: {
      describe: 'YAML-formatted configuration file',
      type: 'string',
      nargs: 1,
      coerce(arg) {
        return loadYamlFile(arg).services[0].conf;
      },
    },
    source: {
      // default: 'sources.prod.yaml',
      describe: 'YAML-formatted sources file',
      type: 'string',
      nargs: 1,
      coerce: normalizePath,
    },
    url: {
      describe: 'Source URL',
      type: 'string',
      nargs: 1,
      coerce: checkType.normalizeUrl,
    },
    v: {
      describe: 'Additional variable in YAML form. Use -v.varname value',
      type: 'string',
      nargs: 1,
      coerce: yaml.safeLoad,
    },
    p: {
      describe: 'Additional param in YAML form. Use -p.paramname value',
      type: 'string',
      nargs: 1,
    },
    j: {
      describe: 'Use -j.jobparam value to enque a job into the que, or if dumptiles is set, to output list of tiles',
      type: 'string',
      nargs: 1,
    },
    dumptiles: {
      describe: 'output tile indexes to this file',
      type: 'string',
    },
    dumprawidx: {
      describe: 'forces file output to a single zoom, index only format',
      type: 'boolean',
      implies: 'dumptiles',
      check: qidx.isValidZoom,
    },
    dumpoverride: {
      default: false,
      describe: 'override file output if exists',
      implies: 'dumptiles',
      type: 'boolean',
    },
    verbose: {
      default: false,
      describe: 'be verbose',
      type: 'boolean',
    },
  })
  .help('h')
  .alias('h', 'help')
  .argv;

if (args.p && (!_.isObject(args.p) || _.isEmpty(args.p))) {
  exit('-p must be used with the parameter name, e.g.   -p.paramname value');
}
if (args.v && (!_.isObject(args.v) || _.isEmpty(args.v))) {
  exit('-v must be used with variable name, e.g.   -v.varname value');
}
if (args.j && (!_.isObject(args.j) || _.isEmpty(args.j))) {
  exit('-j must be used with job parameter name, e.g.   -j.paramname value');
}

const app = {
  logger: {
    log(level, msg) {
      // eslint-disable-next-line no-console
      console.log(level, msg);
    },
  },
  metrics: {
    endTiming() {},
  },
  conf: args.config || {},
};

if (args.source) {
  app.conf.sources = args.source;
}
if (!_.isArray(app.conf.sources)) {
  app.conf.sources = [app.conf.sources];
}
if (app.conf.variables) {
  if (!_.isArray(app.conf.variables)) {
    app.conf.variables = [app.conf.variables];
  }
} else {
  app.conf.variables = [];
}
if (args.v) {
  app.conf.variables.push(args.v);
}
if (args.dumptiles) {
  if (!args.j || !_.isObject(args.j) || _.isArray(args.j)) {
    exit('A job must be specified using -j.<param> <value> parameters');
  }
  // We can reuse the same source, as we are
  // guaranteed that it exists, and we won't
  // execute this job
  if (!args.j.storageId) {
    args.j.storageId = args.j.generatorId;
  }
}

tilerator.bootstrap(app).then(() => {
  const sources = new core.Sources();
  return sources.init(app.conf);
}).then((sources) => {
  core.setSources(sources);
  if (args.j) {
    const job = common.paramsToJob(args.j, sources);

    if (args.dumptiles) {
      const jp = new JobProcessor(sources, { data: job }, app.metrics);

      const outputStream = fs.createWriteStream(args.dumptiles, { flags: args.dumpoverride ? 'w' : 'wx' });

      jp.initSources();
      const iterator = jp.createMainIterator();

      const opt = {
        iterator, outputStream, zoom: job.zoom, rawidx: args.dumprawidx,
      };
      return dumpTiles(opt).then(() => outputStream.endAsync());
    }

    // Make sure not to start the kueui
    app.conf.daemonOnly = true;
    const queue = new Queue(app);

    return common.enqueJob(queue, job, args.j);
  }
  return undefined;
}).catch((err) => {
  // eslint-disable-next-line no-console
  console.log(err);
  // eslint-disable-next-line no-console
  console.log(err.stack);
  process.exit(-2);
})
  .then(() => {
    // eslint-disable-next-line no-console
    console.log('done');
    process.exit(0);
  });
<|endoftext|>


<commit_before>'use strict';

/* global Connector */

var INFO_TRACK = 3;
var INFO_ARTIST = 4;
var INFO_DURATION = 5;

var trackInfo = null;

function updateTrackInfo() {
	trackInfo = JSON.parse(localStorage.getItem('audio_v10_track'));
}

/**
 * Decodes HTML entities in given text string
 * @param  {String} str String with HTML entities
 * @return {String}     Decoded string
 */
var decodeHtmlEntity = function(str) {
	if (str === null) {
		return null;
	}

	return str.replace(/&#(\d+);/g, function(match, dec) {
		return String.fromCharCode(dec);
	});
};

Connector.artistTrackSelector = '.top_audio_player_title';
Connector.playerSelector = '#top_audio_player';

Connector.getArtist = function () {
			updateTrackInfo();
			return decodeHtmlEntity(trackInfo[INFO_ARTIST]);
		};
Connector.getTrack = function () {
			updateTrackInfo();
			return decodeHtmlEntity(trackInfo[INFO_TRACK]);
		};
Connector.getCurrentTime = function () {
			updateTrackInfo();
			var progress = parseFloat(localStorage.getItem('audio_v10_progress'));
			return Math.round(parseInt(trackInfo[INFO_DURATION]) * progress);
		};
Connector.getDuration = function () {
			updateTrackInfo();
			return parseInt(trackInfo[INFO_DURATION]);
		};
Connector.isPlaying = function() {
	return $(this.playerSelector).hasClass('top_audio_player_playing');
		};
<commit_msg>Fix formatting in VK connector<commit_after>'use strict';

/* global Connector */

var INFO_TRACK = 3;
var INFO_ARTIST = 4;
var INFO_DURATION = 5;

var trackInfo = null;

function updateTrackInfo() {
	trackInfo = JSON.parse(localStorage.getItem('audio_v10_track'));
}

/**
 * Decodes HTML entities in given text string
 * @param  {String} str String with HTML entities
 * @return {String}     Decoded string
 */
var decodeHtmlEntity = function(str) {
	if (str === null) {
		return null;
	}

	return str.replace(/&#(\d+);/g, function(match, dec) {
		return String.fromCharCode(dec);
	});
};

Connector.artistTrackSelector = '.top_audio_player_title';

Connector.playerSelector = '#top_audio_player';

Connector.getArtist = function () {
	updateTrackInfo();
	return decodeHtmlEntity(trackInfo[INFO_ARTIST]);
};

Connector.getTrack = function () {
	updateTrackInfo();
	return decodeHtmlEntity(trackInfo[INFO_TRACK]);
};

Connector.getCurrentTime = function () {
	updateTrackInfo();
	var progress = parseFloat(localStorage.getItem('audio_v10_progress'));
	return Math.round(parseInt(trackInfo[INFO_DURATION]) * progress);
};

Connector.getDuration = function () {
	updateTrackInfo();
	return parseInt(trackInfo[INFO_DURATION]);
};

Connector.isPlaying = function() {
	return $(this.playerSelector).hasClass('top_audio_player_playing');
};
<|endoftext|>


<commit_before>{
	"fuckthis":"http://goo.gl/m2RCE",
	"headdesk":"http://goo.gl/EJy54",
	"mindblown":"http://goo.gl/vuEy9",
	"noidea":"http://goo.gl/yCFFA",
	"noidea2":"http://goo.gl/KCpBr",
	"hellodog":"http://goo.gl/JFnxD",
	"whatbutton":"http://goo.gl/Q8B3y",
	"notime":"http://goo.gl/exuKV",
	"pigeon":"http://i.imgur.com/iOBmtNk.gif"
}
<commit_msg>Hello shout added<commit_after>{
	"fuckthis":"http://goo.gl/m2RCE",
	"headdesk":"http://goo.gl/EJy54",
	"mindblown":"http://goo.gl/vuEy9",
	"noidea":"http://goo.gl/yCFFA",
	"noidea2":"http://goo.gl/KCpBr",
	"hellodog":"http://goo.gl/JFnxD",
	"whatbutton":"http://goo.gl/Q8B3y",
	"notime":"http://goo.gl/exuKV",
	"pigeon":"http://i.imgur.com/iOBmtNk.gif",
	"hello":"http://i.imgur.com/6YbAxG8.gif"
}
<|endoftext|>


<commit_before>/* Materializecss Stepper - By Kinark 2016
// https://github.com/Kinark/Materialize-stepper
// JS v2.1.3
*/

var validation = $.isFunction($.fn.valid) ? 1 : 0;

$.fn.isValid  = function() {
   if(validation){
      return this.valid();
   } else {
      return true;
   }
};

if (validation) {
   $.validator.setDefaults({
      errorClass: 'invalid',
      validClass: "valid",
      errorPlacement: function (error, element) {
         if(element.is(':radio') || element.is(':checkbox')) {
            error.insertBefore($(element).parent());
         } else {
            error.insertAfter(element); // default error placement.
            // element.closest('label').data('error', error);
            // element.next().attr('data-error', error);
         }
      },
      success: function (element) {
         if(!$(element).closest('li').find('label.invalid:not(:empty)').length){
            $(element).closest('li').removeClass('wrong');
         }
      }
   });
}

$.fn.getActiveStep  = function() {
   var active = this.find('.step.active');
   return $(this.children('.step:visible')).index($(active))+1;
};

$.fn.activateStep  = function(callback) {
   if($(this).hasClass('step')) return;
   var stepper = $(this).closest('ul.stepper');
   stepper.find('>li').removeAttr("data-last");
   if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
      $(this).addClass("step").stop().slideDown(400, function(){
         $(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   } else {
      $(this).addClass("step").stop().css({'width':'0%','display': 'inherit'}).animate({width:'100%'}, 400, function(){
         $(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   }
};

$.fn.deactivateStep  = function(callback) {
   if(!$(this).hasClass('step')) return;
   var stepper = $(this).closest('ul.stepper');
   stepper.find('>li').removeAttr("data-last");
   if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
      $(this).stop().css({'transition':'none', '-webkit-transition':'margin-bottom none'}).slideUp(400, function(){
         $(this).removeClass("step").css({'height':'auto','margin-bottom':'','transition':'margin-bottom .4s','-webkit-transition':'margin-bottom .4s'});
         if(callback)callback();
         stepper.find('>li').removeAttr("data-last");
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   } else {
      $(this).stop().animate({width:'0%'}, 400, function(){
         $(this).removeClass("step").hide().css({'height':'auto', 'margin-bottom': '','display': 'none', 'width': ''});
         if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   }
};

$.fn.showError  = function(error) {
   if(validation) {
      var name = this.attr('name');
      var form = this.closest('form');
      var obj = {};
      obj[name] = error;
      form.validate().showErrors(obj);
      this.closest('li').addClass('wrong');
   } else {
      this.removeClass('valid').addClass('invalid');
      this.next().attr('data-error', error);
   }
};

$.fn.activateFeedback  = function() {
   var active = this.find('.step.active:not(.feedbacking)').addClass('feedbacking').find('.step-content');
   active.prepend('

');
};

$.fn.destroyFeedback  = function() {
   var active = this.find('.step.active.feedbacking');
   if(active) {
      active.removeClass('feedbacking');
      active.find('.wait-feedback').remove();
   }
   return true;
};

$.fn.resetStepper  = function(step) {
   if(!step) step = 1;
   var form = $(this).closest('form');
   $(form)[0].reset();
   Materialize.updateTextFields();
   return $(this).openStep(step);
};

$.fn.submitStepper  = function(step) {
   var form = this.closest('form');
   if(form.isValid()) {
      form.submit();
   }
};

$.fn.nextStep = function(callback, activefb, e) {
   var stepper = this;
   var settings = $(stepper).data('settings');
   var form = this.closest('form');
   var active = this.find('.step.active');
   var next = $(this.children('.step:visible')).index($(active))+2;
   var feedback = active.find('.next-step').length > 1 ? (e ? $(e.target).data("feedback") : undefined) : active.find('.next-step').data("feedback");
   if(form.isValid()) {
      if(feedback && activefb) {
         if(settings.showFeedbackLoader) stepper.activateFeedback();
         return window[feedback].call();
      }
      active.removeClass('wrong').addClass('done');
      this.openStep(next, callback);
      return this.trigger('nextstep');
   } else {
      return active.removeClass('done').addClass('wrong');
   }
};

$.fn.prevStep = function(callback) {
   var active = this.find('.step.active');
   if(active.hasClass('feedbacking')) return;
   var prev = $(this.children('.step:visible')).index($(active));
   active.removeClass('wrong');
   this.openStep(prev, callback);
   return this.trigger('prevstep');
};

$.fn.openStep = function(step, callback) {
   var settings = $(this).closest('ul.stepper').data('settings');
   var $this = this;
   var step_num = step - 1;
   step = this.find('.step:visible:eq('+step_num+')');
   if(step.hasClass('active')) return;
   var active = this.find('.step.active');
   var next;
   var prev_active = next = $(this.children('.step:visible')).index($(active));
   var order = step_num > prev_active ? 1 : 0;
   if(active.hasClass('feedbacking')) $this.destroyFeedback();
   active.closeAction(order);
   step.openAction(order, function(){
      if(settings.autoFocusInput) step.find('input:enabled:visible:first').focus();
      $this.trigger('stepchange').trigger('step'+(step_num+1));
      if(step.data('event')) $this.trigger(step.data('event'));
      if(callback)callback();
   });
};

$.fn.closeAction = function(order, callback) {
   var closable = this.removeClass('active').find('.step-content');
   if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
      closable.stop().slideUp(300,"easeOutQuad", callback);
   } else {
      if(order==1) {
         closable.animate({left: '-100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
      } else {
         closable.animate({left: '100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
      }
   }
};

$.fn.openAction = function(order, callback) {
   var openable = this.removeClass('done').addClass('active').find('.step-content');
   if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
      openable.slideDown(300,"easeOutQuad", callback);
   } else {
      if(order==1) {
         openable.css({left: '100%', display: 'block'}).animate({left: '0%'}, callback);
      } else {
         openable.css({left: '-100%', display: 'block'}).animate({left: '0%'}, callback);
      }
   }
};

$.fn.activateStepper = function(options) {
   var settings = $.extend({
      linearStepsNavigation: true,
      autoFocusInput: true,
      showFeedbackLoader: true,
      autoFormCreation: true
   }, options);
   $(document).on('click', function(e){
      if(!$(e.target).parents(".stepper").length){
         $('.stepper.focused').removeClass('focused');
      }
   });

   $(this).each(function(){
      var $stepper = $(this);
      if(!$stepper.parents("form").length && settings.autoFormCreation) {
         var method = $stepper.data('method');
         var action = $stepper.data('action');
         var method = (method ? method : "GET");
         action = (action ? action : "?");
         $stepper.wrap( '<form action="'+action+'" method="'+method+'"></form>' );
      }

      $stepper.data('settings', {linearStepsNavigation: settings.linearStepsNavigation,autoFocusInput: settings.autoFocusInput,showFeedbackLoader:settings.showFeedbackLoader});
      $stepper.find('li.step.active').openAction(1);
      $stepper.find('>li').removeAttr("data-last");
      $stepper.find('>li.step').last().attr('data-last', 'true');

      $stepper.on("click", '.step:not(.active)', function () {
         var object = $($stepper.children('.step:visible')).index($(this));
         if(!$stepper.hasClass('linear')) {
            $stepper.openStep(object+1);
         } else if(settings.linearStepsNavigation) {
            var active = $stepper.find('.step.active');
            if($($stepper.children('.step:visible')).index($(active))+1 == object) {
               $stepper.nextStep(undefined, true, undefined);
            } else if ($($stepper.children('.step:visible')).index($(active))-1 == object) {
               $stepper.prevStep(undefined);
            }
         }
      }).on("click", '.next-step', function(e) {
         e.preventDefault();
         $stepper.nextStep(undefined, true, e);
      }).on("click", '.previous-step', function(e) {
         e.preventDefault();
         $stepper.prevStep(undefined);
      }).on("click", "button:submit:not(.next-step, .previous-step)", function (e) {
         e.preventDefault();
         feedback = e ? $(e.target).data("feedback") : undefined;
         var form = $stepper.closest('form');
         if(form.isValid()) {
            if(feedback) {
               stepper.activateFeedback();
               return window[feedback].call();
            }
            form.submit();
         }
      }).on("click", function () {
         $('.stepper.focused').removeClass('focused');
         $(this).addClass('focused');
      });
   });
};
<commit_msg>Include form validation reset<commit_after>/* Materializecss Stepper - By Kinark 2016
// https://github.com/Kinark/Materialize-stepper
// JS v2.1.3
*/

var validation = $.isFunction($.fn.valid) ? 1 : 0;

$.fn.isValid  = function() {
   if(validation){
      return this.valid();
   } else {
      return true;
   }
};

if (validation) {
   $.validator.setDefaults({
      errorClass: 'invalid',
      validClass: "valid",
      errorPlacement: function (error, element) {
         if(element.is(':radio') || element.is(':checkbox')) {
            error.insertBefore($(element).parent());
         } else {
            error.insertAfter(element); // default error placement.
            // element.closest('label').data('error', error);
            // element.next().attr('data-error', error);
         }
      },
      success: function (element) {
         if(!$(element).closest('li').find('label.invalid:not(:empty)').length){
            $(element).closest('li').removeClass('wrong');
         }
      }
   });
}

$.fn.getActiveStep  = function() {
   var active = this.find('.step.active');
   return $(this.children('.step:visible')).index($(active))+1;
};

$.fn.activateStep  = function(callback) {
   if($(this).hasClass('step')) return;
   var stepper = $(this).closest('ul.stepper');
   stepper.find('>li').removeAttr("data-last");
   if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
      $(this).addClass("step").stop().slideDown(400, function(){
         $(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   } else {
      $(this).addClass("step").stop().css({'width':'0%','display': 'inherit'}).animate({width:'100%'}, 400, function(){
         $(this).css({'height':'auto', 'margin-bottom': '','display': 'inherit'});if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   }
};

$.fn.deactivateStep  = function(callback) {
   if(!$(this).hasClass('step')) return;
   var stepper = $(this).closest('ul.stepper');
   stepper.find('>li').removeAttr("data-last");
   if(window.innerWidth < 993 || !stepper.hasClass('horizontal')) {
      $(this).stop().css({'transition':'none', '-webkit-transition':'margin-bottom none'}).slideUp(400, function(){
         $(this).removeClass("step").css({'height':'auto','margin-bottom':'','transition':'margin-bottom .4s','-webkit-transition':'margin-bottom .4s'});
         if(callback)callback();
         stepper.find('>li').removeAttr("data-last");
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   } else {
      $(this).stop().animate({width:'0%'}, 400, function(){
         $(this).removeClass("step").hide().css({'height':'auto', 'margin-bottom': '','display': 'none', 'width': ''});
         if(callback)callback();
         stepper.find('>li.step').last().attr('data-last', 'true');
      });
   }
};

$.fn.showError  = function(error) {
   if(validation) {
      var name = this.attr('name');
      var form = this.closest('form');
      var obj = {};
      obj[name] = error;
      form.validate().showErrors(obj);
      this.closest('li').addClass('wrong');
   } else {
      this.removeClass('valid').addClass('invalid');
      this.next().attr('data-error', error);
   }
};

$.fn.activateFeedback  = function() {
   var active = this.find('.step.active:not(.feedbacking)').addClass('feedbacking').find('.step-content');
   active.prepend('

');
};

$.fn.destroyFeedback  = function() {
   var active = this.find('.step.active.feedbacking');
   if(active) {
      active.removeClass('feedbacking');
      active.find('.wait-feedback').remove();
   }
   return true;
};

$.fn.resetStepper  = function(step) {
   if(!step) step = 1;
   var form = $(this).closest('form');
   $(form)[0].reset();
   Materialize.updateTextFields();

   if (validation) {
       form.validate().resetForm();
       $(this).find('li.step').removeClass('wrong');
   }

   return $(this).openStep(step);
};

$.fn.submitStepper  = function(step) {
   var form = this.closest('form');
   if(form.isValid()) {
      form.submit();
   }
};

$.fn.nextStep = function(callback, activefb, e) {
   var stepper = this;
   var settings = $(stepper).data('settings');
   var form = this.closest('form');
   var active = this.find('.step.active');
   var next = $(this.children('.step:visible')).index($(active))+2;
   var feedback = active.find('.next-step').length > 1 ? (e ? $(e.target).data("feedback") : undefined) : active.find('.next-step').data("feedback");
   if(form.isValid()) {
      if(feedback && activefb) {
         if(settings.showFeedbackLoader) stepper.activateFeedback();
         return window[feedback].call();
      }
      active.removeClass('wrong').addClass('done');
      this.openStep(next, callback);
      return this.trigger('nextstep');
   } else {
      return active.removeClass('done').addClass('wrong');
   }
};

$.fn.prevStep = function(callback) {
   var active = this.find('.step.active');
   if(active.hasClass('feedbacking')) return;
   var prev = $(this.children('.step:visible')).index($(active));
   active.removeClass('wrong');
   this.openStep(prev, callback);
   return this.trigger('prevstep');
};

$.fn.openStep = function(step, callback) {
   var settings = $(this).closest('ul.stepper').data('settings');
   var $this = this;
   var step_num = step - 1;
   step = this.find('.step:visible:eq('+step_num+')');
   if(step.hasClass('active')) return;
   var active = this.find('.step.active');
   var next;
   var prev_active = next = $(this.children('.step:visible')).index($(active));
   var order = step_num > prev_active ? 1 : 0;
   if(active.hasClass('feedbacking')) $this.destroyFeedback();
   active.closeAction(order);
   step.openAction(order, function(){
      if(settings.autoFocusInput) step.find('input:enabled:visible:first').focus();
      $this.trigger('stepchange').trigger('step'+(step_num+1));
      if(step.data('event')) $this.trigger(step.data('event'));
      if(callback)callback();
   });
};

$.fn.closeAction = function(order, callback) {
   var closable = this.removeClass('active').find('.step-content');
   if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
      closable.stop().slideUp(300,"easeOutQuad", callback);
   } else {
      if(order==1) {
         closable.animate({left: '-100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
      } else {
         closable.animate({left: '100%'},function(){closable.css({display: 'none', left: '0%'}, callback);});
      }
   }
};

$.fn.openAction = function(order, callback) {
   var openable = this.removeClass('done').addClass('active').find('.step-content');
   if(window.innerWidth < 993 || !this.closest('ul').hasClass('horizontal')) {
      openable.slideDown(300,"easeOutQuad", callback);
   } else {
      if(order==1) {
         openable.css({left: '100%', display: 'block'}).animate({left: '0%'}, callback);
      } else {
         openable.css({left: '-100%', display: 'block'}).animate({left: '0%'}, callback);
      }
   }
};

$.fn.activateStepper = function(options) {
   var settings = $.extend({
      linearStepsNavigation: true,
      autoFocusInput: true,
      showFeedbackLoader: true,
      autoFormCreation: true
   }, options);
   $(document).on('click', function(e){
      if(!$(e.target).parents(".stepper").length){
         $('.stepper.focused').removeClass('focused');
      }
   });

   $(this).each(function(){
      var $stepper = $(this);
      if(!$stepper.parents("form").length && settings.autoFormCreation) {
         var method = $stepper.data('method');
         var action = $stepper.data('action');
         var method = (method ? method : "GET");
         action = (action ? action : "?");
         $stepper.wrap( '<form action="'+action+'" method="'+method+'"></form>' );
      }

      $stepper.data('settings', {linearStepsNavigation: settings.linearStepsNavigation,autoFocusInput: settings.autoFocusInput,showFeedbackLoader:settings.showFeedbackLoader});
      $stepper.find('li.step.active').openAction(1);
      $stepper.find('>li').removeAttr("data-last");
      $stepper.find('>li.step').last().attr('data-last', 'true');

      $stepper.on("click", '.step:not(.active)', function () {
         var object = $($stepper.children('.step:visible')).index($(this));
         if(!$stepper.hasClass('linear')) {
            $stepper.openStep(object+1);
         } else if(settings.linearStepsNavigation) {
            var active = $stepper.find('.step.active');
            if($($stepper.children('.step:visible')).index($(active))+1 == object) {
               $stepper.nextStep(undefined, true, undefined);
            } else if ($($stepper.children('.step:visible')).index($(active))-1 == object) {
               $stepper.prevStep(undefined);
            }
         }
      }).on("click", '.next-step', function(e) {
         e.preventDefault();
         $stepper.nextStep(undefined, true, e);
      }).on("click", '.previous-step', function(e) {
         e.preventDefault();
         $stepper.prevStep(undefined);
      }).on("click", "button:submit:not(.next-step, .previous-step)", function (e) {
         e.preventDefault();
         feedback = e ? $(e.target).data("feedback") : undefined;
         var form = $stepper.closest('form');
         if(form.isValid()) {
            if(feedback) {
               stepper.activateFeedback();
               return window[feedback].call();
            }
            form.submit();
         }
      }).on("click", function () {
         $('.stepper.focused').removeClass('focused');
         $(this).addClass('focused');
      });
   });
};
<|endoftext|>


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

var fs = require('fs');
var util = require('util');
var url = require('url');
var path = require('path');
var sprintf = require('sprintf').sprintf;

var async = require('async');

var mkdir = require('./fsutil').mkdir;
var stalker = require('stalker');
var targets = require('./targets');

var Manifest = require('./manifest').Manifest;

var log = require('logmagic').local('lib.cassandra-syncer');

function SyncMaster(options, callback) {
  this._options = options;
  this._target = null;
  this._watcher = null;
  this._callback = null;
  this._backupDir = null;
  this._re = /.*-Data.db/;
  this._endBack = null;
  this._endBack = callback;
  this.manifest = null;
  var self = this;
  this._callback = function(err) {
    if (self._watcher) {
      /* TODO: support cancelling a watcher */
      // self._watcher.reset();
    }
    self._endBack(err);
  };
}

SyncMaster.prototype._isSyncable = function(file) {
  return file.match(this._re);
}

SyncMaster.prototype._syncCallback = function(err, file) {
  var self = this,
      deltaManifest = null,
      ignoreFile = false;

  if (err) {
    self._callback(err);
    return;
  }

  if (!self._isSyncable(file)) {
    return;
  }

  async.series([
    function(callback) {
      self.manifest.generate(callback);
    },
    function(callback) {
      self._target.readManifest(callback);
    },
    function(callback) {
      deltaManifest = Manifest.createDelta(self.manifest, self._target.manifest);
      self._target.manifest.setManifest(self.manifest);
      callback();
    },
    function(callback) {
      if (deltaManifest.contains(file)) {
        ignoreFile = true;
        self._target.sync(file, callback);
      } else {
        callback();
      }
    },
    function(callback) {
      if (ignoreFile) {
        self._target.writeManifest(callback);
        return;
      }
      callback();
    },
    function summary(callback) {
      var msg;

      file = path.basename(file);

      if (ignoreFile) {
        msg = sprintf('Synced %s\n', file);
      } else {
        msg = sprintf('Ignore %s\n', file);
      }

      process.stdout.write(msg);
    }
  ], function(err) {
    if (err) {
      process.stderr.write(err);
      self._callback(err);
    }
  });
};

SyncMaster.prototype.run = function() {
  var target = url.parse(this._options.target);
  var T = targets[target.protocol];
  var self = this;

  if (!T) {
    self._callback(new Error("Invalid Target type"));
    return;
  }

  if (this._options.backupDirectory) {
    this._backupDir = this._options.backupDirectory;
  }
  else {
    this._backupDir = path.join(this._options.source, 'snapshots/_syncer');
  }

  log.msg('Hard linking into ' + self._backupDir);
  self._target = new T(target, self._backupDir, self._re);
  self.manifest = new Manifest(self._options.source, self._re);

  async.series([
    function watch(callback) {
      self._watcher = stalker.watch(self._options.source, function(err, file) {
        self._syncCallback(err, file);
      });
      callback();
    }

  ], function(err) {
    if (err) {
      process.stderr.write(err);
    }
  });
};

function sync(options, callback) {
  var sm = new SyncMaster(options, callback);
  sm.run();
}

function FsckMaster(options, callback) {
  this._options = options;
  this._target = null;
  this._callback = callback;
}

FsckMaster.prototype.run = function() {
  var target = url.parse(this._options.target);
  var T = targets[target.protocol];

  if (!T) {
    callback(new Error("Invalid Target type"));
    return;
  }

  this._target = new T(target, null);
  /* TODO: improve */
  this._target.fsck(console.log, this._callback);
};

function fsck(options, callback) {
  var sm = new FsckMaster(options, callback);
  sm.run();
}

exports.sync = sync;
exports.fsck = fsck;
<commit_msg>cleanup log<commit_after>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var fs = require('fs');
var util = require('util');
var url = require('url');
var path = require('path');
var sprintf = require('sprintf').sprintf;

var async = require('async');

var mkdir = require('./fsutil').mkdir;
var stalker = require('stalker');
var targets = require('./targets');

var Manifest = require('./manifest').Manifest;

var log = require('logmagic').local('lib.cassandra-syncer');

function SyncMaster(options, callback) {
  this._options = options;
  this._target = null;
  this._watcher = null;
  this._callback = null;
  this._backupDir = null;
  this._re = /.*-Data.db/;
  this._endBack = null;
  this._endBack = callback;
  this.manifest = null;
  var self = this;
  this._callback = function(err) {
    if (self._watcher) {
      /* TODO: support cancelling a watcher */
      // self._watcher.reset();
    }
    self._endBack(err);
  };
}

SyncMaster.prototype._isSyncable = function(file) {
  return file.match(this._re);
}

SyncMaster.prototype._syncCallback = function(err, file) {
  var self = this,
      deltaManifest = null,
      updateFile = false;

  if (err) {
    self._callback(err);
    return;
  }

  if (!self._isSyncable(file)) {
    return;
  }

  async.series([
    function(callback) {
      self.manifest.generate(callback);
    },
    function(callback) {
      self._target.readManifest(callback);
    },
    function(callback) {
      deltaManifest = Manifest.createDelta(self.manifest, self._target.manifest);
      self._target.manifest.setManifest(self.manifest);
      callback();
    },
    function(callback) {
      if (deltaManifest.contains(file)) {
        updateFile = true;
        self._target.sync(file, callback);
      } else {
        callback();
      }
    },
    function(callback) {
      if (updateFile) {
        self._target.writeManifest(callback);
        return;
      }
      callback();
    },
    function summary(callback) {
      file = path.basename(file);
      log.info(updateFile ? 'Sync' : 'Ignore', file);
      callback();
    }
  ], function(err) {
    if (err) {
      process.stderr.write(err);
      self._callback(err);
    }
  });
};

SyncMaster.prototype.run = function() {
  var target = url.parse(this._options.target);
  var T = targets[target.protocol];
  var self = this;

  if (!T) {
    self._callback(new Error("Invalid Target type"));
    return;
  }

  if (this._options.backupDirectory) {
    this._backupDir = this._options.backupDirectory;
  }
  else {
    this._backupDir = path.join(this._options.source, 'snapshots/_syncer');
  }

  log.msg('Hard linking into ' + self._backupDir);
  self._target = new T(target, self._backupDir, self._re);
  self.manifest = new Manifest(self._options.source, self._re);

  async.series([
    function watch(callback) {
      self._watcher = stalker.watch(self._options.source, function(err, file) {
        self._syncCallback(err, file);
      });
      callback();
    }

  ], function(err) {
    if (err) {
      process.stderr.write(err);
    }
  });
};

function sync(options, callback) {
  var sm = new SyncMaster(options, callback);
  sm.run();
}

function FsckMaster(options, callback) {
  this._options = options;
  this._target = null;
  this._callback = callback;
}

FsckMaster.prototype.run = function() {
  var target = url.parse(this._options.target);
  var T = targets[target.protocol];

  if (!T) {
    callback(new Error("Invalid Target type"));
    return;
  }

  this._target = new T(target, null);
  /* TODO: improve */
  this._target.fsck(console.log, this._callback);
};

function fsck(options, callback) {
  var sm = new FsckMaster(options, callback);
  sm.run();
}

exports.sync = sync;
exports.fsck = fsck;
<|endoftext|>


<commit_before>const crypto = require("crypto");
const execPromise = require("./execPromise");
// for fs.remove. replace with fs.rm after dropping v12 support
const fse = require("fs-extra");
const fsNonPromise = require("fs");
const { promises: fs } = fsNonPromise;
const path = require("path");
const got = require("got");
const { performance } = require("perf_hooks");
const { promisify } = require("util");
const stream = require("stream");
const tar = require("tar-fs");
const zlib = require("zlib");

const pipeline = promisify(stream.pipeline);

const win32BatPath = path.join(__dirname, "build-openssl.bat");
const vendorPath = path.resolve(__dirname, "..", "vendor");
const distrosFilePath = path.join(vendorPath, "static_config", "openssl_distributions.json");
const extractPath = path.join(vendorPath, "openssl");

// TODO: Determine if we are GYPing in Debug
const getIsDebug = () => false;

const getOpenSSLSourceUrl = (version) => `https://www.openssl.org/source/openssl-${version}.tar.gz`;
const getOpenSSLSourceSha256Url = (version) => `${getOpenSSLSourceUrl(version)}.sha256`;

class HashVerify extends stream.Transform {
  constructor(algorithm, expected) {
    super();
    this.expected = expected;
    this.hash = crypto.createHash(algorithm);
  }

  _transform(chunk, encoding, callback) {
    this.hash.update(chunk, encoding);
    callback(null, chunk);
  }

  _final(callback) {
    const digest = this.hash.digest("hex");
    const digestOk = digest === this.expected;
    callback(digestOk ? null : new Error(`Digest not OK: ${digest} !== ${this.expected}`));
  }
}

const buildDarwin = async (buildCwd, macOsDeploymentTarget) => {
  await execPromise(`./Configure darwin64-x86_64-cc shared enable-ec_nistp_64_gcc_128 no-ssl2 no-ssl3 no-comp --prefix="${
    extractPath
  }" --openssldir="${extractPath}" -mmacosx-version-min=${macOsDeploymentTarget}`, {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make", {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make test", {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make install", {
    cwd: buildCwd,
    maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
  }, { pipeOutput: true });
};

const buildWin32 = async (buildCwd) => {
  const vcvarsallPath = process.env.npm_config_vcvarsall_path || `${
    process.env.ProgramFiles || "C:\\Program Files"
  }\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Auxiliary\\Build\\vcvarsall.bat`;
  try {
    await fs.stat(vcvarsallPath);
  } catch {
    throw new Error(`vcvarsall.bat not found at ${vcvarsallPath}`);
  }

  const vcvarsallArch = process.arch === "x64" ? "x64" : "x86";
  const vcTarget = process.arch === "x64" ? "VC-WIN64A" : "VC-WIN32";
  await execPromise(`"${win32BatPath}" "${vcvarsallPath}" ${vcvarsallArch} ${vcTarget}`, {
    cwd: buildCwd,
    maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
  }, { pipeOutput: true });
};

const removeOpenSSLIfOudated = async (openSSLVersion) => {
  try {
    let openSSLResult;
    try {
      const openSSLPath = path.join(extractPath, 'bin', 'openssl');
      openSSLResult = await execPromise(`${openSSLPath} version`);
    } catch {
      /* if we fail to get the version, assume removal not required */
    }

    if (!openSSLResult) {
      return;
    }

    const versionMatch = openSSLResult.match(/^OpenSSL (\d\.\d\.\d[a-z]*)/);
    const installedVersion = versionMatch && versionMatch[1];
    if (!installedVersion || installedVersion === openSSLVersion) {
      return;
    }

    console.log("Removing outdated OpenSSL at: ", extractPath);
    await fse.remove(extractPath);
    console.log("Outdated OpenSSL removed.");
  } catch (err) {
    console.log("Remove outdated OpenSSL failed: ", err);
  }
};

const buildOpenSSLIfNecessary = async (openSSLVersion, macOsDeploymentTarget) => {
  if (process.platform !== "darwin" && process.platform !== "win32") {
    console.log(`Skipping OpenSSL build, not required on ${process.platform}`);
    return;
  }

  await removeOpenSSLIfOudated(openSSLVersion);

  try {
    await fs.stat(extractPath);
    console.log("Skipping OpenSSL build, dir exists");
    return;
  } catch {}

  const openSSLUrl = getOpenSSLSourceUrl(openSSLVersion);
  const openSSLSha256Url = getOpenSSLSourceSha256Url(openSSLVersion);

  const openSSLSha256 = (await got(openSSLSha256Url)).body.trim();

  const downloadStream = got.stream(openSSLUrl);
  let lastReport = performance.now();
  downloadStream.on("downloadProgress", ({ percent, transferred, total }) => {
    const currentTime = performance.now();
    if (currentTime - lastReport > 1 * 1000) {
      lastReport = currentTime;
      console.log(`progress: ${transferred}/${total} (${(percent * 100).toFixed(2)}%)`)
    }
  });

  await pipeline(
    downloadStream,
    new HashVerify("sha256", openSSLSha256),
    zlib.createGunzip(),
    tar.extract(extractPath)
  );

  console.log(`OpenSSL ${openSSLVersion} download + extract complete: SHA256 OK.`);

  const buildCwd = path.join(extractPath, `openssl-${openSSLVersion}`);

  if (process.platform === "darwin") {
    await buildDarwin(buildCwd, macOsDeploymentTarget);
  } else if (process.platform === "win32") {
    await buildWin32(buildCwd);
  } else {
    throw new Error(`Unknown platform: ${process.platform}`);
  }

  console.log("Build finished.");
}

const acquireOpenSSL = async () => {
  try {
    let macOsDeploymentTarget;
    if (process.platform === "darwin") {
      macOsDeploymentTarget = process.argv[2];
      if (!macOsDeploymentTarget || !macOsDeploymentTarget.match(/\d+\.\d+/)) {
        throw new Error(`Invalid macOsDeploymentTarget: ${macOsDeploymentTarget}`);
      }
    }

    await buildOpenSSLIfNecessary("1.1.1l", macOsDeploymentTarget);
  } catch (err) {
    console.error("Acquire failed: ", err);
    process.exit(1);
  }
};

acquireOpenSSL();
<commit_msg>Remove unused code<commit_after>const crypto = require("crypto");
const execPromise = require("./execPromise");
// for fs.remove. replace with fs.rm after dropping v12 support
const fse = require("fs-extra");
const fsNonPromise = require("fs");
const { promises: fs } = fsNonPromise;
const path = require("path");
const got = require("got");
const { performance } = require("perf_hooks");
const { promisify } = require("util");
const stream = require("stream");
const tar = require("tar-fs");
const zlib = require("zlib");

const pipeline = promisify(stream.pipeline);

const win32BatPath = path.join(__dirname, "build-openssl.bat");
const vendorPath = path.resolve(__dirname, "..", "vendor");
const extractPath = path.join(vendorPath, "openssl");

const getOpenSSLSourceUrl = (version) => `https://www.openssl.org/source/openssl-${version}.tar.gz`;
const getOpenSSLSourceSha256Url = (version) => `${getOpenSSLSourceUrl(version)}.sha256`;

class HashVerify extends stream.Transform {
  constructor(algorithm, expected) {
    super();
    this.expected = expected;
    this.hash = crypto.createHash(algorithm);
  }

  _transform(chunk, encoding, callback) {
    this.hash.update(chunk, encoding);
    callback(null, chunk);
  }

  _final(callback) {
    const digest = this.hash.digest("hex");
    const digestOk = digest === this.expected;
    callback(digestOk ? null : new Error(`Digest not OK: ${digest} !== ${this.expected}`));
  }
}

const buildDarwin = async (buildCwd, macOsDeploymentTarget) => {
  await execPromise(`./Configure darwin64-x86_64-cc shared enable-ec_nistp_64_gcc_128 no-ssl2 no-ssl3 no-comp --prefix="${
    extractPath
  }" --openssldir="${extractPath}" -mmacosx-version-min=${macOsDeploymentTarget}`, {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make", {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make test", {
    cwd: buildCwd
  }, { pipeOutput: true });

  await execPromise("make install", {
    cwd: buildCwd,
    maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
  }, { pipeOutput: true });
};

const buildWin32 = async (buildCwd) => {
  const vcvarsallPath = process.env.npm_config_vcvarsall_path || `${
    process.env.ProgramFiles || "C:\\Program Files"
  }\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Auxiliary\\Build\\vcvarsall.bat`;
  try {
    await fs.stat(vcvarsallPath);
  } catch {
    throw new Error(`vcvarsall.bat not found at ${vcvarsallPath}`);
  }

  const vcvarsallArch = process.arch === "x64" ? "x64" : "x86";
  const vcTarget = process.arch === "x64" ? "VC-WIN64A" : "VC-WIN32";
  await execPromise(`"${win32BatPath}" "${vcvarsallPath}" ${vcvarsallArch} ${vcTarget}`, {
    cwd: buildCwd,
    maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
  }, { pipeOutput: true });
};

const removeOpenSSLIfOudated = async (openSSLVersion) => {
  try {
    let openSSLResult;
    try {
      const openSSLPath = path.join(extractPath, 'bin', 'openssl');
      openSSLResult = await execPromise(`${openSSLPath} version`);
    } catch {
      /* if we fail to get the version, assume removal not required */
    }

    if (!openSSLResult) {
      return;
    }

    const versionMatch = openSSLResult.match(/^OpenSSL (\d\.\d\.\d[a-z]*)/);
    const installedVersion = versionMatch && versionMatch[1];
    if (!installedVersion || installedVersion === openSSLVersion) {
      return;
    }

    console.log("Removing outdated OpenSSL at: ", extractPath);
    await fse.remove(extractPath);
    console.log("Outdated OpenSSL removed.");
  } catch (err) {
    console.log("Remove outdated OpenSSL failed: ", err);
  }
};

const buildOpenSSLIfNecessary = async (openSSLVersion, macOsDeploymentTarget) => {
  if (process.platform !== "darwin" && process.platform !== "win32") {
    console.log(`Skipping OpenSSL build, not required on ${process.platform}`);
    return;
  }

  await removeOpenSSLIfOudated(openSSLVersion);

  try {
    await fs.stat(extractPath);
    console.log("Skipping OpenSSL build, dir exists");
    return;
  } catch {}

  const openSSLUrl = getOpenSSLSourceUrl(openSSLVersion);
  const openSSLSha256Url = getOpenSSLSourceSha256Url(openSSLVersion);

  const openSSLSha256 = (await got(openSSLSha256Url)).body.trim();

  const downloadStream = got.stream(openSSLUrl);
  let lastReport = performance.now();
  downloadStream.on("downloadProgress", ({ percent, transferred, total }) => {
    const currentTime = performance.now();
    if (currentTime - lastReport > 1 * 1000) {
      lastReport = currentTime;
      console.log(`progress: ${transferred}/${total} (${(percent * 100).toFixed(2)}%)`)
    }
  });

  await pipeline(
    downloadStream,
    new HashVerify("sha256", openSSLSha256),
    zlib.createGunzip(),
    tar.extract(extractPath)
  );

  console.log(`OpenSSL ${openSSLVersion} download + extract complete: SHA256 OK.`);

  const buildCwd = path.join(extractPath, `openssl-${openSSLVersion}`);

  if (process.platform === "darwin") {
    await buildDarwin(buildCwd, macOsDeploymentTarget);
  } else if (process.platform === "win32") {
    await buildWin32(buildCwd);
  } else {
    throw new Error(`Unknown platform: ${process.platform}`);
  }

  console.log("Build finished.");
}

const acquireOpenSSL = async () => {
  try {
    let macOsDeploymentTarget;
    if (process.platform === "darwin") {
      macOsDeploymentTarget = process.argv[2];
      if (!macOsDeploymentTarget || !macOsDeploymentTarget.match(/\d+\.\d+/)) {
        throw new Error(`Invalid macOsDeploymentTarget: ${macOsDeploymentTarget}`);
      }
    }

    await buildOpenSSLIfNecessary("1.1.1l", macOsDeploymentTarget);
  } catch (err) {
    console.error("Acquire failed: ", err);
    process.exit(1);
  }
};

acquireOpenSSL();
<|endoftext|>


<commit_before>var typeOf = require('component-type')

module.exports = castFromString

function castFromString (string, to) {
  if (castTo[to]) return castTo[to](string)
  throw new Error('Invalid cast type.')
}

var castTo = {
  array: function (string) {
    if (typeOf(string) === 'string') {
      if (string === '') return []
      return string.split(',')
    }
    throw new Error('Should be a string of values separated by commas.')
  },

  boolean: function (string) {
    if (string === 'true') return true
    if (string === 'false') return false
    throw new Error('Should be a boolean written as string.')
  },

  number: function (string) {
    var number = parseInt(string, 10)
    if (typeOf(number) === 'number') return number
    throw new Error('Should be a number written as string.')
  },

  string: function (string) {
    if (typeOf(string) === 'string') return string
    throw new Error('Should be string.')
  },

  object: function (string) {
    try {
      return JSON.parse(string)
    } catch (err) {
      throw new Error('Should be object.')
    }
  }
}
<commit_msg>check if JSON value is object, dont collide with arrays<commit_after>var typeOf = require('component-type')

module.exports = castFromString

function castFromString (string, to) {
  if (castTo[to]) return castTo[to](string)
  throw new Error('Invalid cast type.')
}

var castTo = {
  array: function (string) {
    if (typeOf(string) === 'string') {
      if (string === '') return []
      return string.split(',')
    }
    throw new Error('Should be a string of values separated by commas.')
  },

  boolean: function (string) {
    if (string === 'true') return true
    if (string === 'false') return false
    throw new Error('Should be a boolean written as string.')
  },

  number: function (string) {
    var number = parseInt(string, 10)
    if (typeOf(number) === 'number') return number
    throw new Error('Should be a number written as string.')
  },

  string: function (string) {
    if (typeOf(string) === 'string') return string
    throw new Error('Should be string.')
  },

  object: function (string) {
    try {
      var value = JSON.parse(string)
      if (typeOf(value) === 'object') return value
      throw new Error('Should be a JSON object written as a string.')
    } catch (err) {
      throw new Error('Should be a JSON object written as a string.')
    }
  }
}
<|endoftext|>


<commit_before>/**
 * We.js controller class
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default crud actions
 */
Controller.prototype.find = function findAll(req, res, next) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    if (!record) return next();

    res.locals.metadata.count = record.count;
    res.locals.record = record.rows;

    return res.ok();
  });
}

Controller.prototype.create = function create(req, res) {
  var we = req.getWe();

  req.body.creatorId = req.user.id;

  return res.locals.Model.create(req.body)
  .then(function (record) {
    // generate a unique url
    we.url.generate(req, res, record, function(err, url) {
      if (err) {
        we.log.error(err);
        res.addMessage('error', err);
      }

      res.locals.metadata.url = url;
      return res.created(record);
    })
  });
}

/**
 * Default findOne action
 *
 * Record is preloaded in context by default
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  var we = req.getWe();

  if (!res.locals.record) return next();

  if (res.locals.fieldTitle)
    res.locals.title = res.locals.record[res.locals.fieldTitle];

  we.hooks.trigger('we:after:send:ok:response', {
    res: res,
    req: req
  }, function (err) {
    if (err) return res.serverError(err);
    return res.ok();
  });
};

Controller.prototype.update = function update(req, res) {
  if(!res.locals.record) return res.notFound();

  res.locals.record.updateAttributes(req.body)
  .then(function() {
    return res.ok();
  });
};

Controller.prototype.destroy = function destroy(req, res) {
  var id = req.params.id;

  res.locals.Model.findById(id)
  .then(function (record) {
    if (!record) return res.notFound();

    record.destroy(req.body)
    .then(function() {
      return res.deleted();
    });
  });
};

Controller.prototype.createPage = function createPage(req, res, next) {
  if (!res.locals.template)
    res.locals.template = res.locals.model + '/' + 'createPage';
  if (!res.locals.record) res.locals.record = {};

   _.merge(res.locals.record, req.query);

  if (req.method === 'POST') {

    req.body.creatorId = req.user.id;
    // set temp record for use in validation errors
    res.locals.record = req.query;
    _.merge(res.locals.record, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {

      res.locals.record = record;
      if (res.locals.responseType == 'html')
        return res.redirect('/' + res.locals.model + '/' +record.id);

      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.record = req.query;

    res.responseMethod = 'ok';
    next();
  }
};

Controller.prototype.editPage = function editPage(req, res, next) {
  if (!res.locals.template) {
    res.locals.template = res.local.model + '/' + 'editPage';
  }

  if (req.method === 'GET') {
    res.responseMethod = 'ok';
    next();
  } else if (req.method === 'POST') {
    var record = res.locals.record;

    if (!record) {
      return res.notFound();
    }

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.record = record;

      if (res.locals.responseType == 'html') {
        return res.redirect('/' + res.locals.model + '/' +record.id);
      }

      return res.ok();
    }).catch(res.queryError);
  }
};

Controller.prototype.getAttribute = function getAttribute(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.updateAttribute = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.deleteAttribute = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.addRecord = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.removeRecord = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.getRecord = function(req, res, next) {
  console.log('TODO');  next();
};

module.exports = Controller;
<commit_msg>update editPage to remove redirect<commit_after>/**
 * We.js controller class
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default crud actions
 */
Controller.prototype.find = function findAll(req, res, next) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    if (!record) return next();

    res.locals.metadata.count = record.count;
    res.locals.record = record.rows;

    return res.ok();
  });
}

Controller.prototype.create = function create(req, res) {
  var we = req.getWe();

  req.body.creatorId = req.user.id;

  return res.locals.Model.create(req.body)
  .then(function (record) {
    // generate a unique url
    we.url.generate(req, res, record, function(err, url) {
      if (err) {
        we.log.error(err);
        res.addMessage('error', err);
      }

      res.locals.metadata.url = url;
      return res.created(record);
    })
  });
}

/**
 * Default findOne action
 *
 * Record is preloaded in context by default
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  var we = req.getWe();

  if (!res.locals.record) return next();

  if (res.locals.fieldTitle)
    res.locals.title = res.locals.record[res.locals.fieldTitle];

  we.hooks.trigger('we:after:send:ok:response', {
    res: res,
    req: req
  }, function (err) {
    if (err) return res.serverError(err);
    return res.ok();
  });
};

Controller.prototype.update = function update(req, res) {
  if(!res.locals.record) return res.notFound();

  res.locals.record.updateAttributes(req.body)
  .then(function() {
    return res.ok();
  });
};

Controller.prototype.destroy = function destroy(req, res) {
  var id = req.params.id;

  res.locals.Model.findById(id)
  .then(function (record) {
    if (!record) return res.notFound();

    record.destroy(req.body)
    .then(function() {
      return res.deleted();
    });
  });
};

Controller.prototype.createPage = function createPage(req, res, next) {
  if (!res.locals.template)
    res.locals.template = res.locals.model + '/' + 'createPage';
  if (!res.locals.record) res.locals.record = {};

   _.merge(res.locals.record, req.query);

  if (req.method === 'POST') {

    req.body.creatorId = req.user.id;
    // set temp record for use in validation errors
    res.locals.record = req.query;
    _.merge(res.locals.record, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {

      res.locals.record = record;
      if (res.locals.responseType == 'html')
        return res.redirect('/' + res.locals.model + '/' +record.id);

      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.record = req.query;

    res.responseMethod = 'ok';
    next();
  }
};

Controller.prototype.editPage = function editPage(req, res, next) {
  if (!res.locals.template) {
    res.locals.template = res.local.model + '/' + 'editPage';
  }

  if (req.method === 'GET') {
    res.responseMethod = 'ok';
    next();
  } else if (req.method === 'POST') {
    var record = res.locals.record;

    if (!record) {
      return res.notFound();
    }

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.record = record;
      return res.ok();
    }).catch(res.queryError);
  }
};

Controller.prototype.getAttribute = function getAttribute(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.updateAttribute = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.deleteAttribute = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.addRecord = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.removeRecord = function(req, res, next) {
  console.log('TODO');  next();
};

Controller.prototype.getRecord = function(req, res, next) {
  console.log('TODO');  next();
};

module.exports = Controller;
<|endoftext|>


<commit_before>"use strict";

module.exports = EconItem;

function EconItem(item) {
	for (let thing in item) {
		if (item.hasOwnProperty(thing)) {
			this[thing] = item[thing];
		}
	}

	if (this.id || this.assetid) {
		this.assetid = this.id = (this.id || this.assetid).toString();
	} else if (this.currencyid) {
		this.currencyid = this.currencyid.toString();
	}

	this.appid = this.appid ? parseInt(this.appid, 10) : 0;
	this.classid = this.classid.toString();
	this.instanceid = (this.instanceid || 0).toString();
	this.amount = this.amount ? parseInt(this.amount, 10) : 1;
	this.contextid = this.contextid.toString();

	this.fraudwarnings = fixArray(this.fraudwarnings);
	this.descriptions = fixArray(this.descriptions);
	this.owner_descriptions = fixArray(this.owner_descriptions);
	this.actions = fixArray(this.actions);
	this.owner_actions = fixArray(this.owner_actions);
	this.market_actions = fixArray(this.market_actions);
	this.tags = fixTags(this.tags);

	this.tradable = !!parseInt(this.tradable, 10);
	this.marketable = !!parseInt(this.marketable, 10);
	this.commodity = !!parseInt(this.commodity, 10);
	this.market_tradable_restriction = (this.market_tradable_restriction ? parseInt(this.market_tradable_restriction, 10) : 0);
	this.market_marketable_restriction = (this.market_marketable_restriction ? parseInt(this.market_marketable_restriction, 10) : 0);
}

function fixArray(obj) {
	if (typeof obj === 'undefined' || obj == '') {
		return [];
	}

	var array = [];
	for (var i in obj) {
		if (obj.hasOwnProperty(i)) {
			array[i] = obj[i];
		}
	}

	return array;
}

function fixTags(tags) {
	if (!(tags instanceof Array)) {
		tags = fixArray(tags);
	}

	return tags.map((tag) => {
		// tag.internal_name is always present
		// tag.category is always present
		tag.name = tag.localized_tag_name = (tag.localized_tag_name || tag.name);
		tag.color = tag.color || "";
		tag.category_name = tag.localized_category_name = (tag.localized_category_name || tag.category_name);
		return tag;
	});
}

EconItem.prototype.getImageURL = function() {
	return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url + "/";
};

EconItem.prototype.getLargeImageURL = function() {
	if (!this.icon_url_large) {
		return this.getImageURL();
	}

	return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url_large + "/";
};

EconItem.prototype.getTag = function(category) {
	if (!this.tags) {
		return null;
	}

	for (let i = 0; i < this.tags.length; i++) {
		if (this.tags[i].category == category) {
			return this.tags[i];
		}
	}

	return null;
};
<commit_msg>Restore market_fee_app if it's missing to EconItem<commit_after>"use strict";

module.exports = EconItem;

function EconItem(item) {
	for (let thing in item) {
		if (item.hasOwnProperty(thing)) {
			this[thing] = item[thing];
		}
	}

	if (this.id || this.assetid) {
		this.assetid = this.id = (this.id || this.assetid).toString();
	} else if (this.currencyid) {
		this.currencyid = this.currencyid.toString();
	}

	this.appid = this.appid ? parseInt(this.appid, 10) : 0;
	this.classid = this.classid.toString();
	this.instanceid = (this.instanceid || 0).toString();
	this.amount = this.amount ? parseInt(this.amount, 10) : 1;
	this.contextid = this.contextid.toString();

	this.fraudwarnings = fixArray(this.fraudwarnings);
	this.descriptions = fixArray(this.descriptions);
	this.owner_descriptions = fixArray(this.owner_descriptions);
	this.actions = fixArray(this.actions);
	this.owner_actions = fixArray(this.owner_actions);
	this.market_actions = fixArray(this.market_actions);
	this.tags = fixTags(this.tags);

	this.tradable = !!parseInt(this.tradable, 10);
	this.marketable = !!parseInt(this.marketable, 10);
	this.commodity = !!parseInt(this.commodity, 10);
	this.market_tradable_restriction = (this.market_tradable_restriction ? parseInt(this.market_tradable_restriction, 10) : 0);
	this.market_marketable_restriction = (this.market_marketable_restriction ? parseInt(this.market_marketable_restriction, 10) : 0);

	if (this.appid == 753 && !this.market_fee_app && this.market_hash_name) {
		var match = this.market_hash_name.match(/^(\d+)\-/);
		if (match) {
			this.market_fee_app = parseInt(match[1], 10);
		}
	}
}

function fixArray(obj) {
	if (typeof obj === 'undefined' || obj == '') {
		return [];
	}

	var array = [];
	for (var i in obj) {
		if (obj.hasOwnProperty(i)) {
			array[i] = obj[i];
		}
	}

	return array;
}

function fixTags(tags) {
	if (!(tags instanceof Array)) {
		tags = fixArray(tags);
	}

	return tags.map((tag) => {
		// tag.internal_name is always present
		// tag.category is always present
		tag.name = tag.localized_tag_name = (tag.localized_tag_name || tag.name);
		tag.color = tag.color || "";
		tag.category_name = tag.localized_category_name = (tag.localized_category_name || tag.category_name);
		return tag;
	});
}

EconItem.prototype.getImageURL = function() {
	return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url + "/";
};

EconItem.prototype.getLargeImageURL = function() {
	if (!this.icon_url_large) {
		return this.getImageURL();
	}

	return "https://steamcommunity-a.akamaihd.net/economy/image/" + this.icon_url_large + "/";
};

EconItem.prototype.getTag = function(category) {
	if (!this.tags) {
		return null;
	}

	for (let i = 0; i < this.tags.length; i++) {
		if (this.tags[i].category == category) {
			return this.tags[i];
		}
	}

	return null;
};
<|endoftext|>


<commit_before>/**
 * @module byrd/client-transport
 */

'use strict';

var util = require('util');
var kademlia = require('kad');
var ByrdContact = require('./contact');

util.inherits(ByrdClientTransport, kademlia.RPC);

function ByrdClientTransport(options) {
  kademlia.RPC.call(this, options);
}

ByrdClientTransport.prototype._send = function(data, contact) {
  var self = this;
  var xhr = new XMLHttpRequest();
  var url = contact.protocol + '://' + contact.address + ':' + contact.port;

  xhr.addEventListener('load', function() {
    var json;

    if (xhr.status !== 200 && xhr.status !== 304) {
      return self._handleMessage(null);
    }

    self._handleMessage(new Buffer(xhr.responseText), {});
  });

  xhr.open('POST', url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(data.toString());
};

ByrdClientTransport.prototype._createContact = function(options) {
  return new ByrdContact(options);
};

ByrdClientTransport.prototype._close = function() {
  return;
};

module.exports = ByrdClientTransport;
<commit_msg>try/catch xhr send<commit_after>/**
 * @module byrd/client-transport
 */

'use strict';

var util = require('util');
var kademlia = require('kad');
var ByrdContact = require('./contact');

util.inherits(ByrdClientTransport, kademlia.RPC);

function ByrdClientTransport(options) {
  kademlia.RPC.call(this, options);
}

ByrdClientTransport.prototype._send = function(data, contact) {
  var self = this;
  var xhr = new XMLHttpRequest();
  var url = contact.protocol + '://' + contact.address + ':' + contact.port;

  xhr.addEventListener('load', function() {
    var json;

    if (xhr.status !== 200 && xhr.status !== 304) {
      return self._handleMessage(null);
    }

    self._handleMessage(new Buffer(xhr.responseText), {});
  });

  try {
    xhr.open('POST', url);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(data.toString());
  } catch(err) {
    self._handleMessage(null);
  }
};

ByrdClientTransport.prototype._createContact = function(options) {
  return new ByrdContact(options);
};

ByrdClientTransport.prototype._close = function() {
  return;
};

module.exports = ByrdClientTransport;
<|endoftext|>