<commit_before>"use strict";

var winston = require('winston')
  , _ = require('underscore')
  , defaults = {colorize: true, timestamp: false};

var levels = {
  debug: 1
, info: 2
, warn: 3
, error: 4
};

var colors = {
  info: 'cyan'
, debug: 'grey'
, warn: 'yellow'
, error: 'red'
};

var logger = null;

module.exports.init = function (args) {
  var options = _.extend(_.clone(defaults), {
    timestamp: args.logTimestamp
  , handleExceptions: true
  , exitOnError: false
  , json: false
  });

  var winstonOptions = {
    console:
      _.extend({
        colorize: !args.logNoColors
      , level: 'debug'
      }, options)
    };

  winston.addColors(colors);
  winston.loggers.add('appium', winstonOptions);
  logger = winston.loggers.get('appium');
  logger.setLevels(levels);
  logger.stripColors = args.logNoColors;

  if (args.quiet) {
    logger.transports.console.level = 'warn';
  }

  if (args.log) {
    winstonOptions.file = _.extend({
      filename: args.log
    , colorize: false
    , maxFiles: 1
    }, options);

    try {
      logger.add(winston.transports.File, winstonOptions.file);
    } catch (e) {
      logger.info("Tried to attach logging to file " + args.log +
                  " but an error occurred");
    }
  }

  if (args.webhook) {
    var host = args.webhook;
    var port = 9003;
    if (host.indexOf(':') > -1) {
      try {
        host = host.substring(0, host.indexOf(':'));
        port = args.webhook.substring(args.webhook.indexOf(':') + 1);
        port = parseInt(port, 10);
      } catch (e) {
      }
    }
    host = host || '127.0.0.1';
    port = port || 9003;
    try {
      logger.add(winston.transports.Webhook, { 'host': host, 'port': port,
        'path': '/' });
    } catch (e) {
      logger.info("Tried to attach logging to webhook at " + host +
                  " but an error occurred");
    }
  }
};

module.exports.get = function () {
  if (logger === null) {
    exports.init({});
  }
  return logger;
};
<commit_msg>Set log level to 'debug' for logging to file.<commit_after>"use strict";

var winston = require('winston')
  , _ = require('underscore')
  , defaults = {colorize: true, timestamp: false};

var levels = {
  debug: 1
, info: 2
, warn: 3
, error: 4
};

var colors = {
  info: 'cyan'
, debug: 'grey'
, warn: 'yellow'
, error: 'red'
};

var logger = null;

module.exports.init = function (args) {
  var options = _.extend(_.clone(defaults), {
    timestamp: args.logTimestamp
  , handleExceptions: true
  , exitOnError: false
  , json: false
  , level: 'debug'
  });

  var winstonOptions = {
    console:
      _.extend({
        colorize: !args.logNoColors
      }, options)
    };

  winston.addColors(colors);
  winston.loggers.add('appium', winstonOptions);
  logger = winston.loggers.get('appium');
  logger.setLevels(levels);
  logger.stripColors = args.logNoColors;

  if (args.quiet) {
    logger.transports.console.level = 'warn';
  }

  if (args.log) {
    winstonOptions.file = _.extend({
      filename: args.log
    , colorize: false
    , maxFiles: 1
    }, options);

    try {
      logger.add(winston.transports.File, winstonOptions.file);
    } catch (e) {
      logger.info("Tried to attach logging to file " + args.log +
                  " but an error occurred");
    }
  }

  if (args.webhook) {
    var host = args.webhook;
    var port = 9003;
    if (host.indexOf(':') > -1) {
      try {
        host = host.substring(0, host.indexOf(':'));
        port = args.webhook.substring(args.webhook.indexOf(':') + 1);
        port = parseInt(port, 10);
      } catch (e) {
      }
    }
    host = host || '127.0.0.1';
    port = port || 9003;
    try {
      logger.add(winston.transports.Webhook, { 'host': host, 'port': port,
        'path': '/' });
    } catch (e) {
      logger.info("Tried to attach logging to webhook at " + host +
                  " but an error occurred");
    }
  }
};

module.exports.get = function () {
  if (logger === null) {
    exports.init({});
  }
  return logger;
};
<|endoftext|>


<commit_before>angular.module('lcaApp.plot', [
    'lcaApp.plot.directive',
    'lcaApp.plot.service'
]);

/**
 * @ngdoc directive
 * @name lcaApp.plot.directive:plot
 * @restrict E
 * @function
 * @scope
 *
 * @description
 * Plot directive.
 *
 * @param {object} config Object created by PlotService.createInstance
 * @param {[]} data Array of objects providing data
 */
angular.module('lcaApp.plot.directive', ['lcaApp.plot.service', 'd3', 'lcaApp.format'])
    .directive('plot', ['d3Service', 'FormatService',
        function (d3Service, FormatService) {

        function link(scope, element) {
            var parentElement = element[0],
                svgElement = parentElement.parentNode,
                svg =  d3Service.select(svgElement),
                plot = svg.select("g.lcia-bar-container"),
                width = svgElement.clientWidth,
                height = svgElement.clientHeight,
                xScale, yScale,
                xFormat = FormatService.format("^.2g");

            function prepareSvg(config) {
                var margin = config.margin(),
                    cg;

                if (margin) {
                    width = width - margin.left - margin.right;
                    height = height - margin.top - margin.bottom;
                }
                plot.select(".chart-group").remove();
                cg = plot.append("g")
                    .attr("class", "chart-group");
                if (margin) {
                    cg.attr("transform",
                        "translate(" + margin.left + "," + margin.top + ")");
                }
            }

            function resizeSvg(config, data) {
                if (config.resizeSvg) {
                    var content = config.content(),
                        margin = config.margin(),
                        svgSize;

                    if ( content.width()) {
                        width = content.width() * data.length;
                        svgSize = margin ? width + margin.left + margin.right : width;
                        svg.attr("width", svgSize);
                    }
                    if ( content.height()) {
                        height = content.height() * data.length;
                        svgSize = margin ? height + margin.top + margin.bottom : height;
                        svg.attr("height", svgSize);
                    }
                }
            }

            function drawAxes() {

            }

            function createHBarData(d) {
                var xVal = scope.config.x().valueFn(),
                    labelWidth = 55,
                    shape = {
                        x : xScale(Math.min(0, xVal(d))),
                        width : Math.abs(xScale(xVal(d)) - xScale(0))
                    },
                    label = { x : 0, y : 0, anchor : 0 };
                if (shape.width < labelWidth) {
                    if (width - shape.width - shape.x < labelWidth) {
                        label.x = shape.x - 5;
                        label.anchor = "end";
                    } else {
                        label.x = shape.x + shape.width + 5;
                        label.anchor = "start";
                    }
                }
                else {
                    label.x = shape.x + shape.width /2 ;
                    label.anchor = "middle";
                }
                label.text = xFormat(xVal(d));
                return { d: d, s: shape, l: label};
            }

            function drawHorizontalBars(content, data) {
                var shape = content.shape(),
                    barHeight = yScale.rangeBand(),
                    barData;

                barData = data.map( createHBarData);

                var bar = svg.select(".chart-group").selectAll("g")
                    .data(barData)
                    .enter().append("g")
                    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

                bar.append(shape)
                    .style("fill", content.color())
                    .attr("x", function(d) { return d.s.x; })
                    .attr("y", 0)
                    .attr("width", function(d) { return d.s.width; })
                    .attr("height", barHeight-1);

                bar.append("text")
                    .attr("x", function(d) { return d.l.x; })
                    .attr("y", barHeight / 2)
                    .attr("dy", ".35em")
                    .style("text-anchor", function (d) { return d.l.anchor; })
                    .text(function(d) { return d.l.text });
            }

            function drawContents(config, data) {
                var content = config.content();
                if (!content) throw Error("Plot content must be defined.");
                if (content.orientation() === "horizontal") {
                    drawHorizontalBars(content, data);
                }
                //Future enhancement - vertical bars and other content types
            }

            function createScale(dim, plotData, range) {
                if (!dim.valueFn()) throw Error("Plot dimension must provide valueFn");
                if (!dim.scale()) throw Error("Plot dimension must provide scale type");
                var domain = dim.domain(),
                    valueFn = dim.valueFn(),
                    scale;

                if (!domain) {
                    domain = plotData.map(valueFn);
                    if (dim.scale() === "linear") {
                        if (domain.length === 1 && domain[0]) {
                            domain = domain[0] > 0 ? [0, domain[0]] : [domain[0], 0];
                        } else {
                            domain = d3Service.extent(domain);
                            if (domain[0] > 0) domain[0] = 0;
                            else if (domain[1] < 0) domain[1] = 0;
                        }
                    }
                }
                if (dim.scale() === "linear") {
                    scale = d3Service.scale.linear();
                    scale.domain(domain);
                    scale.range(range);
                } else if (dim.scale() === "ordinal") {
                    scale = d3Service.scale.ordinal();
                    scale.domain(domain).rangeRoundBands(range, .1);
                } else {
                    throw Error("Plot does not support scale type : " + dim.scale());
                }
                return scale;
            }

            function prepareScales(config, data) {
                xScale = createScale(config.x(), data, [0, width]);
                yScale = createScale(config.y(), data, [0, height]);
            }

            scope.$watch('config', function (newVal) {
                if (newVal) {
                    if ( svg ) {
                        prepareSvg(newVal);
                    }
                }
            });

            scope.$watch('data', function (newVal, oldVal) {
                if (svg && scope.config && newVal) {
                    resizeSvg(scope.config, newVal);
                    prepareScales(scope.config, newVal);
                    drawContents(scope.config, newVal);
                }
            },
                true);

        }

        return {
            restrict: 'E',
            scope: { config: "=", data: "=", transform: "@" },
            link: link,
            templateNamespace: "svg",
            replace: true,
            template: "<g class='lcia-bar-container' ng-attr-transform='{{transform}}'></g>"
        }
    }]);
