<commit_before>/*
 * bin.js: Utilties for parsing command line arguments for haibu bin scripts.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    utils = require('./index');

var bin = exports;

//
// ### function getAddress (address, callback)
// #### @address {string} **Optional** Explicit address to use
// #### @callback {function} Continuation to respond to when complete
// Attempts to get the address for the current machine, if and explicit
// `address` is supplied, it will be eagerly supplied.
//
bin.getAddress = function (address, callback) {
  if (!callback) {
    callback = address;
    address = null;
  }
  else if (address) {
    return callback(null, address);
  }

  utils.getIpAddress(function (err, addr) {
    if (err) {
      addr = '127.0.0.1';
    }

    callback(null, addr);
  });
};

bin.findFile = function findFile(dir, file, callback) {
  var _file = path.join(dir, file)
  fs.stat(_file, function (err, exists) {
    if (exists)
      callback(null, _file)
    else if(dir == '/')
      callback(new Error('could not find '+file))
    else
      return findFile(path.dirname(dir), file, callback)
  })
}

//
// ### function tryLoadCache (cachePath, callback)
// #### @cachePatch {string} Path for the cache file
// #### @callback {function} Continuation to respond to when complete.
// Attempts to load the configuration data in `cachePath` or under
// `haibu/config/cache.json`.
//
bin.tryLoadCache = function (cachePath, callback) {
  if (!callback) {
    callback = cachePath;
    cachePath = null
  }
  function loadFile (cachePath) {
    fs.readFile(cachePath, function (err, data) {
      if (err) {
        return callback(err);
      }

      try {
        data = JSON.parse(data.toString());
        console.error('config/cache.json', data)
        callback(null, data.cache);
      }
      catch (ex) {
        callback(ex);
      }
    });
  }

  if(cachePath)
    return loadFile(cachePath)

  bin.findFile(__dirname, path.join('config', 'cache.json'), function (err, file) {
    if(err)
      return callback(err)
    loadFile(file)
  })
};<commit_msg>[minor] style commit<commit_after>/*
 * bin.js: Utilties for parsing command line arguments for haibu bin scripts.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    utils = require('./index');

var bin = exports;

//
// ### function getAddress (address, callback)
// #### @address {string} **Optional** Explicit address to use
// #### @callback {function} Continuation to respond to when complete
// Attempts to get the address for the current machine, if and explicit
// `address` is supplied, it will be eagerly supplied.
//
bin.getAddress = function (address, callback) {
  if (!callback) {
    callback = address;
    address = null;
  }
  else if (address) {
    return callback(null, address);
  }

  utils.getIpAddress(function (err, addr) {
    if (err) {
      addr = '127.0.0.1';
    }

    callback(null, addr);
  });
};

bin.findFile = function findFile(dir, file, callback) {
  var _file = path.join(dir, file);
  fs.stat(_file, function (err, exists) {
    if (exists)
      callback(null, _file);
    else if(dir == '/')
      callback(new Error('could not find '+file));
    else
      return findFile(path.dirname(dir), file, callback);
  });
}

//
// ### function tryLoadCache (cachePath, callback)
// #### @cachePatch {string} Path for the cache file
// #### @callback {function} Continuation to respond to when complete.
// Attempts to load the configuration data in `cachePath` or under
// `haibu/config/cache.json`.
//
bin.tryLoadCache = function (cachePath, callback) {
  if (!callback) {
    callback = cachePath;
    cachePath = null
  }
  function loadFile (cachePath) {
    fs.readFile(cachePath, function (err, data) {
      if (err) {
        return callback(err);
      }

      try {
        data = JSON.parse(data.toString());
        console.error('config/cache.json', data)
        callback(null, data.cache);
      }
      catch (ex) {
        callback(ex);
      }
    });
  }

  if(cachePath)
    return loadFile(cachePath)

  bin.findFile(__dirname, path.join('config', 'cache.json'), function (err, file) {
    if(err)
      return callback(err)
    loadFile(file)
  })
};<|endoftext|>


<commit_before>define(
  ['collection-interactions', 'collection-datasuitcases', 'collection-forms', 'collection-pending', 'feature!data', 'api', 'collection-stars', 'domReady'],
  function (InteractionCollection, DataSuitcaseCollection, FormCollection, PendingCollection, Data, API, StarsCollection, domReady) {
    "use strict";
    var Application = Backbone.Model.extend({

      initialize: function () {
        var app = this;
        BMP.FileInput.initialize();
        require(['router'], function (router) {
          app.set({
            _id: window.BMP.BIC.siteVars.answerSpace
          });

          app.on('change', app.update);

          app.data = new Data(window.BMP.BIC.siteVars.answerSpace + '-AnswerSpace');

          app.interactions = new InteractionCollection();
          app.datasuitcases = new DataSuitcaseCollection();
          app.forms = new FormCollection();
          app.pending = new PendingCollection();
          app.stars = new StarsCollection();

          app.router = router;
          $(document).on('pagebeforeload', function (e, data) {
            e.preventDefault();
            $.mobile.loading('show');
            if (app.has('currentInteraction') && app.get('currentInteraction').get('dbid') === "i" + app.get('loginPromptInteraction')) {
              app.checkLoginStatus().then(function () {
                app.router.routeRequest(data);
              });
            } else {
              app.router.routeRequest(data);
            }
          });

          $.when(
            app.interactions.initialize,
            app.datasuitcases.initialize,
            app.forms.initialize,
            app.pending.initialize,
            app.stars.initialize
          ).always(function () {
            if (navigator.onLine) {
              app.populate().done(function () {
                app.initialRender();
              });
            } else {
              app.fetch({
                success: function () {
                  app.initialRender();
                },
                error: function () {
                  app.populate().done(function () {
                    app.initialRender();
                  });
                }
              });
            }
          });
        });
      },

      idAttribute: "_id",

      defaults: {
        loginStatus: false
      },

      populate: function () {
        var app = this,
          dfrd = new $.Deferred(),
          promise = dfrd.promise();

        API.getAnswerSpaceMap().then(
          function (data) {
            var models = [];
            _.each(data, function (value, key) {
              var model;
              if (key.substr(0, 1) === 'c' || key.substr(0, 1) === 'i') {
                model = value.pertinent;
                model._id = model.name;
                model.dbid = key;
                models.push(model);
              }
              if (key.substr(0, 1) === 'a') {
                model = {
                  _id: window.BMP.BIC.siteVars.answerSpace,
                  dbid: key
                };
                models.push(model);

                app.save(value.pertinent);
              }
            }, app);

            app.interactions.set(models).save();
            _.each(_.compact(_.uniq(app.interactions.pluck('xml'))), function (element) {
              if (!app.datasuitcases.get(element)) {
                app.datasuitcases.create({_id: element}, {success: function (model) {
                  model.populate();
                }});
              } else {
                if (navigator.onLine) {
                  app.datasuitcases.get(element).populate();
                }
              }
            });

            app.trigger("initialize");
            dfrd.resolve();
          },
          function () {
            dfrd.reject();
          }
        );
        return promise;
      },

      checkLoginStatus: function () {
        //false
        var app = this,
          dfrd = $.Deferred();

        API.getLoginStatus().then(function (data) {
          var status = data.status || data;
          if (app.get('loginStatus') !== status) {
            app.interactions.reset();
            app.datasuitcases.reset();
            app.forms.reset();
            app.populate().then(function () {
              app.set({loginStatus: status});
              dfrd.resolve();
            });
          } else {
            dfrd.resolve();
          }
        });

        return dfrd.promise();
      },

      initialRender: function () {
        var app = this;
        $.mobile.defaultPageTransition = app.get("defaultTransition");
        domReady(function () {
          $.mobile.changePage($.mobile.path.parseLocation().pathname, {
            changeHash: false,
            reloadPage: true,
            transition: 'fade'
          });
          $(document).on('pageshow', function () {
            $('#temp').remove();
          });
        });
      }
    });

    window.BMP.BIC3 = new Application();

    return window.BMP.BIC3;
  }
);
<commit_msg>Use href instead of pathname in initial render so as to maintain URL arguments through application boot<commit_after>define(
  ['collection-interactions', 'collection-datasuitcases', 'collection-forms', 'collection-pending', 'feature!data', 'api', 'collection-stars', 'domReady'],
  function (InteractionCollection, DataSuitcaseCollection, FormCollection, PendingCollection, Data, API, StarsCollection, domReady) {
    "use strict";
    var Application = Backbone.Model.extend({

      initialize: function () {
        var app = this;
        BMP.FileInput.initialize();
        require(['router'], function (router) {
          app.set({
            _id: window.BMP.BIC.siteVars.answerSpace
          });

          app.on('change', app.update);

          app.data = new Data(window.BMP.BIC.siteVars.answerSpace + '-AnswerSpace');

          app.interactions = new InteractionCollection();
          app.datasuitcases = new DataSuitcaseCollection();
          app.forms = new FormCollection();
          app.pending = new PendingCollection();
          app.stars = new StarsCollection();

          app.router = router;
          $(document).on('pagebeforeload', function (e, data) {
            e.preventDefault();
            $.mobile.loading('show');
            if (app.has('currentInteraction') && app.get('currentInteraction').get('dbid') === "i" + app.get('loginPromptInteraction')) {
              app.checkLoginStatus().then(function () {
                app.router.routeRequest(data);
              });
            } else {
              app.router.routeRequest(data);
            }
          });

          $.when(
            app.interactions.initialize,
            app.datasuitcases.initialize,
            app.forms.initialize,
            app.pending.initialize,
            app.stars.initialize
          ).always(function () {
            if (navigator.onLine) {
              app.populate().done(function () {
                app.initialRender();
              });
            } else {
              app.fetch({
                success: function () {
                  app.initialRender();
                },
                error: function () {
                  app.populate().done(function () {
                    app.initialRender();
                  });
                }
              });
            }
          });
        });
      },

      idAttribute: "_id",

      defaults: {
        loginStatus: false
      },

      populate: function () {
        var app = this,
          dfrd = new $.Deferred(),
          promise = dfrd.promise();

        API.getAnswerSpaceMap().then(
          function (data) {
            var models = [];
            _.each(data, function (value, key) {
              var model;
              if (key.substr(0, 1) === 'c' || key.substr(0, 1) === 'i') {
                model = value.pertinent;
                model._id = model.name;
                model.dbid = key;
                models.push(model);
              }
              if (key.substr(0, 1) === 'a') {
                model = {
                  _id: window.BMP.BIC.siteVars.answerSpace,
                  dbid: key
                };
                models.push(model);

                app.save(value.pertinent);
              }
            }, app);

            app.interactions.set(models).save();
            _.each(_.compact(_.uniq(app.interactions.pluck('xml'))), function (element) {
              if (!app.datasuitcases.get(element)) {
                app.datasuitcases.create({_id: element}, {success: function (model) {
                  model.populate();
                }});
              } else {
                if (navigator.onLine) {
                  app.datasuitcases.get(element).populate();
                }
              }
            });

            app.trigger("initialize");
            dfrd.resolve();
          },
          function () {
            dfrd.reject();
          }
        );
        return promise;
      },

      checkLoginStatus: function () {
        //false
        var app = this,
          dfrd = $.Deferred();

        API.getLoginStatus().then(function (data) {
          var status = data.status || data;
          if (app.get('loginStatus') !== status) {
            app.interactions.reset();
            app.datasuitcases.reset();
            app.forms.reset();
            app.populate().then(function () {
              app.set({loginStatus: status});
              dfrd.resolve();
            });
          } else {
            dfrd.resolve();
          }
        });

        return dfrd.promise();
      },

      initialRender: function () {
        var app = this;
        $.mobile.defaultPageTransition = app.get("defaultTransition");
        domReady(function () {
          $.mobile.changePage($.mobile.path.parseLocation().href, {
            changeHash: false,
            reloadPage: true,
            transition: 'fade'
          });
          $(document).on('pageshow', function () {
            $('#temp').remove();
          });
        });
      }
    });

    window.BMP.BIC3 = new Application();

    return window.BMP.BIC3;
  }
);
<|endoftext|>


<commit_before>'use strict';

const Prometheus = require('prom-client');
const cloneDeep = require('lodash.clonedeep');

// Prometheus metrics implementation
class PrometheusMetric {
    constructor(options, client) {
        this.client = client;
        this.options = cloneDeep(options);
        if (this.options.labels === undefined) {
            this.options.labels = { names: [] };
        }
        this.staticLabels = this.options.prometheus.staticLabels;
        if (this.staticLabels !== undefined) {
            if (Object.keys(this.staticLabels).length > 0) {
                Object.keys(this.staticLabels).forEach((name) => {
                    this.options.labels.names.unshift(name);
                    this.staticLabels[name] = this._normalize(this.staticLabels[name]);
                });
            }
        }
        this.options.prometheus.name = this._normalize(this.options.prometheus.name);
        this.options.prometheus.labelNames = this.options.prometheus.labelNames || [];
        this.options.prometheus.labelNames = this.options.prometheus.labelNames
            .map(this._normalize);
        this.metric = new this.client[this.options.type]({
            name: this.options.prometheus.name,
            help: this.options.prometheus.help,
            labelNames: this.options.labels.names,
            buckets: this.options.prometheus.buckets,
            percentiles: this.options.prometheus.percentiles
        });
    }

    _handleStaticLabels(labels) {
        const updatedLabels = [...labels];
        if (this.staticLabels !== undefined) {
            Object.keys(this.staticLabels).forEach((name) => {
                if (updatedLabels.indexOf(this.staticLabels[name]) === -1) {
                    updatedLabels.unshift(this.staticLabels[name]);
                }
            });
        }
        return updatedLabels;
    }

    _normalize(str) {
        return String(str).replace( /\W/g, '_' ) // replace non-alphanumerics
            .replace( /_+/g, '_' ) // dedupe underscores
            .replace( /(^_+|_+$)/g, '' ); // trim leading and trailing underscores
    }

    increment(amount, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.metric.labels.apply(this.metric, updatedLabels).inc(amount);
    }

    decrement(amount, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.metric.labels.apply(this.metric, updatedLabels).dec(amount);
    }

    observe(value, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.metric.labels.apply(this.metric, updatedLabels).observe(value);
    }

    gauge(amount, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        if (amount < 0) {
            this.metric.labels.apply(this.metric, updatedLabels).dec(Math.abs(amount));
        } else {
            this.metric.labels.apply(this.metric, updatedLabels).inc(amount);
        }
    }

    set(value, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.metric.labels.apply(this.metric, updatedLabels).set(value);
    }

    timing(value, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.observe(value, updatedLabels);
    }

    endTiming(startTime, labels) {
        const updatedLabels = this._handleStaticLabels(labels).map(this._normalize);
        this.timing(Date.now() - startTime, updatedLabels);
    }
}

class PrometheusClient {
    constructor(options, logger) {
        this.options = options;
        this.logger = logger;
        this.client = Prometheus;
    }

    makeMetric(options) {
        return new PrometheusMetric(options, this.client);
    }

    close() {}
}

module.exports = PrometheusClient;
<commit_msg>Don't normalize prometheus label values<commit_after>'use strict';

const Prometheus = require('prom-client');
const cloneDeep = require('lodash.clonedeep');

// Prometheus metrics implementation
class PrometheusMetric {
    constructor(options, client) {
        this.client = client;
        this.options = cloneDeep(options);
        if (this.options.labels === undefined) {
            this.options.labels = { names: [] };
        }
        this.staticLabels = this.options.prometheus.staticLabels || {};

        // Add staticLabel names to list of known label names.
        Object.keys(this.staticLabels).forEach((labelName) => {
            this.options.labels.names.unshift(labelName);
        });
        // Normalize all the label names.
        this.options.labels.names = this.options.labels.names.map(this._normalize)

        this.options.prometheus.name = this._normalize(this.options.prometheus.name);
        this.metric = new this.client[this.options.type]({
            name: this.options.prometheus.name,
            help: this.options.prometheus.help,
            labelNames: this.options.labels.names,
            buckets: this.options.prometheus.buckets,
            percentiles: this.options.prometheus.percentiles
        });
    }

    /**
     * Normalizes a prometheus string. Should be used for label
     * and metric names, but is not needed for label values.
     *
     * @param {string} str
     * @return {string}
     */
    _normalize(str) {
        return String(str).replace( /\W/g, '_' ) // replace non-alphanumerics
            .replace( /_+/g, '_' ) // dedupe underscores
            .replace( /(^_+|_+$)/g, '' ); // trim leading and trailing underscores
    }

    /**
     * Gets label values array for this metric
     * including both static and dynamic labels merged together.
     *
     * @param {Array} labelValues
     * @return {Array}
     */
     _getLabelValues(labelValues) {
        // make a clone of labelValues.
        const updatedLabelValues = [...labelValues];
        // Add staticLabel values to updatedLabelValues if they aren't already listed.
        Object.keys(this.staticLabels).forEach((labelName) => {
            if (updatedLabelValues.indexOf(this.staticLabels[labelName]) === -1) {
                updatedLabelValues.unshift(this.staticLabels[labelName]);
            }
        });
        return updatedLabelValues;
    }

    increment(amount, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.metric.labels.apply(this.metric, updatedLabelValues).inc(amount);
    }

    decrement(amount, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.metric.labels.apply(this.metric, updatedLabelValues).dec(amount);
    }

    observe(value, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.metric.labels.apply(this.metric, updatedLabelValues).observe(value);
    }

    gauge(amount, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        if (amount < 0) {
            this.metric.labels.apply(this.metric, updatedLabelValues).dec(Math.abs(amount));
        } else {
            this.metric.labels.apply(this.metric, updatedLabelValues).inc(amount);
        }
    }

    set(value, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.metric.labels.apply(this.metric, updatedLabelValues).set(value);
    }

    timing(value, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.observe(value, updatedLabelValues);
    }

    endTiming(startTime, labelValues) {
        const updatedLabelValues = this._getLabelValues(labelValues);
        this.timing(Date.now() - startTime, updatedLabelValues);
    }
}