<commit_msg>Plot: handle data updates (#8)<commit_after>angular.module('lcaApp.plot', [
    'lcaApp.plot.directive',
    'lcaApp.plot.service'
]);

/**
 * @ngdoc directive
 * @name lcaApp.plot.directive:plot
 * @restrict E
 * @function
 * @scope
 *
 * @description
 * Plot directive.
 *
 * @param {object} config Object created by PlotService.createInstance
 * @param {[]} data Array of objects providing data
 */
angular.module('lcaApp.plot.directive', ['lcaApp.plot.service', 'd3', 'lcaApp.format'])
    .directive('plot', ['d3Service', 'FormatService',
        function (d3Service, FormatService) {

        function link(scope, element) {
            var parentElement = element[0],
                svgElement = parentElement.parentNode,
                svg =  d3Service.select(svgElement),
                plot = svg.select("g.lcia-bar-container"),
                width = svgElement.clientWidth,
                height = svgElement.clientHeight,
                xScale, yScale,
                xFormat = FormatService.format("^.2g");

            function prepareSvg(config) {
                var margin = config.margin(),
                    cg;

                if (margin) {
                    width = width - margin.left - margin.right;
                    height = height - margin.top - margin.bottom;
                }
                plot.select(".chart-group").remove();
                cg = plot.append("g")
                    .attr("class", "chart-group");
                if (margin) {
                    cg.attr("transform",
                        "translate(" + margin.left + "," + margin.top + ")");
                }
            }

            function resizeSvg(config, data) {
                if (config.resizeSvg) {
                    var content = config.content(),
                        margin = config.margin(),
                        svgSize;

                    if ( content.width()) {
                        width = content.width() * data.length;
                        svgSize = margin ? width + margin.left + margin.right : width;
                        svg.attr("width", svgSize);
                    }
                    if ( content.height()) {
                        height = content.height() * data.length;
                        svgSize = margin ? height + margin.top + margin.bottom : height;
                        svg.attr("height", svgSize);
                    }
                }
            }

            function drawAxes() {

            }

            function createHBarData(d) {
                var xVal = scope.config.x().valueFn(),
                    labelWidth = 55,
                    shape = {
                        x : xScale(Math.min(0, xVal(d))),
                        width : Math.abs(xScale(xVal(d)) - xScale(0))
                    },
                    label = { x : 0, y : 0, anchor : 0 };
                if (shape.width < labelWidth) {
                    if (width - shape.width - shape.x < labelWidth) {
                        label.x = shape.x - 5;
                        label.anchor = "end";
                    } else {
                        label.x = shape.x + shape.width + 5;
                        label.anchor = "start";
                    }
                }
                else {
                    label.x = shape.x + shape.width /2 ;
                    label.anchor = "middle";
                }
                label.text = xFormat(xVal(d));
                return { d: d, s: shape, l: label};
            }

            function drawHorizontalBars(content, data) {
                var shape = content.shape(),
                    barHeight = yScale.rangeBand(),
                    barData, barGroups, newGroups;

                barData = data.map( createHBarData);

                barGroups = svg.select(".chart-group").selectAll("g").data(barData);
                newGroups = barGroups.enter().append("g");
                barGroups.exit().remove();
                newGroups.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

                newGroups.append(shape)
                    .style("fill", content.color())
                    .attr("x", function(d) { return d.s.x; })
                    .attr("y", 0)
                    .attr("width", function(d) { return d.s.width; })
                    .attr("height", barHeight-1);

                newGroups.append("text")
                    .attr("x", function(d) { return d.l.x; })
                    .attr("y", barHeight / 2)
                    .attr("dy", ".35em")
                    .style("text-anchor", function (d) { return d.l.anchor; })
                    .text(function(d) { return d.l.text });
            }

            function drawContents(config, data) {
                var content = config.content();
                if (!content) throw Error("Plot content must be defined.");
                if (content.orientation() === "horizontal") {
                    drawHorizontalBars(content, data);
                }
                //Future enhancement - vertical bars and other content types
            }

            function createScale(dim, plotData, range) {
                if (!dim.valueFn()) throw Error("Plot dimension must provide valueFn");
                if (!dim.scale()) throw Error("Plot dimension must provide scale type");
                var domain = dim.domain(),
                    valueFn = dim.valueFn(),
                    scale;

                if (!domain) {
                    domain = plotData.map(valueFn);
                    if (dim.scale() === "linear") {
                        if (domain.length === 1 && domain[0]) {
                            domain = domain[0] > 0 ? [0, domain[0]] : [domain[0], 0];
                        } else {
                            domain = d3Service.extent(domain);
                            if (domain[0] > 0) domain[0] = 0;
                            else if (domain[1] < 0) domain[1] = 0;
                        }
                    }
                }
                if (dim.scale() === "linear") {
                    scale = d3Service.scale.linear();
                    scale.domain(domain);
                    scale.range(range);
                } else if (dim.scale() === "ordinal") {
                    scale = d3Service.scale.ordinal();
                    scale.domain(domain).rangeRoundBands(range, .1);
                } else {
                    throw Error("Plot does not support scale type : " + dim.scale());
                }
                return scale;
            }

            function prepareScales(config, data) {
                xScale = createScale(config.x(), data, [0, width]);
                yScale = createScale(config.y(), data, [0, height]);
            }

            scope.$watch('config', function (newVal) {
                if (newVal) {
                    if ( svg ) {
                        prepareSvg(newVal);
                    }
                }
            });

            scope.$watch('data', function (newVal, oldVal) {
                if (svg && scope.config && newVal) {
                    resizeSvg(scope.config, newVal);
                    prepareScales(scope.config, newVal);
                    drawContents(scope.config, newVal);
                }
            },
                true);

        }

        return {
            restrict: 'E',
            scope: { config: "=", data: "=", transform: "@" },
            link: link,
            templateNamespace: "svg",
            replace: true,
            template: "<g class='lcia-bar-container' ng-attr-transform='{{transform}}'></g>"
        }
    }]);
<|endoftext|>


<commit_before>'use strict';

var http     = require('http'),
    color    = require('cli-color'),
    defaults = require('../defaults.json');

module.exports = function(hostname, port, done) {
  var data = 'reload'
  var options = {
    hostname: hostname || '127.0.0.1',
    port: port || defaults.notifyPort,
    path: '/',
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': data.length
    }
  };

  var req = http.request(options, function() {
    done();
  });
  req.on('error', function() {
    console.error(color.red('LiveReactload: could not send reload notification. Are you sure that reload server is listening?'));
  })
  req.write(data);
  req.end();
}
<commit_msg>Fix nofity crash if done callback is not set<commit_after>'use strict';

var http     = require('http'),
    color    = require('cli-color'),
    defaults = require('../defaults.json');

module.exports = function(hostname, port, done) {
  var data = 'reload'
  var options = {
    hostname: hostname || '127.0.0.1',
    port: port || defaults.notifyPort,
    path: '/',
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': data.length
    }
  };

  var req = http.request(options, function() {
    if (typeof done === 'function') {
      done();
    }
  });
  req.on('error', function() {
    console.error(color.red('LiveReactload: could not send reload notification. Are you sure that reload server is listening?'));
  })
  req.write(data);
  req.end();
}
<|endoftext|>


<commit_before>import Ember from "ember"
import _ from "npm:lodash"
import rpc from "../lib/rpc"
import idGen from "../lib/id-gen"
import hbs from "htmlbars-inline-precompile"
import Fetcher from "../lib/fetcher"
import { storageFor } from "ember-local-storage"

export default Ember.Component.extend({
  authenticate: Ember.inject.service(),
  session: storageFor("persistedSession"),

  isAuthenticated: Ember.computed("session.authenticatedAt", function () {
    return Date.now() - this.get("session.authenticatedAt") < 3100000
  }),

  pullRequests: Ember.computed("session.id", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("userPullRequests", this.get("session.id")),
    })
  }),

  isAuthenticatedWatcher: Ember.observer("isAuthenticated", function () {
    if (this.get("isAuthenticated") === true) $(window).scrollTop(0)
  }),

  jurisdictions: Ember.computed(function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", "index", true),
    })
  }),

  jurisdiction: Ember.computed("jurisdictionId", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", this.get("jurisdictionId")),
    })
  }),

  standardSet: Ember.computed("standardSetId", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("standardSet", this.get("standardSetId")),
    })
  }),

  paneObserver: Ember.observer("pane", function () {
    $(window).scrollTop(0)
  }),

  scrollOnStart: Ember.on("didInsertElement", function () {
    $(window).scrollTop(0)
  }),

  actions: {
    signIn() {
      this.get("authenticate").show()
    },
    showReset() {
      this.get("authenticate").logout()
    },
    selectJurisdiction(id) {
      this.set("jurisdictionId", id)
      this.set("pane", "jurisdiction")
    },
    selectStandardSet(id) {
      this.set("standardSetId", id)
      this.set("pane", "standard-set")
    },
    goToPane(pane) {
      this.set("pane", pane)
    },
    createPullRequest() {
      if (this.get("isCreatingPullRequest") === true) return
      Ember.set(this, "isCreatingPullRequest", true)
      window.addEventListener(
        "message",
        function (e) {
          if (e && e.data && e.data.type && e.data.currentStepTitle === "All done!") {
            if (this.get("isCreatingPullRequestAfterStonly") === true) return
            this.set("isCreatingPullRequestAfterStonly", true)
            window.StonlyWidget.close()
            window.StonlyWidget.closeFullscreen()
            rpc["pullRequest:create"](
              {},
              function (data) {
                Ember.getOwner(this).lookup("router:main").transitionTo("edit.pull-requests", data.data.id)
                Ember.set(this, "isCreatingPullRequest", false)
              }.bind(this),
              function (error) {
                Ember.set(this, "isCreatingPullRequest", false)
                console.error(error)
              }
            )
          }
        }.bind(this)
      )
      window.StonlyWidget.changeActiveExplanation(1302)
      window.StonlyWidget.open()
      window.StonlyWidget.openFullscreen()
    },
  },

  layout: hbs`
  {{partial "navbar"}}

        Standards Creator & Editor

        Are we missing standards you rely on? Found a typo? Has your school, district or charter network created their own custom standards? Add them to the database and make them searchable!

          Welcome to the Common Standards Project editing interface. Here, you can add or edit any standard in the database or add your own. Once your standards are in the database, you can share them so your colleagues can easily search them.

How does this work?

          First, log in or sign up below. Then, add or edit standards using the easy interface. Each time someone submits a change to  the standards, we review it and then save a version. This way, if someone makes a mistake (or edits with the standards you spent hours adding), we can rollback the change. Educators rely on standards to be accurate, so we take the integrity of standards very seriously.

Who can use the standards?

          Anyone. For free! All standards that published to Common Standards Project are licensed under a Creative Commons Attribution license. This means anyone who uses standards on Common Standards Project can use them and do whatever they like with them for free! For more details, click the link.

        {{#if isAuthenticated}}

My Changes/Additions

          {{#if pullRequests.isPending}}

{{partial "icons/ripple"}}

          {{/if}}

          {{#each pullRequests.list as |pullRequest|}}

{{#link-to 'edit.pull-requests' pullRequest.id}}{{pullRequest.title}}{{/link-to}}

          {{/each}}

          {{#if isCreatingPullRequest}}

{{partial "icons/ripple"}}

          {{else}}

Create Standards

          {{/if}}
        {{else}}

Get Started!

        {{/if}}

  `,
})
<commit_msg>fix(front): Change check to id for flexibility in title<commit_after>import Ember from "ember"
import _ from "npm:lodash"
import rpc from "../lib/rpc"
import idGen from "../lib/id-gen"
import hbs from "htmlbars-inline-precompile"
import Fetcher from "../lib/fetcher"
import { storageFor } from "ember-local-storage"

export default Ember.Component.extend({
  authenticate: Ember.inject.service(),
  session: storageFor("persistedSession"),

  isAuthenticated: Ember.computed("session.authenticatedAt", function () {
    return Date.now() - this.get("session.authenticatedAt") < 3100000
  }),

  pullRequests: Ember.computed("session.id", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("userPullRequests", this.get("session.id")),
    })
  }),

  isAuthenticatedWatcher: Ember.observer("isAuthenticated", function () {
    if (this.get("isAuthenticated") === true) $(window).scrollTop(0)
  }),

  jurisdictions: Ember.computed(function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", "index", true),
    })
  }),

  jurisdiction: Ember.computed("jurisdictionId", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", this.get("jurisdictionId")),
    })
  }),

  standardSet: Ember.computed("standardSetId", function () {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("standardSet", this.get("standardSetId")),
    })
  }),

  paneObserver: Ember.observer("pane", function () {
    $(window).scrollTop(0)
  }),

  scrollOnStart: Ember.on("didInsertElement", function () {
    $(window).scrollTop(0)
  }),

  actions: {
    signIn() {
      this.get("authenticate").show()
    },
    showReset() {
      this.get("authenticate").logout()
    },
    selectJurisdiction(id) {
      this.set("jurisdictionId", id)
      this.set("pane", "jurisdiction")
    },
    selectStandardSet(id) {
      this.set("standardSetId", id)
      this.set("pane", "standard-set")
    },
    goToPane(pane) {
      this.set("pane", pane)
    },
    createPullRequest() {
      if (this.get("isCreatingPullRequest") === true) return
      Ember.set(this, "isCreatingPullRequest", true)
      window.addEventListener(
        "message",
        function (e) {
          if (e && e.data && e.data.type && e.data.currentStepID === 9870) {
            if (this.get("isCreatingPullRequestAfterStonly") === true) return
            this.set("isCreatingPullRequestAfterStonly", true)
            window.StonlyWidget.close()
            window.StonlyWidget.closeFullscreen()
            rpc["pullRequest:create"](
              {},
              function (data) {
                Ember.getOwner(this).lookup("router:main").transitionTo("edit.pull-requests", data.data.id)
                Ember.set(this, "isCreatingPullRequest", false)
              }.bind(this),
              function (error) {
                Ember.set(this, "isCreatingPullRequest", false)
                console.error(error)
              }
            )
          }
        }.bind(this)
      )
      window.StonlyWidget.changeActiveExplanation(1302)
      window.StonlyWidget.open()
      window.StonlyWidget.openFullscreen()
    },
  },

  layout: hbs`
  {{partial "navbar"}}

        Standards Creator & Editor

        Are we missing standards you rely on? Found a typo? Has your school, district or charter network created their own custom standards? Add them to the database and make them searchable!

          Welcome to the Common Standards Project editing interface. Here, you can add or edit any standard in the database or add your own. Once your standards are in the database, you can share them so your colleagues can easily search them.

How does this work?

          First, log in or sign up below. Then, add or edit standards using the easy interface. Each time someone submits a change to  the standards, we review it and then save a version. This way, if someone makes a mistake (or edits with the standards you spent hours adding), we can rollback the change. Educators rely on standards to be accurate, so we take the integrity of standards very seriously.

Who can use the standards?

          Anyone. For free! All standards that published to Common Standards Project are licensed under a Creative Commons Attribution license. This means anyone who uses standards on Common Standards Project can use them and do whatever they like with them for free! For more details, click the link.

        {{#if isAuthenticated}}

My Changes/Additions

          {{#if pullRequests.isPending}}

{{partial "icons/ripple"}}

          {{/if}}

          {{#each pullRequests.list as |pullRequest|}}

{{#link-to 'edit.pull-requests' pullRequest.id}}{{pullRequest.title}}{{/link-to}}

          {{/each}}

          {{#if isCreatingPullRequest}}

{{partial "icons/ripple"}}

          {{else}}

Create Standards

          {{/if}}
        {{else}}

Get Started!

        {{/if}}

  `,
})
<|endoftext|>