class PrometheusClient {
    constructor(options, logger) {
        this.options = options;
        this.logger = logger;
        this.client = Prometheus;
    }

    makeMetric(options) {
        return new PrometheusMetric(options, this.client);
    }

    close() {}
}

module.exports = PrometheusClient;
<|endoftext|>


<commit_before>
module.exports = get

var GET = require("./request").GET
  , fs = require("../graceful-fs")
  , npm = require("../../../npm")
  , path = require("path")
  , log = require("../log")

function get (project, version, timeout, nofollow, cb) {
  if (typeof cb !== "function") cb = nofollow, nofollow = false
  if (typeof cb !== "function") cb = timeout, timeout = -1
  if (typeof cb !== "function") cb = version, version = null
  if (typeof cb !== "function") cb = project, project = null
  if (typeof cb !== "function") {
    throw new Error("No callback provided to registry.get")
  }
  var uri = []
  uri.push(project || "")
  if (version) uri.push(version)
  uri = uri.join("/")
  var cache = path.join(npm.cache, uri, ".cache.json")
  fs.stat(cache, function (er, stat) {
    if (!er) fs.readFile(cache, function (er, data) {
      try { data = JSON.parse(data) }
      catch (ex) { data = null }
      get_(uri, timeout, cache, stat, data, nofollow, cb)
    })
    else get_(uri, timeout, cache, null, null, nofollow, cb)
  })
}
function get_ (uri, timeout, cache, stat, data, nofollow, cb) {
  var etag
  if (data && data._etag) etag = data._etag
  if (timeout && timeout > 0 && stat && data) {
    if ((Date.now() - stat.mtime.getTime())/1000 < timeout) {
      log.verbose("not expired, no request", "registry.get " +uri)
      delete data._etag
      return cb(null, data, JSON.stringify(data), {statusCode:304})
    }
  }
  GET(uri, etag, nofollow, function (er, remoteData, raw, response) {
    if (response) {
      log.silly([response.statusCode, response.headers], "get cb")
      if (response.statusCode === 304 && etag) {
        remoteData = data
        log.verbose("from cache", "etag")
      }
    }
    data = remoteData
    if (er) return cb(er, data, raw, response)
    // just give the write the old college try.  if it fails, whatever.
    fs.writeFile(cache, JSON.stringify(data), function () {})
    delete data._etag
    cb(er, data, raw, response)
  })
}
<commit_msg>Be better about saving cache files.<commit_after>
module.exports = get

var GET = require("./request").GET
  , fs = require("../graceful-fs")
  , npm = require("../../../npm")
  , path = require("path")
  , log = require("../log")
  , mkdir = require("../mkdir-p")

function get (project, version, timeout, nofollow, cb) {
  if (typeof cb !== "function") cb = nofollow, nofollow = false
  if (typeof cb !== "function") cb = timeout, timeout = -1
  if (typeof cb !== "function") cb = version, version = null
  if (typeof cb !== "function") cb = project, project = null
  if (typeof cb !== "function") {
    throw new Error("No callback provided to registry.get")
  }
  var uri = []
  uri.push(project || "")
  if (version) uri.push(version)
  uri = uri.join("/")
  var cache = path.join(npm.cache, uri, ".cache.json")
  fs.stat(cache, function (er, stat) {
    if (!er) fs.readFile(cache, function (er, data) {
      try { data = JSON.parse(data) }
      catch (ex) { data = null }
      get_(uri, timeout, cache, stat, data, nofollow, cb)
    })
    else get_(uri, timeout, cache, null, null, nofollow, cb)
  })
}
function get_ (uri, timeout, cache, stat, data, nofollow, cb) {
  var etag
  if (data && data._etag) etag = data._etag
  if (timeout && timeout > 0 && stat && data) {
    if ((Date.now() - stat.mtime.getTime())/1000 < timeout) {
      log.verbose("not expired, no request", "registry.get " +uri)
      delete data._etag
      return cb(null, data, JSON.stringify(data), {statusCode:304})
    }
  }
  GET(uri, etag, nofollow, function (er, remoteData, raw, response) {
    if (response) {
      log.silly([response.statusCode, response.headers], "get cb")
      if (response.statusCode === 304 && etag) {
        remoteData = data
        log.verbose("from cache", "etag")
      }
    }
    data = remoteData
    if (er) return cb(er, data, raw, response)
    // just give the write the old college try.  if it fails, whatever.
    log.warn(cache, "Writing to cache")
    function saved () {
      delete data._etag
      cb(er, data, raw, response)
    }
    mkdir(path.dirname(cache), 0777, function (er) {
      log.warn(er || cache, "mkdired!")
      if (er) return saved()
      fs.writeFile(cache, JSON.stringify(data), saved)
    })
  })
}
<|endoftext|>


<commit_before>var config
  , path = require('path')
  , fs = require('fs')
  , utils = require('utilities');

config = new (function () {

  this.readConfig = function (options) {
    var opts = options || {}
      , ret = {}
      , baseConfig
      , env
      , dir = process.cwd()
      , dirList = fs.readdirSync(path.join(dir, 'config'))
      , fileName
      , fileExt
      , fileBaseName
      , useCoffee
      , appBaseConfig
      , appEnvConfig
      , secretsFile = path.join(dir, 'config', 'secrets.json')
      , secrets
      , protocol
      , fullHostname;

    baseConfig = utils.mixin({}, require('./base_config'), true);
    env = opts.environment || baseConfig.environment;

    // Base config for workers-count should be 1 in dev-mode
    // Cycle based on filesystem changes, not keep-alive
    // Process-rotation not possible in this mode
    if (env == 'development') {
      baseConfig.workers = 1;
      baseConfig.rotateWorkers = false;
    }

    // App configs
    for (var i = 0; i < dirList.length; i++) {
      fileName = dirList[i];
      fileExt = path.extname(fileName);
      fileBaseName = path.basename(fileName, fileExt);
      // Require the environment configuration and the base configuration file
      if (fileBaseName === env || fileBaseName === 'environment') {
        if (fileExt === '.coffee') {
          // fileName is a CoffeeScript file so try to require it
          useCoffee = useCoffee || utils.file.requireLocal('coffee-script');
        }
        appBaseConfig = require(dir + '/config/environment');
        appEnvConfig = require(dir + '/config/' + env);
      }
    }

    // Start with a blank slate, mix everything in
    utils.mixin(ret, baseConfig, true);
    utils.mixin(ret, appBaseConfig, true);
    utils.mixin(ret, appEnvConfig, true);
    utils.mixin(ret, opts, true);

    // Mix in any app-secrets -- should never be checked into revision control
    if (utils.file.existsSync(secretsFile)) {
      try {
        secrets = JSON.parse(fs.readFileSync(secretsFile));
        utils.mixin(ret, secrets);
      }
      catch (e) {
        throw new Error('Could not parse secrets.json file');
      }
    }

    // Obvious, don't rotate with only one worker
    if (ret.workers < 2) {
      ret.rotateWorkers = false;
    }

    // Construct fullHostname if not specifically set and there's a
    // usable hostname (i.e., not the 'any IPv4 address' option)
    if (!ret.fullHostname && ret.hostname) {
      protocol = ret.ssl ? 'https' : 'http';
      fullHostname = protocol + '://' + ret.hostname;
      if (ret.port != 80) {
        fullHostname += ':' + ret.port;
      }
      ret.fullHostname = fullHostname;
    }

    return ret;
  };

})();

module.exports = config;
<commit_msg>Allow EJS in secrets.json for passing in env vars for Heroku deploy, etc.<commit_after>var config
  , path = require('path')
  , fs = require('fs')
  , utils = require('utilities')
  , ejs = require('./template/engines/ejs');

config = new (function () {

  this.readConfig = function (options) {
    var opts = options || {}
      , ret = {}
      , baseConfig
      , env
      , dir = process.cwd()
      , dirList = fs.readdirSync(path.join(dir, 'config'))
      , fileName
      , fileExt
      , fileBaseName
      , useCoffee
      , appBaseConfig
      , appEnvConfig
      , secretsFile = path.join(dir, 'config', 'secrets.json')
      , secrets
      , protocol
      , fullHostname;

    baseConfig = utils.mixin({}, require('./base_config'), true);
    env = opts.environment || baseConfig.environment;

    // Base config for workers-count should be 1 in dev-mode
    // Cycle based on filesystem changes, not keep-alive
    // Process-rotation not possible in this mode
    if (env == 'development') {
      baseConfig.workers = 1;
      baseConfig.rotateWorkers = false;
    }

    // App configs
    for (var i = 0; i < dirList.length; i++) {
      fileName = dirList[i];
      fileExt = path.extname(fileName);
      fileBaseName = path.basename(fileName, fileExt);
      // Require the environment configuration and the base configuration file
      if (fileBaseName === env || fileBaseName === 'environment') {
        if (fileExt === '.coffee') {
          // fileName is a CoffeeScript file so try to require it
          useCoffee = useCoffee || utils.file.requireLocal('coffee-script');
        }
        appBaseConfig = require(dir + '/config/environment');
        appEnvConfig = require(dir + '/config/' + env);
      }
    }

    // Start with a blank slate, mix everything in
    utils.mixin(ret, baseConfig, true);
    utils.mixin(ret, appBaseConfig, true);
    utils.mixin(ret, appEnvConfig, true);
    utils.mixin(ret, opts, true);

    // Mix in any app-secrets
    if (utils.file.existsSync(secretsFile)) {
      secrets = fs.readFileSync(secretsFile).toString();
      // HACK, allow EJS in JSON, get env vars for deploy-from-Git
      secrets = ejs.render(secrets, {});
      try {
        // Parse into obj and mix in to config
        secrets = JSON.parse(secrets);
      }
      catch (e) {
        throw new Error('Could not parse secrets.json file, ' + e.message);
      }
      utils.mixin(ret, secrets);
    }

    // Obvious, don't rotate with only one worker
    if (ret.workers < 2) {
      ret.rotateWorkers = false;
    }

    // Construct fullHostname if not specifically set and there's a
    // usable hostname (i.e., not the 'any IPv4 address' option)
    if (!ret.fullHostname && ret.hostname) {
      protocol = ret.ssl ? 'https' : 'http';
      fullHostname = protocol + '://' + ret.hostname;
      if (ret.port != 80) {
        fullHostname += ':' + ret.port;
      }
      ret.fullHostname = fullHostname;
    }

    return ret;
  };

})();

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