<commit_before>import React from 'react'

import Nav from '../../organisms/Nav/Nav';
import Link from '../../../components/atoms/Link/Link.js'

export default class Main extends React.Component {
  constructor(props) {
      super(props);
  }

  render() {
    return(

          {this.props.children}

    )
  }
}
<commit_msg>Remove Main tags<commit_after>import React from 'react'

import Nav from '../../organisms/Nav/Nav';
import Link from '../../../components/atoms/Link/Link.js'

export default class Main extends React.Component {
  constructor(props) {
      super(props);
  }

  render() {
    return(

        {this.props.children}

    )
  }
}
<|endoftext|>


<commit_before>/**
 * Implementation of the `akismet.Server` class.
 * @module server/server
 */
const {Author, Blog, Comment, EndPoints, HTTPHeaders} = require('../core');
const bodyParser = require('body-parser');
const {Client} = require('../client');
const cors = require('cors');
const {EventEmitter} = require('events');
const express = require('express');
const http = require('http');
const https = require('https');
const logger = require('morgan');
const url = require('url');

/**
 * An HTTP server that acts as a proxy between clients and the [Akismet](https://akismet.com) service.
 * @augments events.EventEmitter
 */
module.exports = class Server extends EventEmitter {

  /**
   * Emitted when the server closes.
   * @event close
   */

  /**
   * Emitted each time the server experiences an error.
   * @event error
   * @param {Error} err The emitted error event.
   */

  /**
   * Emitted when the server has been bound after calling `listen` method.
   * @event listening
   */

  /**
   * Emitted each time there is a request.
   * @event request
   * @param {http.IncomingMessage} req The request sent by the client.
   */

  /**
   * Initializes a new instance of the class.
   * @param {object} [options] An object specifying values used to initialize this instance.
   */
  constructor(options = {}) {
    super();

    /**
     * The underlying [Express](http://expressjs.com/api.html#express) application used for routing requests.
     * @type {function}
     * @private
     */
    this._express = express();
    this._express.disable('x-powered-by');
    this._registerMiddleware();
    this._registerRoutes();

    /**
     * The underlying HTTP(S) service listening for requests.
     * @type {(http.Server|https.Server)}
     * @private
     */
    this._httpService = null;

    /**
     * The server settings.
     * @type {object}
     * @private
     */
    this._options = options;
  }

  /**
   * The default address that the server is listening on.
   * @type {string}
   */
  static get DEFAULT_ADDRESS() {
    return '0.0.0.0';
  }

  /**
   * The default port that the server is listening on.
   * @type {number}
   */
  static get DEFAULT_PORT() {
    return 3000;
  }

  /**
   * The address that the server is listening on.
   * @type {string}
   */
  get address() {
    return typeof this._options.address == 'string' ? this._options.address : Server.DEFAULT_ADDRESS;
  }

  /**
   * The port that the server is listening on.
   * @type {number}
   */
  get port() {
    return typeof this._options.port == 'number' ? this._options.port : Server.DEFAULT_PORT;
  }

  /**
   * The URL to redirect the user when a request is unhandled.
   * If this property is empty, a 404 status code is sent instead of redirecting.
   * @type {string}
   */
  get redirectURL() {
    return typeof this._options.redirectURL == 'string' && this._options.redirectURL.length ? this._options.redirectURL : null;
  }

  /**
   * Checks a comment against the service database, and prints a value indicating whether it is spam.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been checked.
   * @throws {Error} The specified request is invalid.
   */
  checkComment(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.checkComment(req.akismet.comment).then(
      isSpam => Server._sendResponse(res, isSpam ? 'true' : 'false'),
      err => { Server._sendResponse(res, 'invalid', err); this.emit('error', err); }
    );
  }

  /**
   * Stops the server from accepting new connections.
   * @returns {Promise} Completes when the server is finally closed.
   */
  close() {
    if(!this._httpService) return Promise.resolve();

    return new Promise(resolve => this._httpService.close(() => {
      this._httpService = null;
      this.emit('close');
      resolve();
    }));
  }

  /**
   * Begin accepting connections.
   * @param {number} [port] The port that the server should run on.
   * @param {string} [address] The address that the server should run on.
   * @returns {Promise} Completes when the server has been started.
   */
  listen(port = -1, address = '') {
    if(port <= 0) port = this.port;
    if(!address.length) address = this.address;

    this._httpService =
      'ssl' in this._options ?
      https.createServer(this._options.ssl, this._express) :
      http.createServer(this._express);

    this._httpService.on('error', err => this.emit('error', err));
    this._httpService.on('request', req => this.emit('request', req));

    return new Promise(resolve => this._httpService.listen(port, address, () => {
      let socket = this._httpService.address();
      this._options.address = socket.address;
      this._options.port = socket.port;

      this.emit('listening');
      resolve();
    }));
  }

  /**
   * Submits a comment that was incorrectly marked as spam but should not have been.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been submitted.
   * @throws {Error} The specified request is invalid.
   */
  submitHam(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.submitHam(req.akismet.comment).then(
      () => Server._sendResponse(res, 'Thanks for making the web a better place.'),
      err => { Server._sendResponse(res, '', err); this.emit('error', err); }
    );
  }

  /**
   * Submits a comment that was not marked as spam but should have been.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been submitted.
   * @throws {Error} The specified request is invalid.
   */
  submitSpam(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.submitSpam(req.akismet.comment).then(
      () => Server._sendResponse(res, 'Thanks for making the web a better place.'),
      err => { Server._sendResponse(res, '', err); this.emit('error', err); }
    );
  }

  /**
   * Checks an API key against the service database, and prints a value indicating whether it is a valid key.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server. The response sent by the server.
   * @returns {Promise} Completes once the API key has been checked.
   * @throws {Error} The specified request is invalid.
   */
  verifyKey(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.verifyKey().then(
      isValid => Server._sendResponse(res, isValid ? 'valid' : 'invalid'),
      err => { Server._sendResponse(res, 'invalid', err); this.emit('error', err); }
    );
  }

  /**
   * Processes the specified request body.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @param {Function} next The callback used to pass the request off to the next middleware.
   * @private
   */
  static _processRequest(req, res, next) {
    // Parse client arguments.
    let apiKey = 'key' in req.body ? req.body.key : req.hostname.split('.')[0];
    let userAgent = HTTPHeaders.X_USER_AGENT in req.headers ? req.headers[HTTPHeaders.X_USER_AGENT] : req.headers['user-agent'];
    let client = new Client(apiKey, Blog.fromJSON(req.body), {userAgent});

    // Parse comment values.
    let comment = Comment.fromJSON(req.body);
    if(!comment.author) comment.author = new Author();
    if(!comment.author.ipAddress) comment.author.ipAddress = req.connection.remoteAddress;

    // Update request properties.
    req.akismet = {client, comment};
    next();
  }

  /**
   * Registers the middleware.
   * @private
   */
  _registerMiddleware() {
    this._express.use(logger(this._express.get('env') == 'development' ? 'dev' : 'combined'));

    this._express.use(cors({
      allowedHeaders: [HTTPHeaders.X_REQUESTED_WITH, HTTPHeaders.X_USER_AGENT],
      exposedHeaders: [HTTPHeaders.X_AKISMET_DEBUG_HELP],
      methods: ['GET', 'POST'],
      origin: true
    }));

    this._express.use(bodyParser.urlencoded({extended: true}));
    this._express.use(Server._processRequest);
  }

  /**
   * Registers the route table.
   * @private
   */
  _registerRoutes() {
    this._express.post(EndPoints.CHECK_COMMENT, this.checkComment.bind(this));
    this._express.post(EndPoints.SUBMIT_HAM, this.submitHam.bind(this));
    this._express.post(EndPoints.SUBMIT_SPAM, this.submitSpam.bind(this));
    this._express.post(EndPoints.VERIFY_KEY, this.verifyKey.bind(this));

    this._express.all('*', (req, res) => {
      if(req.method == 'OPTIONS')
        res.status(204).end();
      else {
        let redirect = this.redirectURL;
        if(typeof redirect == 'string') res.redirect(301, url.resolve(redirect, req.url));
        else res.status(404).send(http.STATUS_CODES[404]);
      }
    });
  }

  /**
   * Sends the specified response body.
   * @param {express.Response} res The response sent by the server.
   * @param {string} body The response body to send to the client.
   * @param {Error} [error] An error message to add to the response headers as `HTTPHeaders.X_AKISMET_DEBUG_HELP`.
   * @private
   */
  static _sendResponse(res, body, error = null) {
    res.type('text/plain; charset=utf-8');
    if(error) res.set(HTTPHeaders.X_AKISMET_DEBUG_HELP, error.toString());
    res.send(body);
  }
};
<commit_msg>Code optimization<commit_after>/**
 * Implementation of the `akismet.Server` class.
 * @module server/server
 */
const {Author, Blog, Comment, EndPoints, HTTPHeaders} = require('../core');
const bodyParser = require('body-parser');
const {Client} = require('../client');
const cors = require('cors');
const {EventEmitter} = require('events');
const express = require('express');
const http = require('http');
const https = require('https');
const logger = require('morgan');
const url = require('url');

/**
 * An HTTP server that acts as a proxy between clients and the [Akismet](https://akismet.com) service.
 * @augments events.EventEmitter
 */
module.exports = class Server extends EventEmitter {

  /**
   * Emitted when the server closes.
   * @event close
   */

  /**
   * Emitted each time the server experiences an error.
   * @event error
   * @param {Error} err The emitted error event.
   */

  /**
   * Emitted when the server has been bound after calling `listen` method.
   * @event listening
   */

  /**
   * Emitted each time there is a request.
   * @event request
   * @param {http.IncomingMessage} req The request sent by the client.
   */

  /**
   * Initializes a new instance of the class.
   * @param {object} [options] An object specifying values used to initialize this instance.
   */
  constructor(options = {}) {
    super();

    /**
     * The underlying [Express](http://expressjs.com/api.html#express) application used for routing requests.
     * @type {function}
     * @private
     */
    this._express = express();
    this._express.disable('x-powered-by');
    this._registerMiddleware();
    this._registerRoutes();

    /**
     * The underlying HTTP(S) service listening for requests.
     * @type {(http.Server|https.Server)}
     * @private
     */
    this._httpService = null;

    /**
     * The server settings.
     * @type {object}
     * @private
     */
    this._options = options;
  }

  /**
   * The default address that the server is listening on.
   * @type {string}
   */
  static get DEFAULT_ADDRESS() {
    return '0.0.0.0';
  }

  /**
   * The default port that the server is listening on.
   * @type {number}
   */
  static get DEFAULT_PORT() {
    return 3000;
  }

  /**
   * The address that the server is listening on.
   * @type {string}
   */
  get address() {
    return typeof this._options.address == 'string' ? this._options.address : Server.DEFAULT_ADDRESS;
  }

  /**
   * The port that the server is listening on.
   * @type {number}
   */
  get port() {
    return typeof this._options.port == 'number' ? this._options.port : Server.DEFAULT_PORT;
  }

  /**
   * The URL to redirect the user when a request is unhandled.
   * If this property is empty, a 404 status code is sent instead of redirecting.
   * @type {string}
   */
  get redirectURL() {
    return typeof this._options.redirectURL == 'string' && this._options.redirectURL.length ? this._options.redirectURL : null;
  }

  /**
   * Checks a comment against the service database, and prints a value indicating whether it is spam.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been checked.
   * @throws {Error} The specified request is invalid.
   */
  checkComment(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.checkComment(req.akismet.comment).then(
      isSpam => Server._sendResponse(res, isSpam ? 'true' : 'false'),
      err => { Server._sendResponse(res, 'invalid', err); this.emit('error', err); }
    );
  }

  /**
   * Stops the server from accepting new connections.
   * @returns {Promise} Completes when the server is finally closed.
   */
  close() {
    if(!this._httpService) return Promise.resolve();

    return new Promise(resolve => this._httpService.close(() => {
      this._httpService = null;
      this.emit('close');
      resolve();
    }));
  }

  /**
   * Begin accepting connections.
   * @param {number} [port] The port that the server should run on.
   * @param {string} [address] The address that the server should run on.
   * @returns {Promise} Completes when the server has been started.
   */
  listen(port = -1, address = '') {
    if(port <= 0) port = this.port;
    if(!address.length) address = this.address;

    this._httpService =
      'ssl' in this._options ?
      https.createServer(this._options.ssl, this._express) :
      http.createServer(this._express);

    this._httpService.on('error', err => this.emit('error', err));
    this._httpService.on('request', req => this.emit('request', req));

    return new Promise(resolve => this._httpService.listen(port, address, () => {
      let socket = this._httpService.address();
      this._options.address = socket.address;
      this._options.port = socket.port;

      this.emit('listening');
      resolve();
    }));
  }

  /**
   * Submits a comment that was incorrectly marked as spam but should not have been.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been submitted.
   * @throws {Error} The specified request is invalid.
   */
  submitHam(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.submitHam(req.akismet.comment).then(
      () => Server._sendResponse(res, 'Thanks for making the web a better place.'),
      err => { Server._sendResponse(res, '', err); this.emit('error', err); }
    );
  }

  /**
   * Submits a comment that was not marked as spam but should have been.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @returns {Promise} Completes once the comment has been submitted.
   * @throws {Error} The specified request is invalid.
   */
  submitSpam(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.submitSpam(req.akismet.comment).then(
      () => Server._sendResponse(res, 'Thanks for making the web a better place.'),
      err => { Server._sendResponse(res, '', err); this.emit('error', err); }
    );
  }

  /**
   * Checks an API key against the service database, and prints a value indicating whether it is a valid key.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server. The response sent by the server.
   * @returns {Promise} Completes once the API key has been checked.
   * @throws {Error} The specified request is invalid.
   */
  verifyKey(req, res) {
    if(!('akismet' in req) || !('client' in req.akismet)) throw new Error('Invalid request.');

    let client = req.akismet.client;
    return client.verifyKey().then(
      isValid => Server._sendResponse(res, isValid ? 'valid' : 'invalid'),
      err => { Server._sendResponse(res, 'invalid', err); this.emit('error', err); }
    );
  }

  /**
   * Processes the specified request body.
   * @param {express.Request} req The request sent by a client.
   * @param {express.Response} res The response sent by the server.
   * @param {Function} next The callback used to pass the request off to the next middleware.
   * @private
   */
  static _processRequest(req, res, next) {
    // Parse client arguments.
    let apiKey = 'key' in req.body ? req.body.key : req.hostname.split('.')[0];
    let userAgent = HTTPHeaders.X_USER_AGENT in req.headers ? req.headers[HTTPHeaders.X_USER_AGENT] : req.headers['user-agent'];
    let client = new Client(apiKey, Blog.fromJSON(req.body), {userAgent});

    // Parse comment values.
    let comment = Comment.fromJSON(req.body);
    if(!comment.author) comment.author = new Author();
    if(!comment.author.ipAddress) comment.author.ipAddress = req.connection.remoteAddress;

    // Update request properties.
    req.akismet = {client, comment};
    next();
  }

  /**
   * Registers the middleware.
   * @private
   */
  _registerMiddleware() {
    this._express.use(logger(this._express.get('env') == 'development' ? 'dev' : 'combined'));

    this._express.use(cors({
      allowedHeaders: [HTTPHeaders.X_REQUESTED_WITH, HTTPHeaders.X_USER_AGENT],
      exposedHeaders: [HTTPHeaders.X_AKISMET_DEBUG_HELP],
      methods: ['GET', 'POST'],
      origin: true
    }));

    this._express.use(bodyParser.urlencoded({extended: true}));
    this._express.use(Server._processRequest);
  }

  /**
   * Registers the route table.
   * @private
   */
  _registerRoutes() {
    this._express.post(EndPoints.CHECK_COMMENT, this.checkComment.bind(this));
    this._express.post(EndPoints.SUBMIT_HAM, this.submitHam.bind(this));
    this._express.post(EndPoints.SUBMIT_SPAM, this.submitSpam.bind(this));
    this._express.post(EndPoints.VERIFY_KEY, this.verifyKey.bind(this));

    this._express.all('*', (req, res) => {
      if(req.method == 'OPTIONS')
        res.sendStatus(204);
      else {
        if(typeof this.redirectURL == 'string') res.redirect(301, url.resolve(this.redirectURL, req.url));
        else res.sendStatus(404);
      }
    });
  }

  /**
   * Sends the specified response body.
   * @param {express.Response} res The response sent by the server.
   * @param {string} body The response body to send to the client.
   * @param {Error} [error] An error message to add to the response headers as `HTTPHeaders.X_AKISMET_DEBUG_HELP`.
   * @private
   */
  static _sendResponse(res, body, error = null) {
    res.type('text/plain; charset=utf-8');
    if(error) res.set(HTTPHeaders.X_AKISMET_DEBUG_HELP, error.toString());
    res.send(body);
  }
};
<|endoftext|>