export default {

  browserPort: 3000,
  UIPort: 3001,

  sourceDir: './app/',
  buildDir: './build/',

  styles: {
    src: 'app/styles/**/*.scss',
    dest: 'build/css',
    prodSourcemap: false,
    sassIncludePaths: []
  },

  scripts: {
    src: 'app/js/**/*.js',
    dest: 'build/js'
  },

  images: {
    src: 'app/images/**/*',
    dest: 'build/images'
  },

  fonts: {
    src: ['app/fonts/**/*'],
    dest: 'build/fonts'
  },

  assetExtensions: [
    'js',
    'css',
    'png',
    'jpe?g',
    'gif',
    'svg',
    'eot',
    'otf',
    'ttc',
    'ttf',
    'woff2?'
  ],

  views: {
    index: 'app/index.html',
    src: 'app/views/**/*.html',
    dest: 'app/js'
  },

  gzip: {
    src: 'build/**/*.{html,xml,json,css,js,js.map,css.map}',
    dest: 'build/',
    options: {}
  },

  browserify: {
    bundleName: 'main.js',
    prodSourcemap: false
  },

  test: {
    karma: 'test/karma.conf.js',
    protractor: 'test/protractor.conf.js'
  },

  init: function() {
    this.views.watch = [
      this.views.index,
      this.views.src
    ];

    return this;
  }

}.init();
<commit_msg>no gzip and always make sourcemaps<commit_after>'use strict';

export default {

  browserPort: 3000,
  UIPort: 3001,

  sourceDir: './app/',
  buildDir: './build/',

  styles: {
    src: 'app/styles/**/*.scss',
    dest: 'build/css',
    prodSourcemap: false,
    sassIncludePaths: []
  },

  scripts: {
    src: 'app/js/**/*.js',
    dest: 'build/js'
  },

  images: {
    src: 'app/images/**/*',
    dest: 'build/images'
  },

  fonts: {
    src: ['app/fonts/**/*'],
    dest: 'build/fonts'
  },

  assetExtensions: [
    'js',
    'css',
    'png',
    'jpe?g',
    'gif',
    'svg',
    'eot',
    'otf',
    'ttc',
    'ttf',
    'woff2?'
  ],

  views: {
    index: 'app/index.html',
    src: 'app/views/**/*.html',
    dest: 'app/js'
  },

  browserify: {
    bundleName: 'main.js',
    prodSourcemap: true
  },

  test: {
    karma: 'test/karma.conf.js',
    protractor: 'test/protractor.conf.js'
  },

  init: function () {
    this.views.watch = [
      this.views.index,
      this.views.src
    ];

    return this;
  }

}.init();
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
        'public/lib/gridster/dist/jquery.gridster.css',
        'public/lib/decksterjs/dist/jquery.deckster.css',
        'public/lib/components-font-awesome/css/font-awesome.css'
      ],
      js: [
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/spin.js/spin.js',
        'public/lib/spin.js/jquery.spin.js',
        'public/lib/gridster/dist/jquery.gridster.min.js',
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/angular-timeago/dist/angular-timeago.js',
        'https://www.google.com/recaptcha/api.js',
        'public/lib/decksterjs/dist/jquery.deckster.js',
        'public/lib/ng-lodash/build/ng-lodash.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<commit_msg>Production fixes, part 2 (html)<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
        'public/lib/gridster/dist/jquery.gridster.css',
        'public/lib/decksterjs/dist/jquery.deckster.css',
        'public/lib/components-font-awesome/css/font-awesome.css'
      ],
      js: [
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/spin.js/spin.js',
        'public/lib/spin.js/jquery.spin.js',
        'public/lib/gridster/dist/jquery.gridster.min.js',
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/angular-timeago/dist/angular-timeago.js',
        'https://www.google.com/recaptcha/api.js',
        'public/lib/decksterjs/dist/jquery.deckster.js',
        'public/lib/ng-lodash/build/ng-lodash.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js',
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  }
};
<|endoftext|>


<commit_before>const ROOM_NAME = "Shadow Ban Room";
var room = Rooms.get(toId(ROOM_NAME));
if (!room) {
	Rooms.global.addChatRoom(ROOM_NAME);
	room = Rooms.get(toId(ROOM_NAME));

	room.isPrivate = true;
	room.staffRoom = true;
	room.staffAutojoin = true;
	room.addedUsers = {};

	if (room.chatRoomData) {
		room.chatRoomData.isPrivate = true;
		room.chatRoomData.staffRoom = true;
		room.chatRoomData.staffAutojoin = true;
		room.chatRoomData.addedUsers = room.addedUsers;

		Rooms.global.writeChatRoomData();
	}
}
if (Object.size(room.addedUsers) > 0) {
	setImmediate(function () {
		room.add("||Loaded user list: " + Object.keys(room.addedUsers).sort().join(", "));
		room.update();
	});
}
exports.room = room;

function getAllAlts(user) {
	var targets = {};
	if (typeof user === 'string') {
		targets[toId(user)] = 1;
	} else {
		user.getAlts().concat(user.name).forEach(function (altName) {
			var alt = Users.get(altName);
			if (!alt.named) return;

			targets[toId(alt)] = 1;
			Object.keys(alt.prevNames).forEach(function (name) {
				targets[toId(name)] = 1;
			});
		});
	}
	return targets;
}

function intersectAndExclude(a, b) {
	var intersection = [];
	var exclusionA = [];
	var exclusionB = [];

	var ai = 0;
	var bi = 0;
	while (ai < a.length && bi < b.length) {
		var difference = a[ai].localeCompare(b[bi]);
		if (difference < 0) {
			exclusionA.push(a[ai]);
			++ai;
		} else if (difference > 0) {
			exclusionB.push(b[bi]);
			++bi;
		} else {
			intersection.push(a[ai]);
			++ai;
			++bi;
		}
	}

	Array.prototype.push.apply(exclusionA, a.slice(ai));
	Array.prototype.push.apply(exclusionB, b.slice(bi));
	return {intersection: intersection, exclusionA: exclusionA, exclusionB: exclusionB};
}

var checkBannedCache = {};
var checkBanned = exports.checkBanned = function (user) {
	var userId = toId(user);
	if (userId in checkBannedCache) return checkBannedCache[userId];
	//console.log("Shadow ban cache miss:", userId);

	var targets = Object.keys(getAllAlts(user)).sort();
	var bannedUsers = Object.keys(room.addedUsers).sort();

	var matches = intersectAndExclude(targets, bannedUsers);
	var isBanned = matches.intersection.length !== 0;
	for (var t = 0; t < targets.length; ++t) {
		if (isBanned) room.addedUsers[targets[t]] = 1;
		checkBannedCache[targets[t]] = isBanned;
	}
	if (!isBanned) return false;

	if (matches.exclusionA.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Alts of " + matches.intersection[0] + " automatically added: " + matches.exclusionA.join(", "));
	}

	return true;
};

var addUser = exports.addUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (room.addedUsers[u]) {
			delete targets[u];
		} else {
			room.addedUsers[u] = 1;
		}
		checkBannedCache[u] = true;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Added users: " + targets.join(", "));
		room.update();
	}

	return targets;
};
var removeUser = exports.removeUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (!room.addedUsers[u]) {
			delete targets[u];
		} else {
			delete room.addedUsers[u];
		}
		checkBannedCache[u] = false;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Removed users: " + targets.join(", "));
		room.update();
	}

	return targets;
};

var addMessage = exports.addMessage = function (user, tag, message) {
	room.add('|c|' + user.getIdentity() + '|__(' + tag + ')__ ' + message);
	room.update();
};

exports.commands = {
	spam: 'shadowban',
	sban: 'shadowban',
	shadowban: function (target, room, user) {
		if (!target) return this.sendReply("/shadowban OR /sban [username], [secondary command], [reason] - Sends all the user's messages to the shadow ban room.");

		var params = this.splitTarget(target).split(',');
		var action = params[0].trim().toLowerCase();
		var reason = params.slice(1).join(',').trim();
		if (!(action in CommandParser.commands)) {
			action = 'mute';
			reason = params.join(',').trim();
		}

		if (!this.targetUser) return this.sendReply("User '" + this.targetUsername + "' not found.");
		if (!this.can('lock', this.targetUser)) return;

		var targets = addUser(this.targetUser);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is already shadow banned or isn't named.");
		}
		this.privateModCommand("(" + user.name + " has shadow banned: " + targets.join(", ") + (reason ? " (" + reason + ")" : "") + ")");

		//return this.parse('/' + action + ' ' + toId(this.targetUser) + ',' + reason);
	},

	unspam: 'unshadowban',
	unsban: 'unshadowban',
	unshadowban: function (target, room, user) {
		if (!target) return this.sendReply("/unshadowban OR /unsban [username] - Undoes /shadowban (except the secondary command).");
		this.splitTarget(target);

		if (!this.can('lock')) return;

		var targets = removeUser(this.targetUser || this.targetUsername);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is not shadow banned.");
		}
		this.privateModCommand("(" + user.name + " has shadow unbanned: " + targets.join(", ") + ")");
	},

	sbanlist: function (target, room, user) {
		if (!target && !this.can('lock')) return this.sendReply("The command '/sbanlist' was unrecognized.  To send a message starting with '/sbanlist', type '//sbanlist'.");
		if ((user.locked || user.mutedRooms[room.id]) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
		if (!this.can('lock')) return false;

		Users.get(toId(user.name)).send('|popup| Here is a list of sbanned users: \n' + JSON.stringify(Rooms.rooms.shadowbanroom.chatRoomData, null, 2));
	}
};