<commit_before>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),

        exec            = main.child_process.exec,
        spawn           = main.child_process.spawn,

        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        ConNum          = 0,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var ret;

        if (io) {
            io          = io.listen(pServer);

            io.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                io.enable('browser client minification');
                io.enable('browser client gzip');
                io.enable('browser client etag');
            }

            io.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            ret = io.sockets.on('connection', onConnection);
        }

        return ret;
    };

    function jsonSend(socket, json) {
        var msg = Util.stringifyJSON(json);
        socket.send(msg);
    }

    function onConnection(socket) {
        var msg, onDisconect, onConnect;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'connected\n');

            jsonSend(socket, {
                stdout : msg
            });

            Clients[ConNum]   = true;
            onConnect           = onMessage(ConNum, function(json) {
                jsonSend(socket, json);
            });
            onDisconect         = Util.retFunc(disconnect, ConNum);

            socket.on('message', onConnect);
            socket.on('disconnect', function() {
                socket.removeListener('message', onConnect);
                socket.removeListener('disconnect', onDisconect);
            });
        } else {
            msg = log(ConNum, ' in use. Reconnecting...');

            jsonSend(socket, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    function disconnect(connNum) {
        OnMessageFuncs  [connNum]  =
        ClientFuncs     [connNum]  = null;

        log(connNum, 'disconnected');
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function onMessage(pConnNum, callback) {
        return function(pCommand) {
            var lMsg, lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, Util.retExec(callback, json));
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        Util.exec(callback, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        Util.exec(callback, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    lMsg    = Util.stringifyJSON({
                        stdout: pCommand
                    });

                    io.sockets.emit('message', lMsg);
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, Util.retExec(callback));
            }
        };
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        Util.tryCatchLog(function() {
            cmd         = spawn(pCommand, args, options);
        });

        if (cmd) {
            send        = function(error, data) {
                var exec    = {
                        stderr: error,
                        stdout: data
                    };

                Util.exec(callback, exec);
            };

            cmd.stdout.on('data', function(data) {
                send(null, data + '');
            });

            cmd.stderr.on('data', function(error) {
                send(error + '', null);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }
})();
<commit_msg>refactor(socket) onConnection: onConnect -> onMessage<commit_after>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),

        exec            = main.child_process.exec,
        spawn           = main.child_process.spawn,

        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        ConNum          = 0,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var ret;

        if (io) {
            io          = io.listen(pServer);

            io.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                io.enable('browser client minification');
                io.enable('browser client gzip');
                io.enable('browser client etag');
            }

            io.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            ret = io.sockets.on('connection', onConnection);
        }

        return ret;
    };

    function jsonSend(socket, json) {
        var msg = Util.stringifyJSON(json);
        socket.send(msg);
    }

    function onConnection(socket) {
        var msg, onDisconect, onMessage;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'connected\n');

            jsonSend(socket, {
                stdout : msg
            });

            Clients[ConNum]   = true;
            onMessage           = getOnMessage(ConNum, function(json) {
                jsonSend(socket, json);
            });
            onDisconect         = Util.retFunc(disconnect, ConNum);

            socket.on('message', onMessage);
            socket.on('disconnect', function() {
                socket.removeListener('message', onMessage);
                socket.removeListener('disconnect', onDisconect);
            });
        } else {
            msg = log(ConNum, ' in use. Reconnecting...');

            jsonSend(socket, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    function disconnect(connNum) {
        OnMessageFuncs  [connNum]  =
        ClientFuncs     [connNum]  = null;

        log(connNum, 'disconnected');
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function getOnMessage(pConnNum, callback) {
        return function(pCommand) {
            var lMsg, lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, Util.retExec(callback, json));
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        Util.exec(callback, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        Util.exec(callback, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    lMsg    = Util.stringifyJSON({
                        stdout: pCommand
                    });

                    io.sockets.emit('message', lMsg);
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, Util.retExec(callback));
            }
        };
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        Util.tryCatchLog(function() {
            cmd         = spawn(pCommand, args, options);
        });

        if (cmd) {
            send        = function(error, data) {
                var exec    = {
                        stderr: error,
                        stdout: data
                    };

                Util.exec(callback, exec);
            };

            cmd.stdout.on('data', function(data) {
                send(null, data + '');
            });

            cmd.stderr.on('data', function(error) {
                send(error + '', null);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }
})();
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var RPC = require('../rpc')
var path = require('path')
var util = require('util')
var Asset = require('../web/asset')
var debug = require('debug')('micromono:service')
var Router = require('../web/router')
var assign = require('lodash.assign')
var extend = require('ampersand-class-extend')
var EventEmitter = require('eventemitter3')
var Announcement = require('../announcement')

/**
 * MicroMono Service class constructor.
 */
var Service = module.exports = function MicroMonoService() {
  if (!this.packagePath) {
    throw new Error('Please provide `packagePath` property when you extend Service class')
  }

  this.packageInfo = require(path.join(this.packagePath, 'package.json'))
  this.setDefaults(this.packageInfo)
  this.announcement = new Announcement(this)

  this.setupAsset()
  this.setupWeb()
  this.setupRPC()

  if (!this.init) {
    this.init = function() {
      return Promise.resolve()
    }
  }
}

// Provide the ability to extend the Service class.
Service.extend = extend

// Service is an event emitter
assign(Service.prototype, EventEmitter.prototype)

/**
 * Set default options of the service
 *
 * @param {Object} info Object contains service information.
 */
Service.prototype.setDefaults = function(info) {
  this.name = this.name || info.name
  this.baseUrl = this.baseUrl || '/'
  this.version = info.version
}

Service.prototype.setupAsset = function() {
  if (this.packageInfo.jspm) {
    // found jspm info, initialize Asset
    this.asset = new Asset(this.packagePath)
  }
}

Service.prototype.setupWeb = function() {
  if (this.route || this.asset || this.middleware) {
    this.framework = this.framework || 'express'
    this.router = new Router(this)
    this.app = this.router.framework.getApp()
  }
}

Service.prototype.setupRPC = function() {
  if (!this.api) {
    this.api = {}
  }

  // We need at least one api for heartbeating.
  this.api.__ping = function(msg, callback) {
    callback('pong')
  }

  this.rpcType = this.rpcType || 'axon'
  var rpcOptions = {
    api: this.api,
    type: this.rpcType,
    context: this,
    isRemote: false
  }
  this.rpc = new RPC(rpcOptions)
}

/**
 * Get the type of the service instance, remote or not.
 *
 * @return {Boolean} True if this is a farcaster (a fake service rebuilt from
 * announcement of remote service), otherwise false.
 */
Service.prototype.isRemote = function() {
  return false
}

/**
 * Set the instance of native node http.Server instance
 *
 * @param {http.Server} server
 * @emit 'server' {http.Server}
 */
Service.prototype.setHttpServer = function(server) {
  this.server = server
  this.emit('server', server)
}

/**
 * Set or get upgrade url.
 *
 * @param  {String|undefined} upgradeUrl Set the upgrade url when this is string
 * or return the current value if this is undefined.
 * @return {String}           Value of current upgrade url.
 */
Service.prototype.allowUpgrade = function(upgradeUrl) {
  if ('undefined' === typeof upgradeUrl) {
    return this.announcement.upgradeUrl
  } else if (upgradeUrl) {
    upgradeUrl = path.join(this.baseUrl, upgradeUrl)
  }
  return (this.announcement.upgradeUrl = upgradeUrl)
}

/**
 * Start a web server which serves requests for route, asset and middleware
 * provided by this service.
 *
 * @param  {Number|String}  port Port to bind the server.
 * @param  {String}         host Host or ip address to bind the port to.
 * @return {Promise}        A promise instance rejects with error or resolve with
 * instance of http.Server when server started successfully.
 */
Service.prototype.startWebServer = function(port, host) {
  debug('startWebServer()')
  if (!this.router) {
    // no need to start http server if we don't have asset or route to serve.
    debug('no need to start web server')
    return Promise.resolve()
  }

  var self = this
  host = host || '0.0.0.0'
  port = port || 0

  debug('start web server at %s:%s', host, port)

  return this.router.startServer(port, host).then(function(server) {
    if (server) {
      var address = server.address()
      self.announcement.webPort = address.port
      debug('web server started at %s:%s', address.address, address.port)

      self.setHttpServer(server)
    }
  })
}

Service.prototype.startRPCServer = function(port, host) {
  host = host || '0.0.0.0'
  port = port || 0
  var self = this
  debug('start "%s" rpc server at %s:%s', this.rpc.type, host, port)
  return this.rpc.startServer(port, host).then(function(server) {
    var address = server.address()
    self.announcement.rpcPort = address.port
    debug('"%s" rpc server started at %s:%s', self.rpc.type, address.address, address.port)
  })
}

Service.prototype.run = function(options) {
  debug('run service "%s"', this.name)
  options = options || {}
  var self = this
  var ann = this.announcement

  var promise = this.startWebServer(options.port, options.host)
    .then(function() {
      debug('init() service "%s"', self.name)
      return self.init()
    })
    .then(function() {
      if (self.router) {
        debug('setup router & middleware for service "%s"', self.name)
        if (self.asset) {
          debug('setup asset for serivce "%s"', self.name)
          ann.asset = self.asset.parseJSPM()

          // make sure we have a consistent package name
          ann.asset.name = self.name
          self.asset.pkgInfo.name = self.name
        }

        // build and attach route handlers
        self.router.buildRoutes()
        ann.route = self.router.getRoutes()
        ann.middleware = self.router.getMiddlewares()
      }
    })
    .then(function() {
      if (self.rpc && !isNaN(+options.rpcPort)) {
        // only when a real port is provided
        debug('setup rpc for service "%s"', self.name)
        ann.rpc = self.rpc.getAPIs()
        ann.rpcType = self.rpcType
        ann.rpcPort = options.rpcPort
        return self.startRPCServer(options.rpcPort, options.rpcHost)
      }
    })
    .then(function() {
      var ann = util.inspect(self.announcement, {
        colors: true,
        depth: 4
      })
      debug('service "%s" started with announcement: \n%s\n', self.name, ann)
    })

  return promise
}
<commit_msg>Improve debugging info.<commit_after>/**
 * Module dependencies.
 */
var RPC = require('../rpc')
var path = require('path')
var util = require('util')
var Asset = require('../web/asset')
var debug = require('debug')('micromono:service')
var Router = require('../web/router')
var assign = require('lodash.assign')
var extend = require('ampersand-class-extend')
var EventEmitter = require('eventemitter3')
var Announcement = require('../announcement')

/**
 * MicroMono Service class constructor.
 */
var Service = module.exports = function MicroMonoService() {
  if (!this.packagePath) {
    throw new Error('Please provide `packagePath` property when you extend Service class')
  }

  this.packageInfo = require(path.join(this.packagePath, 'package.json'))
  this.setDefaults(this.packageInfo)
  this.announcement = new Announcement(this)

  this.setupAsset()
  this.setupWeb()
  this.setupRPC()

  if (!this.init) {
    this.init = function() {
      return Promise.resolve()
    }
  }
}

// Provide the ability to extend the Service class.
Service.extend = extend

// Service is an event emitter
assign(Service.prototype, EventEmitter.prototype)

/**
 * Set default options of the service
 *
 * @param {Object} info Object contains service information.
 */
Service.prototype.setDefaults = function(info) {
  this.name = this.name || info.name
  this.baseUrl = this.baseUrl || '/'
  this.version = info.version
}

Service.prototype.setupAsset = function() {
  if (this.packageInfo.jspm) {
    // found jspm info, initialize Asset
    this.asset = new Asset(this.packagePath)
  }
}

Service.prototype.setupWeb = function() {
  if (this.route || this.asset || this.middleware) {
    this.framework = this.framework || 'express'
    this.router = new Router(this)
    this.app = this.router.framework.getApp()
  }
}

Service.prototype.setupRPC = function() {
  if (!this.api) {
    this.api = {}
  }

  // We need at least one api for heartbeating.
  this.api.__ping = function(msg, callback) {
    callback('pong')
  }

  this.rpcType = this.rpcType || 'axon'
  var rpcOptions = {
    api: this.api,
    type: this.rpcType,
    context: this,
    isRemote: false
  }
  this.rpc = new RPC(rpcOptions)
}

/**
 * Get the type of the service instance, remote or not.
 *
 * @return {Boolean} True if this is a farcaster (a fake service rebuilt from
 * announcement of remote service), otherwise false.
 */
Service.prototype.isRemote = function() {
  return false
}

/**
 * Set the instance of native node http.Server instance
 *
 * @param {http.Server} server
 * @emit 'server' {http.Server}
 */
Service.prototype.setHttpServer = function(server) {
  this.server = server
  this.emit('server', server)
}

/**
 * Set or get upgrade url.
 *
 * @param  {String|undefined} upgradeUrl Set the upgrade url when this is string
 * or return the current value if this is undefined.
 * @return {String}           Value of current upgrade url.
 */
Service.prototype.allowUpgrade = function(upgradeUrl) {
  if ('undefined' === typeof upgradeUrl) {
    return this.announcement.upgradeUrl
  } else if (upgradeUrl) {
    upgradeUrl = path.join(this.baseUrl, upgradeUrl)
  }
  return (this.announcement.upgradeUrl = upgradeUrl)
}

/**
 * Start a web server which serves requests for route, asset and middleware
 * provided by this service.
 *
 * @param  {Number|String}  port Port to bind the server.
 * @param  {String}         host Host or ip address to bind the port to.
 * @return {Promise}        A promise instance rejects with error or resolve with
 * instance of http.Server when server started successfully.
 */
Service.prototype.startWebServer = function(port, host) {
  debug('[%s] startWebServer()', this.name)

  if (!this.router) {
    // no need to start http server if we don't have asset or route to serve.
    debug('[%s] no need to start web server', this.name)
    return Promise.resolve()
  }

  var self = this
  host = host || '0.0.0.0'
  port = port || 0

  debug('[%s] start web server at %s:%s', this.name, host, port)

  return this.router.startServer(port, host).then(function(server) {
    if (server) {
      var address = server.address()
      self.announcement.webPort = address.port
      debug('[%s] web server started at %s:%s', self.name, address.address, address.port)

      self.setHttpServer(server)
    }
  })
}

Service.prototype.startRPCServer = function(port, host) {
  host = host || '0.0.0.0'
  port = port || 0
  var self = this
  debug('[%s] start "%s" rpc server at %s:%s', this.name, this.rpc.type, host, port)
  return this.rpc.startServer(port, host).then(function(server) {
    var address = server.address()
    self.announcement.rpcPort = address.port
    debug('[%s] "%s" rpc server started at %s:%s',
      self.name,
      self.rpc.type,
      address.address,
      address.port
    )
  })
}

Service.prototype.run = function(options) {
  var name = this.name
  debug('[%s] run service', name)
  options = options || {}
  var self = this
  var ann = this.announcement

  var promise = this.startWebServer(options.port, options.host)
    .then(function() {
      debug('[%s] init() service ', name)
      return self.init()
    })
    .then(function() {
      if (self.router) {
        debug('[%s] setup router & middleware', name)
        if (self.asset) {
          debug('[%s] setup static asset', name)
          ann.asset = self.asset.parseJSPM()

          // make sure we have a consistent package name
          ann.asset.name = self.name
          self.asset.pkgInfo.name = self.name
        }

        // build and attach route handlers
        self.router.buildRoutes()
        ann.route = self.router.getRoutes()
        ann.middleware = self.router.getMiddlewares()
      }
    })
    .then(function() {
      if (self.rpc && !isNaN(+options.rpcPort)) {
        // only when a real port is provided
        debug('[%s] setup rpc ', name)
        ann.rpc = self.rpc.getAPIs()
        ann.rpcType = self.rpcType
        ann.rpcPort = options.rpcPort
        return self.startRPCServer(options.rpcPort, options.rpcHost)
      }
    })
    .then(function() {
      var annStr = util.inspect(ann, {
        colors: true,
        depth: 4
      })
      debug('[%s] service started with announcement: \n%s\n', name, annStr)
    })

  return promise
}
<|endoftext|>


<commit_before>'use strict'

var miss = require('mississippi')

var setupArchive = miss.through(function (chunck, encoding, callback) {
  var item = JSON.parse(chunck)

  if (item.sendCopyToGuardian && item.dsfGuardian) {
    console.log(item._id + ': setup-archive. Adds guardian')
    var guardian = item.dsfGuardian
    var guardianAddress = {
      secret: item.gotRestrictedAddress,
      id: guardian.FODT.toString() + guardian.PERS.toString(),
      firstName: guardian['NAVN-F'],
      middleName: guardian['NAVN-M'],
      lastName: guardian['NAVN-S'],
      streetAddress: guardian.ADR,
      zip: guardian.POSTN,
      city: guardian.POSTS
    }
    item.archive.guardian = guardianAddress
  }

  if (item.sendCopyToGuardian && !item.dsfGuardian) {
    item.noGuardianFound = true
  }

  console.log(item._id + ': setup-archive')

  return callback(null, JSON.stringify(item))
})

module.exports = setupArchive
<commit_msg>Changes restricted address filter<commit_after>'use strict'

var miss = require('mississippi')

var setupArchive = miss.through(function (chunck, encoding, callback) {
  var item = JSON.parse(chunck)

  item.archive.student.secret = item.gotRestrictedAddress

  if (item.sendCopyToGuardian && item.dsfGuardian) {
    console.log(item._id + ': setup-archive. Adds guardian')
    var guardian = item.dsfGuardian
    var guardianAddress = {
      id: guardian.FODT.toString() + guardian.PERS.toString(),
      firstName: guardian['NAVN-F'],
      middleName: guardian['NAVN-M'],
      lastName: guardian['NAVN-S'],
      streetAddress: guardian.ADR,
      zip: guardian.POSTN,
      city: guardian.POSTS
    }
    item.archive.guardian = guardianAddress
  }

  if (item.sendCopyToGuardian && !item.dsfGuardian) {
    item.noGuardianFound = true
  }

  console.log(item._id + ': setup-archive')

  return callback(null, JSON.stringify(item))
})

module.exports = setupArchive
<|endoftext|>


<commit_before>/**
 * default shower
 */

var util = require('util')
  , Base = require('./base')
  , tips = require('../../txt/tips')
  ;

util.inherits(Ashees, Base);
function Ashees(){
  var that = this;
  Base.call(this);

  this.on('pendStart', function(){
    process.stdout.write('[ ')
  });
  this.on('pending', function(){
    process.stdout.write(this.color('\b=>').cyan)
  });

  this.on('pendDone', function(){
    process.stdout.write(']\n');
  });
  this.on('pendFail', function(err){
    process.stdout.write(this.color('※').error);
  });

}

var statusTpl = '{{date}}({{status_id}}) from {{source}}\n{{name}}({{user_id}}): {{text}}{{pic}}|{{reposts_count}}/{{comments_count}}';

//扩展默认颜色表
Ashees.prototype.colors.name = Ashees.prototype.colors.green;
Ashees.prototype.colors.mention =35;
Ashees.prototype.colors.url = 94;

Ashees.prototype.showStatus = function(status){
  var user = status.user || {};
  process.stdout.write(

    statusTpl.replace('{{name}}', this.color(user.screen_name || '').name)
    .replace('{{user_id}}', user.idstr || '')
    .replace('{{text}}', status.text)
    .replace('{{status_id}}', status.idstr)
    .replace('{{date}}', this.color(status.created_at).grey)
    .replace('{{pic}}', status.original_pic ? '[pic: ' + status.original_pic + ']' : '')
    .replace('{{comments_count}}', status.comments_count || '\b')
    .replace('{{reposts_count}}', status.reposts_count || '\b')
    .replace('{{source}}', this.color((status.source || '').replace(/.+>(.+?)<\/a>$/, '$1')).grey)
    .replace(/(@[^\s\:\\\/\[]+)/g, this.color('$1').mention)
    .replace(/(http\:\/\/[^\s\]]+)/g, this.color('$1').url)
    .replace(/(#.+?#)/g, this.color('$1').url)

  );
  if(status.retweeted_status){
    process.stdout.write("\n  转自: ");
    this.showStatus(status.retweeted_status);
  }
  //log('微博详情: ' + util.inspect(status))
  process.stdout.write('\n\n')
}

module.exports = Ashees;<commit_msg>ashees mentions<commit_after>/**
 * default shower
 */

var util = require('util')
  , Base = require('./base')
  , tips = require('../../txt/tips')
  ;

util.inherits(Ashees, Base);
function Ashees(){
  var that = this;
  Base.call(this);

  this.on('pendStart', function(){
    process.stdout.write('[ ')
  });
  this.on('pending', function(){
    process.stdout.write(this.color('\b=>').cyan)
  });

  this.on('pendDone', function(){
    process.stdout.write(']\n');
  });
  this.on('pendFail', function(err){
    process.stdout.write(this.color('※').error);
  });

}

var statusTpl = '{{date}}({{status_id}}) from {{source}}\n{{name}}({{user_id}}): {{text}}{{pic}}|{{reposts_count}}/{{comments_count}}';

//扩展默认颜色表
Ashees.prototype.colors.name = Ashees.prototype.colors.green;
Ashees.prototype.colors.mention =35;
Ashees.prototype.colors.url = 94;

Ashees.prototype.showStatus = function(status){
  var user = status.user || {};
  process.stdout.write(

    statusTpl.replace('{{name}}', this.color(user.screen_name || '').name)
    .replace('{{user_id}}', user.idstr || '')
    .replace('{{text}}', status.text)
    .replace('{{status_id}}', status.idstr)
    .replace('{{date}}', this.color(status.created_at).grey)
    .replace('{{pic}}', status.original_pic ? '[pic: ' + status.original_pic + ']' : '')
    .replace('{{comments_count}}', status.comments_count || '\b')
    .replace('{{reposts_count}}', status.reposts_count || '\b')
    .replace('{{source}}', this.color((status.source || '').replace(/.+>(.+?)<\/a>$/, '$1')).grey)
    .replace(/(@[^\s\:\\\/\[\：]+)/g, this.color('$1').mention)
    .replace(/(http\:\/\/[^\s\]]+)/g, this.color('$1').url)
    .replace(/(#.+?#)/g, this.color('$1').url)

  );
  if(status.retweeted_status){
    process.stdout.write("\n  转自: ");
    this.showStatus(status.retweeted_status);
  }
  //log('微博详情: ' + util.inspect(status))
  process.stdout.write('\n\n')
}

module.exports = Ashees;<|endoftext|>