Users.ShadowBan = exports;
<commit_msg>Fix a crash in sban<commit_after>const ROOM_NAME = "Shadow Ban Room";
var room = Rooms.get(toId(ROOM_NAME));
if (!room) {
	Rooms.global.addChatRoom(ROOM_NAME);
	room = Rooms.get(toId(ROOM_NAME));

	room.isPrivate = true;
	room.staffRoom = true;
	room.staffAutojoin = true;
	room.addedUsers = {};

	if (room.chatRoomData) {
		room.chatRoomData.isPrivate = true;
		room.chatRoomData.staffRoom = true;
		room.chatRoomData.staffAutojoin = true;
		room.chatRoomData.addedUsers = room.addedUsers;

		Rooms.global.writeChatRoomData();
	}
}
if (Object.size(room.addedUsers) > 0) {
	setImmediate(function () {
		room.add("||Loaded user list: " + Object.keys(room.addedUsers).sort().join(", "));
		room.update();
	});
}
exports.room = room;

function getAllAlts(user) {
	var targets = {};
	if (typeof user === 'string') {
		targets[toId(user)] = 1;
	} else {
		user.getAlts().concat(user.name).forEach(function (altName) {
			var alt = Users.get(altName);
			if (!alt.named) return;

			targets[toId(alt)] = 1;
			Object.keys(alt.prevNames).forEach(function (name) {
				targets[toId(name)] = 1;
			});
		});
	}
	return targets;
}

function intersectAndExclude(a, b) {
	var intersection = [];
	var exclusionA = [];
	var exclusionB = [];

	var ai = 0;
	var bi = 0;
	while (ai < a.length && bi < b.length) {
		var difference = a[ai].localeCompare(b[bi]);
		if (difference < 0) {
			exclusionA.push(a[ai]);
			++ai;
		} else if (difference > 0) {
			exclusionB.push(b[bi]);
			++bi;
		} else {
			intersection.push(a[ai]);
			++ai;
			++bi;
		}
	}

	Array.prototype.push.apply(exclusionA, a.slice(ai));
	Array.prototype.push.apply(exclusionB, b.slice(bi));
	return {intersection: intersection, exclusionA: exclusionA, exclusionB: exclusionB};
}

var checkBannedCache = {};
var checkBanned = exports.checkBanned = function (user) {
	var userId = toId(user);
	if (userId in checkBannedCache) return checkBannedCache[userId];
	//console.log("Shadow ban cache miss:", userId);

	var targets = Object.keys(getAllAlts(user)).sort();
	var bannedUsers = Object.keys(room.addedUsers).sort();

	var matches = intersectAndExclude(targets, bannedUsers);
	var isBanned = matches.intersection.length !== 0;
	for (var t = 0; t < targets.length; ++t) {
		if (isBanned) room.addedUsers[targets[t]] = 1;
		checkBannedCache[targets[t]] = isBanned;
	}
	if (!isBanned) return false;

	if (matches.exclusionA.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Alts of " + matches.intersection[0] + " automatically added: " + matches.exclusionA.join(", "));
	}

	return true;
};

var addUser = exports.addUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (room.addedUsers[u]) {
			delete targets[u];
		} else {
			room.addedUsers[u] = 1;
		}
		checkBannedCache[u] = true;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Added users: " + targets.join(", "));
		room.update();
	}

	return targets;
};
var removeUser = exports.removeUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (!room.addedUsers[u]) {
			delete targets[u];
		} else {
			delete room.addedUsers[u];
		}
		checkBannedCache[u] = false;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Removed users: " + targets.join(", "));
		room.update();
	}

	return targets;
};

var addMessage = exports.addMessage = function (user, tag, message) {
	room.add('|c|' + user.getIdentity() + '|__(' + tag + ')__ ' + message);
	room.update();
};
var addEmoticonMessage = exports.addEmoticonMessage = function (user, message) {
	room.add(message);
	room.update();
};

exports.commands = {
	spam: 'shadowban',
	sban: 'shadowban',
	shadowban: function (target, room, user) {
		if (!target) return this.sendReply("/shadowban OR /sban [username], [secondary command], [reason] - Sends all the user's messages to the shadow ban room.");

		var params = this.splitTarget(target).split(',');
		var action = params[0].trim().toLowerCase();
		var reason = params.slice(1).join(',').trim();
		if (!(action in CommandParser.commands)) {
			action = 'mute';
			reason = params.join(',').trim();
		}

		if (!this.targetUser) return this.sendReply("User '" + this.targetUsername + "' not found.");
		if (!this.can('lock', this.targetUser)) return;

		var targets = addUser(this.targetUser);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is already shadow banned or isn't named.");
		}
		this.privateModCommand("(" + user.name + " has shadow banned: " + targets.join(", ") + (reason ? " (" + reason + ")" : "") + ")");

		//return this.parse('/' + action + ' ' + toId(this.targetUser) + ',' + reason);
	},

	unspam: 'unshadowban',
	unsban: 'unshadowban',
	unshadowban: function (target, room, user) {
		if (!target) return this.sendReply("/unshadowban OR /unsban [username] - Undoes /shadowban (except the secondary command).");
		this.splitTarget(target);

		if (!this.can('lock')) return;

		var targets = removeUser(this.targetUser || this.targetUsername);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is not shadow banned.");
		}
		this.privateModCommand("(" + user.name + " has shadow unbanned: " + targets.join(", ") + ")");
	},

	sbanlist: function (target, room, user) {
		if (!target && !this.can('lock')) return this.sendReply("The command '/sbanlist' was unrecognized.  To send a message starting with '/sbanlist', type '//sbanlist'.");
		if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
		if (!this.can('lock')) return false;

		Users.get(toId(user.name)).send('|popup| Here is a list of sbanned users: \n' + JSON.stringify(Rooms.rooms.shadowbanroom.chatRoomData, null, 2));
	}
};

Users.ShadowBan = exports;
<|endoftext|>


<commit_before>//'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:SystemservicesCtrl
 * @description
 * # SystemservicesCtrl
 * Controller of the clientApp
 */

angular.module('clientApp')
  .controller('SystemservicesCtrl',function (
    $location,
    $scope,
  //  $parse,
    $interval,
    $http
  ) {

    var checkServiceTimer = setInterval(function () {
      checkServiceStatus();
    }, 5000);

    servicelocation = "https://" + $location.$$host + "/api/";

    $scope.systemsettings = {};
      var stopped = "stopped";
      var notrunning = "not running";
      var running = "is running";
      checkServiceStatus = function() {
          var data = "servicename=elasticsearch";
          var config = {headers:{
            "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
          }};
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.elasticsearchstatusbit=(data==="true");
              });
          $http.post(servicelocation+"GetServiceStatus",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.elasticsearchstatus=data;
                 var str = data;
                 if(str.match(stopped)){
                   console.log(data + ' service stopped');
                  $scope.systemsettings.elasticsearchstatusbit = false;
                 }
                 if(str.match(notrunning)){
                   console.log(data + ' service stopped');
                    $scope.systemsettings.elasticsearchstatusbit = false;
                 }
                 if(str.match(running)){
                   console.log(data + ' service running');
                    $scope.systemsettings.elasticsearchstatusbit = true;
                 }
              });

          data = "servicename=logstash";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.logstashstatusbit=(data==="true");
              });
          $http.post(servicelocation+"GetServiceStatus",data,config)
                .success(function(data)
                  {
                     $scope.systemsettings.logstashstatus=data;
                     var str = data;
                     if(str.match(stopped)){
                       console.log(data + ' service stopped');
                      $scope.systemsettings.logstashstatusbit = false;
                     }
                     if(str.match(notrunning)){
                       console.log(data + ' service stopped');
                        $scope.systemsettings.logstashstatusbit = false;
                     }
                     if(str.match(running)){
                       console.log(data + ' service running');
                        $scope.systemsettings.logstashstatusbit = true;
                     }
                  });
           data = "servicename=kibana4";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.kibanastatusbit=(data==="true");
              });
          $http.post(servicelocation+"GetServiceStatus",data,config)
            .success(function(data)
              {
                 $scope.systemsettings.kibanastatus=data;
                 var str = data;
                 if(str.match(stopped)){
                   console.log(data + ' service stopped');
                  $scope.systemsettings.kibanastatusbit = false;
                 }
                 if(str.match(notrunning)){
                   console.log(data + ' service stopped');
                    $scope.systemsettings.kibanastatusbit = false;
                 }
                 if(str.match(running)){
                   console.log(data + ' service running');
                    $scope.systemsettings.kibanastatusbit = true;
                 }

              });
      };

    $http.post(servicelocation+"GetTimeZone",data,config)
      .success(function(data)
        {
          $scope.systemsettings.timezone = data;
        });

    console.log("Get Service Status")
    var data = "servicename=elasticsearch";
    var config = {headers:{
      "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
    }};

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.elasticsearchstatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.elasticsearchstatusbit = true;
           }
        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.elasticsearchstatusbit=(data==="true");
        });
    data = "servicename=logstash";
    $http.post(servicelocation+"GetServiceStatus",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatus=data;
               var str = data;
               if(str.match(stopped)){
                 console.log(data + ' service stopped');
                $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(notrunning)){
                 console.log(data + ' service stopped');
                  $scope.systemsettings.logstashstatusbit = false;
               }
               if(str.match(running)){
                 console.log(data + ' service running');
                  $scope.systemsettings.logstashstatusbit = true;
               }
            });
    $http.post(servicelocation+"IsServiceRunning",data,config)
          .success(function(data)
            {
               $scope.systemsettings.logstashstatusbit=(data==="true");
            });
    data = "servicename=kibana4";

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatus=data;
           var str = data;
           if(str.match(stopped)){
             console.log(data + ' service stopped');
            $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(notrunning)){
             console.log(data + ' service stopped');
              $scope.systemsettings.kibanastatusbit = false;
           }
           if(str.match(running)){
             console.log(data + ' service running');
              $scope.systemsettings.kibanastatusbit = true;
           }

        });
    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data)
        {
           $scope.systemsettings.kibanastatusbit=(data==="true");
        });

    $scope.saveTimeZone = function(timezone) {
      $scope.selectedTimezone = timezone;
      var data = "timezone=" + timezone;
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      $http.post(servicelocation+"UpdateTimeZone",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
    };

    $scope.updateStatus = function(status, service)//status: Boolean running/not running, service: "serviceName"
    {
        if(status)
        {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Stop";
          var status = document.getElementsByName(service + 'Status');
        }
        else {
          var button = document.getElementsByName(service + 'Button');
          button.value = "Start";
          var status = document.getElementsByName(service + 'Status');
        }
    };

    $scope.cycleElasticSearch = function() {
      var data = "servicename=elasticsearch";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.elasticsearchstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.elasticsearchstatus=data;
          });
    //  checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.elasticsearchstatusbit,'elastic');

    };

    $scope.cycleKibana = function() {
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};
      var data = "servicename=kibana4";

      var method = "StartService";
      if($scope.systemsettings.kibanastatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.kibanastatus=data;
          });
    //  checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.kibanastatusbit,'kibana');

    };

    $scope.cycleLogstash = function() {
      var data = "servicename=logstash";
      var config = {headers:{
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
        }};

      var method = "StartService";
      if($scope.systemsettings.logstashstatusbit)
        {method = "StopService";}
      $http.post(servicelocation+method,data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
      $http.post(servicelocation+"GetServiceStatus",data,config)
        .success(function(data)
          {
             $scope.systemsettings.logstashstatus=data;
          });
    //  checkServiceStatus();
      $scope.updateStatus($scope.systemsettings.logstashstatusbit,'logstash');

    };
  });
<commit_msg>Updated formatting<commit_after>//'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:SystemservicesCtrl
 * @description
 * # SystemservicesCtrl
 * Controller of the clientApp
 */

angular.module('clientApp')
  .controller('SystemservicesCtrl',function (
                                              $location,
                                              $scope,
                                            //  $parse,
                                              $interval,
                                              $http
                                            ) {

    var checkServiceTimer = setInterval(function () {
                                                      checkServiceStatus();
                                                    }, 5000);

    servicelocation = "https://" + $location.$$host + "/api/";

    $scope.systemsettings = {};
      var stopped = "stopped";
      var notrunning = "not running";
      var running = "is running";
      checkServiceStatus = function() {
                                        var data = "servicename=elasticsearch";
                                        var config = {headers:{
                                                                "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                                                              }};
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data){
                                       $scope.systemsettings.elasticsearchstatusbit=(data==="true");
                                    });
          $http.post(servicelocation+"GetServiceStatus",data,config)
            .success(function(data){
                                       $scope.systemsettings.elasticsearchstatus=data;
                                       var str = data;
                                       if(str.match(stopped)){
                                                               console.log(data + ' service stopped');
                                                              $scope.systemsettings.elasticsearchstatusbit = false;
                                                             }
                                       if(str.match(notrunning)){
                                                                   console.log(data + ' service stopped');
                                                                    $scope.systemsettings.elasticsearchstatusbit = false;
                                                                 }
                                       if(str.match(running)){
                                                               console.log(data + ' service running');
                                                                $scope.systemsettings.elasticsearchstatusbit = true;
                                                             }
                                    });

          data = "servicename=logstash";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data){
                                       $scope.systemsettings.logstashstatusbit=(data==="true");
                                    });

          $http.post(servicelocation+"GetServiceStatus",data,config)
                .success(function(data){
                                           $scope.systemsettings.logstashstatus=data;
                                           var str = data;
                                           if(str.match(stopped)){
                                                                   console.log(data + ' service stopped');
                                                                  $scope.systemsettings.logstashstatusbit = false;
                                                                 }
                                           if(str.match(notrunning)){
                                                                       console.log(data + ' service stopped');
                                                                       $scope.systemsettings.logstashstatusbit = false;
                                                                     }
                                           if(str.match(running)){
                                                                   console.log(data + ' service running');
                                                                    $scope.systemsettings.logstashstatusbit = true;
                                                                 }
                                        });
           data = "servicename=kibana4";
          $http.post(servicelocation+"IsServiceRunning",data,config)
            .success(function(data){
                                       $scope.systemsettings.kibanastatusbit=(data==="true");
                                    });
          $http.post(servicelocation+"GetServiceStatus",data,config)
            .success(function(data){
                                       $scope.systemsettings.kibanastatus=data;
                                       var str = data;
                                       if(str.match(stopped)){
                                                               console.log(data + ' service stopped');
                                                               $scope.systemsettings.kibanastatusbit = false;
                                                             }
                                       if(str.match(notrunning)){
                                                                   console.log(data + ' service stopped');
                                                                   $scope.systemsettings.kibanastatusbit = false;
                                                                 }
                                       if(str.match(running)){
                                                               console.log(data + ' service running');
                                                               $scope.systemsettings.kibanastatusbit = true;
                                                             }

                                    });
      };

    $http.post(servicelocation+"GetTimeZone",data,config)
      .success(function(data){
                                $scope.systemsettings.timezone = data;
                              });

    console.log("Get Service Status")
    var data = "servicename=elasticsearch";
    var config = {headers:{
                            "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                          }};

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data){
                                 $scope.systemsettings.elasticsearchstatus=data;
                                 var str = data;
                                 if(str.match(stopped)){
                                                         console.log(data + ' service stopped');
                                                        $scope.systemsettings.elasticsearchstatusbit = false;
                                                       }
                                 if(str.match(notrunning)){
                                                             console.log(data + ' service stopped');
                                                              $scope.systemsettings.elasticsearchstatusbit = false;
                                                           }
                                 if(str.match(running)){
                                                         console.log(data + ' service running');
                                                          $scope.systemsettings.elasticsearchstatusbit = true;
                                                       }
                              });

    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data){
                                 $scope.systemsettings.elasticsearchstatusbit=(data==="true");
                              });
    data = "servicename=logstash";
    $http.post(servicelocation+"GetServiceStatus",data,config)
          .success(function(data){
                                     $scope.systemsettings.logstashstatus=data;
                                     var str = data;
                                     if(str.match(stopped)){
                                                             console.log(data + ' service stopped');
                                                             $scope.systemsettings.logstashstatusbit = false;
                                                           }
                                     if(str.match(notrunning)){
                                                                  console.log(data + ' service stopped');
                                                                  $scope.systemsettings.logstashstatusbit = false;
                                                               }
                                     if(str.match(running)){
                                                             console.log(data + ' service running');
                                                              $scope.systemsettings.logstashstatusbit = true;
                                                           }
                                  });
    $http.post(servicelocation+"IsServiceRunning",data,config)
          .success(function(data){
                                     $scope.systemsettings.logstashstatusbit=(data==="true");
                                  });
    data = "servicename=kibana4";

    $http.post(servicelocation+"GetServiceStatus",data,config)
      .success(function(data){
                                 $scope.systemsettings.kibanastatus=data;
                                 var str = data;
                                 if(str.match(stopped)){
                                                         console.log(data + ' service stopped');
                                                        $scope.systemsettings.kibanastatusbit = false;
                                                       }
                                 if(str.match(notrunning)){
                                                             console.log(data + ' service stopped');
                                                              $scope.systemsettings.kibanastatusbit = false;
                                                           }
                                 if(str.match(running)){
                                                         console.log(data + ' service running');
                                                          $scope.systemsettings.kibanastatusbit = true;
                                                       }
                              });

    $http.post(servicelocation+"IsServiceRunning",data,config)
      .success(function(data){
                                 $scope.systemsettings.kibanastatusbit=(data==="true");
                              });

    $scope.saveTimeZone = function(timezone) {
                                              $scope.selectedTimezone = timezone;
                                              var data = "timezone=" + timezone;
                                              var config = {headers:{
                                                                    "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                                                                    }};

                                              $http.post(servicelocation+"UpdateTimeZone",data,config)
                                                .success(function(data){
                                                                           $scope.systemsettings.logstashstatus=data;
                                                                        });
                                              $http.post(servicelocation+"GetServiceStatus",data,config)
                                                .success(function(data){
                                                                           $scope.systemsettings.logstashstatus=data;
                                                                        });
                                            };
//status: Boolean running/not running, service: "serviceName"
    $scope.updateStatus = function(status, service){
                                                        if(status){
                                                                    var button = document.getElementsByName(service + 'Button');
                                                                    button.value = "Stop";
                                                                    var status = document.getElementsByName(service + 'Status');
                                                                  }
                                                        else {
                                                                var button = document.getElementsByName(service + 'Button');
                                                                button.value = "Start";
                                                                var status = document.getElementsByName(service + 'Status');
                                                              }
                                                    };

    $scope.cycleElasticSearch = function() {
                                              var data = "servicename=elasticsearch";
                                              var config = {headers:{
                                                                    "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                                                                    }};

                                              var method = "StartService";
                                              if($scope.systemsettings.elasticsearchstatusbit)
                                                {method = "StopService";}
                                              $http.post(servicelocation+method,data,config)
                                                .success(function(data){
                                                                           $scope.systemsettings.elasticsearchstatus=data;
                                                                        });
                                              $http.post(servicelocation+"GetServiceStatus",data,config)
                                                .success(function(data){
                                                                           $scope.systemsettings.elasticsearchstatus=data;
                                                                        });

                                              $scope.updateStatus($scope.systemsettings.elasticsearchstatusbit,'elastic');

                                            };

    $scope.cycleKibana = function() {
                                      var config = {headers:{
                                                            "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                                                            }};
                                      var data = "servicename=kibana4";

                                      var method = "StartService";
                                      if($scope.systemsettings.kibanastatusbit)
                                        {method = "StopService";}
                                      $http.post(servicelocation+method,data,config)
                                        .success(function(data){
                                                                   $scope.systemsettings.kibanastatus=data;
                                                                });
                                      $http.post(servicelocation+"GetServiceStatus",data,config)
                                        .success(function(data){
                                                                   $scope.systemsettings.kibanastatus=data;
                                                                });

                                      $scope.updateStatus($scope.systemsettings.kibanastatusbit,'kibana');
                                    };

    $scope.cycleLogstash = function() {
                                          var data = "servicename=logstash";
                                          var config = {headers:{
                                                                "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                                                                }};

                                          var method = "StartService";
                                          if($scope.systemsettings.logstashstatusbit)
                                            {method = "StopService";}
                                          $http.post(servicelocation+method,data,config)
                                            .success(function(data){
                                                                       $scope.systemsettings.logstashstatus=data;
                                                                    });
                                          $http.post(servicelocation+"GetServiceStatus",data,config)
                                            .success(function(data){
                                                                       $scope.systemsettings.logstashstatus=data;
                                                                    });
                                          $scope.updateStatus($scope.systemsettings.logstashstatusbit,'logstash');
                                        };
  });
<|endoftext|>


<commit_before>;(function (global) {
    "use strict";

    var lastId = -1;

    // Visibility.js allow you to know, that your web page is in the background
    // tab and thus not visible to the user. This library is wrap under
    // Page Visibility API. It fix problems with different vendor prefixes and
    // add high-level useful functions.
    var self = {

        // Call callback only when page become to visible for user or
        // call it now if page is visible now or Page Visibility API
        // doesn’t supported.
        //
        // Return false if API isn’t supported, true if page is already visible
        // or listener ID (you can use it in `unbind` method) if page isn’t
        // visible now.
        //
        //   Visibility.onVisible(function () {
        //       startIntroAnimation();
        //   });
        onVisible: function (callback) {
            var support = self.isSupported();
            if ( !support || !self.hidden() ) {
                callback();
                return support;
            }

            var listener = self.change(function (e, state) {
                if ( !self.hidden() ) {
                    self.unbind(listener);
                    callback();
                }
            });
            return listener;
        },

        // Call callback when visibility will be changed. First argument for
        // callback will be original event object, second will be visibility
        // state name.
        //
        // Return listener ID to unbind listener by `unbind` method.
        //
        // If Page Visibility API doesn’t supported method will be return false
        // and callback never will be called.
        //
        //   Visibility.change(function(e, state) {
        //       Statistics.visibilityChange(state);
        //   });
        //
        // It is just proxy to `visibilitychange` event, but use vendor prefix.
        change: function (callback) {
            if ( !self.isSupported() ) {
                return false;
            }
            lastId += 1;
            var number = lastId;
            self._callbacks[number] = callback;
            self._listen();
            return number;
        },

        // Remove `change` listener by it ID.
        //
        //   var id = Visibility.change(function(e, state) {
        //       firstChangeCallback();
        //       Visibility.unbind(id);
        //   });
        unbind: function (id) {
            delete self._callbacks[id];
        },

        // Call `callback` in any state, expect “prerender”. If current state
        // is “prerender” it will wait until state will be changed.
        // If Page Visibility API doesn’t supported, it will call `callback`
        // immediately.
        //
        // Return false if API isn’t supported, true if page is already after
        // prerendering or listener ID (you can use it in `unbind` method)
        // if page is prerended now.
        //
        //   Visibility.afterPrerendering(function () {
        //       Statistics.countVisitor();
        //   });
        afterPrerendering: function (callback) {
            var support   = self.isSupported();
            var prerender = 'prerender';

            if ( !support || prerender != self.state() ) {
                callback();
                return support;
            }

            var listener = self.change(function (e, state) {
                if ( prerender != state ) {
                    self.unbind(listener);
                    callback();
                }
            });
            return listener;
        },

        // Return true if page now isn’t visible to user.
        //
        //   if ( !Visibility.hidden() ) {
        //       VideoPlayer.play();
        //   }
        //
        // It is just proxy to `document.hidden`, but use vendor prefix.
        hidden: function () {
            return !!(self._doc.hidden || self._doc.webkitHidden);
        },

        // Return visibility state: 'visible', 'hidden' or 'prerender'.
        //
        //   if ( 'prerender' == Visibility.state() ) {
        //       Statistics.pageIsPrerendering();
        //   }
        //
        // Don’t use `Visibility.state()` to detect, is page visible, because
        // visibility states can extend in next API versions.
        // Use more simpler and general `Visibility.hidden()` for this cases.
        //
        // It is just proxy to `document.visibilityState`, but use
        // vendor prefix.
        state: function () {
            return self._doc.visibilityState       ||
                   self._doc.webkitVisibilityState ||
                   'visible';
        },

        // Return true if browser support Page Visibility API.
        //
        //   if ( Visibility.isSupported() ) {
        //       Statistics.startTrackingVisibility();
        //       Visibility.change(function(e, state)) {
        //           Statistics.trackVisibility(state);
        //       });
        //   }
        isSupported: function () {
            return !!(self._doc.visibilityState ||
                      self._doc.webkitVisibilityState);
        },

        // Link to document object to change it in tests.
        _doc: global.document || {},

        // Callbacks from `change` method, that wait visibility changes.
        _callbacks: { },

        // Listener for `visibilitychange` event.
        _change: function(event) {
            var state = self.state();

            for ( var i in self._callbacks ) {
                self._callbacks[i].call(self._doc, event, state);
            }
        },

        // Set listener for `visibilitychange` event.
        _listen: function () {
            if ( self._init ) {
                return;
            }

            var event = 'visibilitychange';
            if ( self._doc.webkitVisibilityState ) {
                event = 'webkit' + event;
            }

            var listener = function () {
                self._change.apply(self, arguments);
            };
            if ( self._doc.addEventListener ) {
                self._doc.addEventListener(event, listener);
            } else {
                self._doc.attachEvent(event, listener);
            }
            self._init = true;
        }

    };

    if ( typeof(module) != 'undefined' && module.exports ) {
        module.exports = self;
    } else {
        global.Visibility = self;
    }

})(this);
<commit_msg>Fix document getter for npm<commit_after>;(function (global) {
    "use strict";

    var lastId = -1;

    // Visibility.js allow you to know, that your web page is in the background
    // tab and thus not visible to the user. This library is wrap under
    // Page Visibility API. It fix problems with different vendor prefixes and
    // add high-level useful functions.
    var self = {

        // Call callback only when page become to visible for user or
        // call it now if page is visible now or Page Visibility API
        // doesn’t supported.
        //
        // Return false if API isn’t supported, true if page is already visible
        // or listener ID (you can use it in `unbind` method) if page isn’t
        // visible now.
        //
        //   Visibility.onVisible(function () {
        //       startIntroAnimation();
        //   });
        onVisible: function (callback) {
            var support = self.isSupported();
            if ( !support || !self.hidden() ) {
                callback();
                return support;
            }

            var listener = self.change(function (e, state) {
                if ( !self.hidden() ) {
                    self.unbind(listener);
                    callback();
                }
            });
            return listener;
        },

        // Call callback when visibility will be changed. First argument for
        // callback will be original event object, second will be visibility
        // state name.
        //
        // Return listener ID to unbind listener by `unbind` method.
        //
        // If Page Visibility API doesn’t supported method will be return false
        // and callback never will be called.
        //
        //   Visibility.change(function(e, state) {
        //       Statistics.visibilityChange(state);
        //   });
        //
        // It is just proxy to `visibilitychange` event, but use vendor prefix.
        change: function (callback) {
            if ( !self.isSupported() ) {
                return false;
            }
            lastId += 1;
            var number = lastId;
            self._callbacks[number] = callback;
            self._listen();
            return number;
        },

        // Remove `change` listener by it ID.
        //
        //   var id = Visibility.change(function(e, state) {
        //       firstChangeCallback();
        //       Visibility.unbind(id);
        //   });
        unbind: function (id) {
            delete self._callbacks[id];
        },

        // Call `callback` in any state, expect “prerender”. If current state
        // is “prerender” it will wait until state will be changed.
        // If Page Visibility API doesn’t supported, it will call `callback`
        // immediately.
        //
        // Return false if API isn’t supported, true if page is already after
        // prerendering or listener ID (you can use it in `unbind` method)
        // if page is prerended now.
        //
        //   Visibility.afterPrerendering(function () {
        //       Statistics.countVisitor();
        //   });
        afterPrerendering: function (callback) {
            var support   = self.isSupported();
            var prerender = 'prerender';

            if ( !support || prerender != self.state() ) {
                callback();
                return support;
            }

            var listener = self.change(function (e, state) {
                if ( prerender != state ) {
                    self.unbind(listener);
                    callback();
                }
            });
            return listener;
        },

        // Return true if page now isn’t visible to user.
        //
        //   if ( !Visibility.hidden() ) {
        //       VideoPlayer.play();
        //   }
        //
        // It is just proxy to `document.hidden`, but use vendor prefix.
        hidden: function () {
            return !!(self._doc.hidden || self._doc.webkitHidden);
        },

        // Return visibility state: 'visible', 'hidden' or 'prerender'.
        //
        //   if ( 'prerender' == Visibility.state() ) {
        //       Statistics.pageIsPrerendering();
        //   }
        //
        // Don’t use `Visibility.state()` to detect, is page visible, because
        // visibility states can extend in next API versions.
        // Use more simpler and general `Visibility.hidden()` for this cases.
        //
        // It is just proxy to `document.visibilityState`, but use
        // vendor prefix.
        state: function () {
            return self._doc.visibilityState       ||
                   self._doc.webkitVisibilityState ||
                   'visible';
        },

        // Return true if browser support Page Visibility API.
        //
        //   if ( Visibility.isSupported() ) {
        //       Statistics.startTrackingVisibility();
        //       Visibility.change(function(e, state)) {
        //           Statistics.trackVisibility(state);
        //       });
        //   }
        isSupported: function () {
            return !!(self._doc.visibilityState ||
                      self._doc.webkitVisibilityState);
        },

        // Link to document object to change it in tests.
        _doc: document || {},

        // Callbacks from `change` method, that wait visibility changes.
        _callbacks: { },

        // Listener for `visibilitychange` event.
        _change: function(event) {
            var state = self.state();

            for ( var i in self._callbacks ) {
                self._callbacks[i].call(self._doc, event, state);
            }
        },

        // Set listener for `visibilitychange` event.
        _listen: function () {
            if ( self._init ) {
                return;
            }

            var event = 'visibilitychange';
            if ( self._doc.webkitVisibilityState ) {
                event = 'webkit' + event;
            }

            var listener = function () {
                self._change.apply(self, arguments);
            };
            if ( self._doc.addEventListener ) {
                self._doc.addEventListener(event, listener);
            } else {
                self._doc.attachEvent(event, listener);
            }
            self._init = true;
        }

    };

    if ( typeof(module) != 'undefined' && module.exports ) {
        module.exports = self;
    } else {
        global.Visibility = self;
    }

})(this);
<|endoftext|>


<commit_before>var moment = require('moment');
var googleapis = require('googleapis');
var GoogleToken = require('gapitoken');
var OAuth2Client = googleapis.OAuth2Client;

var oauth2Client;

var curApp;

var numHangoutUrlsAvailable = 0;

exports.init = function(app) {
	curApp = app;

	app.redis.llen('global:hangout_urls', function(err, len) {
		numHangoutUrlsAvailable = len;
	});

	app.express.get('/hangout-farming', function(req, res){
		var url = "http://" + app.options.HOST + ":" + app.options.PORT + "/hangout-callback";

		oauth2Client =
		new OAuth2Client(app.options.GOOGLE_CLIENT_ID, app.options.GOOGLE_CLIENT_SECRET, url);

		var url = oauth2Client.generateAuthUrl({
			access_type: 'offline',
			scope: 'https://www.googleapis.com/auth/calendar'
		});

		res.redirect(url);
	});

	app.express.get('/hangout-callback', function(req, res) {
		// console.log(req.query["code"]);
		oauth2Client.getToken(req.query["code"], function(err, token) {
			if(err) {
				res.send(500, "Error getting token.");
				return;
			}

			oauth2Client.credentials = token;
			// okay, we've got a token now.	lets actually issue a request.
			googleapis.discover('calendar', 'v3').execute(function(err, client) {
				var now = moment().format();

				client.calendar
				.events
				.insert({
					calendarId: 'primary',
					resource: {
						summary: 'hangout',
						description: 'hangout',
						anyoneCanAddSelf: true,
						visibility: "public",
						transparency: "transparent",
						reminders: {
							overrides: {
								method: 'popup',
								minutes: 0
							}
						},
						start: {
							dateTime: moment().add('days', 1).format()
						},
						end: {
							dateTime: moment().add('days', 1).add('hours', 1).format()
						},
						attendees: []
						}
					})
					.withAuthClient(oauth2Client)
					.execute(function(err, event) {
						if(!err && "hangoutLink" in event) {
							// push it into redis for safekeeping.
							app.redis.lpush("global:hangout_urls", event.hangoutLink, function(err, num) {
								app.logger.info("logged new hangout url: " + event.hangoutLink + "; total: " + num);
								// purely for convenience of clicking to farm another url.
								res.send("urls available: " + num + "
CLICK ME");

								// update the tracking number.
								numHangoutUrlsAvailable = num;

								// now delete the event so it doesn't clutter up the user's calendar.
								// as far as I can tell,
								// client.calendar.events.delete({
								// 	calendarId:'primary',
								// 	eventId:event.id
								// 	}).withAuthClient(oauth2Client)
								// 	.execute();
							});
						} else {
							res.send(err + "
" + "your account doesn't seem to have the 'create video calls for events I create' option enabled. go to google calendar, settings (in the upper right hand corner) and enable that option. Then CLICK HERE!");
						}
					});
				});

		});
	});

	app.logger.info("registered hangout-faming urls");
}

exports.getNextHangoutUrl = function(callback) {

	// just hit redis directly here, with an rpop.
	curApp.redis.rpop("global:hangout_urls", function(err, url) {
		curApp.logger.debug("returning hangout url: " + url + " (err: " + err + ")");
		callback && callback(err, url);
	});
}

exports.reuseUrl = function(url) {
	curApp.redis.rpush("global:hangout_urls", url, function(err) {
		curApp.logger.debug("re-added a url that was no longer needed: " + url);
	});
}

exports.getNumHangoutsAvailable = function() {
	return numHangoutUrlsAvailable;
}<commit_msg>Docs for unhangout farming.<commit_after>var moment = require('moment');
var googleapis = require('googleapis');
var GoogleToken = require('gapitoken');
var OAuth2Client = googleapis.OAuth2Client;

var oauth2Client;

var curApp;

var numHangoutUrlsAvailable = 0;

// The rationale for this crazy situation is covered in DEVELOPMENT.md

exports.init = function(app) {
	curApp = app;

	// keep track of the total number of hangout urls we've farmed so far, so we
	// can put it in the UI.
	app.redis.llen('global:hangout_urls', function(err, len) {
		numHangoutUrlsAvailable = len;
	});

	// set up an HTTP endpoint that will put us in the endpoint redirect loop
	// people who load this url
	app.express.get('/hangout-farming', function(req, res){
		var url = "http://" + app.options.HOST + ":" + app.options.PORT + "/hangout-callback";

		// initialize an oauth client request, using our google client id
		oauth2Client =
		new OAuth2Client(app.options.GOOGLE_CLIENT_ID, app.options.GOOGLE_CLIENT_SECRET, url);

		var url = oauth2Client.generateAuthUrl({
			access_type: 'offline',
			scope: 'https://www.googleapis.com/auth/calendar'
		});

		// redirect the request to the google calendar api
		res.redirect(url);
	});

	// users who complete the authentication request will get redirected back here
	// from google, after they authorize our app. The request they make back to
	// our server will have a token attached to it, that we will use to
	// place requests on behalf of this user.
	app.express.get('/hangout-callback', function(req, res) {
		// console.log(req.query["code"]);
		oauth2Client.getToken(req.query["code"], function(err, token) {
			if(err) {
				res.send(500, "Error getting token.");
				return;
			}

			oauth2Client.credentials = token;

			// okay, we've got a token now.	lets actually issue a request.
			// all we're doing here is creating a calendar event.
			googleapis.discover('calendar', 'v3').execute(function(err, client) {
				var now = moment().format();

				client.calendar
				.events
				.insert({
					calendarId: 'primary',
					resource: {
						summary: 'hangout',
						description: 'hangout',
						anyoneCanAddSelf: true,
						visibility: "public",
						transparency: "transparent",
						reminders: {
							overrides: {
								method: 'popup',
								minutes: 0
							}
						},
						start: {
							dateTime: moment().add('days', 1).format()
						},
						end: {
							dateTime: moment().add('days', 1).add('hours', 1).format()
						},
						attendees: []
						}
					})
					.withAuthClient(oauth2Client)
					.execute(function(err, event) {
						// this event fires when google tells us the calendar
						// event has been created. it includes the new calendar
						// event object.
						if(!err && "hangoutLink" in event) {
							// push it into redis for safekeeping.
							app.redis.lpush("global:hangout_urls", event.hangoutLink, function(err, num) {
								app.logger.info("logged new hangout url: " + event.hangoutLink + "; total: " + num);
								// purely for convenience of clicking to farm another url.
								res.send("urls available: " + num + "
CLICK ME");

								// update the tracking number.
								numHangoutUrlsAvailable = num;

								// TODO test whether it's okay to do this.
								// now delete the event so it doesn't clutter up the user's calendar.
								// as far as I can tell,
								// client.calendar.events.delete({
								// 	calendarId:'primary',
								// 	eventId:event.id
								// 	}).withAuthClient(oauth2Client)
								// 	.execute();
							});
						} else {
							// we send this error if the calendar event created doesn't have a hangout url
							// included in the object. Give the user some rudimentary instructions about
							// how to fix this situation.
							res.send(err + "
" + "your account doesn't seem to have the 'create video calls for events I create' option enabled. go to google calendar, settings (in the upper right hand corner) and enable that option. Then CLICK HERE!");
						}
					});
				});

		});
	});

	app.logger.info("registered hangout-faming urls");
}

// get a hangout url from redis
exports.getNextHangoutUrl = function(callback) {

	// just hit redis directly here, with an rpop.
	curApp.redis.rpop("global:hangout_urls", function(err, url) {
		curApp.logger.debug("returning hangout url: " + url + " (err: " + err + ")");
		callback && callback(err, url);
	});
}

// put a hangout url back into redis that was unused
// (this situation occurs in some limited situations where people
//  join a new hangout in rapid succession)
exports.reuseUrl = function(url) {
	curApp.redis.rpush("global:hangout_urls", url, function(err) {
		curApp.logger.debug("re-added a url that was no longer needed: " + url);
	});
}

// used for UI purposes
exports.getNumHangoutsAvailable = function() {
	return numHangoutUrlsAvailable;
}<|endoftext|>