<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.Confidence = factory();
  }
}(this, function () {
  /** Private Constants */
  var DEFAULT_Z_SCORE = 1.96;
  var DEFAULT_MARGIN_OF_ERROR = 0.01;
  var VERSION = '1.1.0';

  var Confidence = function(settings) {
    settings = settings || { };

    this._zScore = settings.zScore || DEFAULT_Z_SCORE;
    this._marginOfError = settings.marginOfError || DEFAULT_MARGIN_OF_ERROR;
    this._variants = { };
    this._confidenceIntervals = { };
  };

  Confidence.version = VERSION;

  /** Public Constants **/

  Confidence.prototype.addVariant = function(variant) {
    // TODO verify variant first
    // variant must have properties name, conversionCount, eventCount
    if (variant.hasOwnProperty('id') &&
      variant.hasOwnProperty('name') &&
      variant.hasOwnProperty('conversionCount') &&
      variant.hasOwnProperty('eventCount')) {
      this._variants[variant.id] = variant;
    } else {
      throw new Error('variant object needs name, conversionCount, and eventCount properties');
    }
  };

  Confidence.prototype.getVariant = function(variantID) {
    if (this._variants.hasOwnProperty(variantID)) {
      return this._variants[variantID];
    } else {
      throw new Error('The variant you requested does not exist.');
    }
  };

  Confidence.prototype.hasVariants = function(variants) {
    for(var variant in variants) {
      if(variants.hasOwnProperty(variant)) {
        return true;
      }
    }
    return false;
  };

  Confidence.prototype.getResult = function() {
    if (this.hasVariants(this._variants)) {

      confidenceIntervals = {};

      var result;
      // for each variant in variants
      for (var variantID in this._variants) {
        // get sample size required for statistically significant answer
        var requiredSampleSize = this.getRequiredSampleSize(variantID);

        // do we have a winner to pass into the result
        var hasWinner = false;

        // verify whether we have enough data
        var hasEnoughData = this.hasEnoughData(variantID);

        // If we don't have enough data yet, we cannot yet declare a result.
        if (!hasEnoughData) {
          result = {
            hasWinner: hasWinner,
            hasEnoughData: hasEnoughData,
            winnerID: null,
            winnerName: null,
            confidenceInterval: null,
            readable: "There is not enough data to determine a conclusive result."
          };
          return result;
        }

        //calculate confidence interval
        var confidenceInterval = this.getConfidenceInterval(variantID);

        confidenceIntervals[variantID] = confidenceInterval;
      }

      // At this point, we have enough data to determine whether there is a winner or not
      result = this.analyzeConfidenceIntervals(confidenceIntervals);
      return result;
    } else {
      throw new Error('There are no variants available.');
    }
  };

  Confidence.prototype.analyzeConfidenceIntervals = function(confidenceIntervals) {
    // TODO if confidence interval bad format, throw an error

    var minimums = [];
    var maximums = [];

    // split confidence intervals into a list of mins and maxes.
    for (var id in confidenceIntervals) {
      // instantiate object
      var min = confidenceIntervals[id].min;
      minimums.push({ id: id, val: min });

      var max = confidenceIntervals[id].max;
      maximums.push({ id: id, val: max });
    }

    // sort list of minimums greatest to least
    minimums = this.sortList(minimums);

    // identify ID with the largest min
    var idWithLargestMin = minimums[0].id;
    var largestMin = minimums[0].val;

    // sort list of maximums greatest to least
    maximums = this.sortList(maximums);

    // remove the ID with the largest min from the list of maximums.
    for (var index = 0; index < maximums.length; index++) {
      var obj = maximums[index];

      if (obj.id == idWithLargestMin) {
        maximums.splice(index, 1);
      }
    }

    // identify ID with the largest max and its value
    var idWithLargestMax = maximums[0].id;
    var largestMax = maximums[0].val;

    var result;

    var hasWinner;
    var hasEnoughData;

    // if highest min > highest max, declare the ID of the winner to be the min
    if (largestMin > largestMax) {
      winningVariantName = this._variants[idWithLargestMin].name;
      var roundedMin = (Math.round(10000 * confidenceIntervals[idWithLargestMin].min)/100);
      var roundedMax = (Math.round(10000 * confidenceIntervals[idWithLargestMin].max)/100);

      var message = "With 95% confidence, the true population parameter of the \"";
      message += winningVariantName + "\" variant will fall between ";
      message += roundedMin + "% and ";
      message += roundedMax + "%.";
      hasWinner = true;
      hasEnoughData = true;

      result = {
        hasWinner: hasWinner,
        hasEnoughData: hasEnoughData,
        winnerID: idWithLargestMin,
        winnerName: winningVariantName,
        confidenceInterval: { min: roundedMin, max: roundedMax },
        readable: message
      };
      return result;
    } else {
      // otherwise, there is no winner
      var messageNoWinner = "There is no winner, the results are too close.";

      hasWinner = false;
      hasEnoughData = true;

      result = {
        hasWinner: hasWinner,
        hasEnoughData: hasEnoughData,
        winnerID: null,
        winnerName: null,
        confidenceInterval: null,
        readable: messageNoWinner
      };
    }

    return result;
  };

  // Sorts list from greatest to least
  Confidence.prototype.sortList = function(list) {
    list.sort(function(a, b) {
      return b.val - a.val;
    });
    return list;
  };

  // Are these result statistically significant?
  // (zscore^2 * stdErr * (1 - stdErr)) / marginErr^2
  Confidence.prototype.getRequiredSampleSize = function(variantID) {
    var standardError = this.getStandardError(variantID);
    var numerator = (Math.pow(this._zScore, 2) * standardError * (1 - standardError));
    var denominator = Math.pow(this._marginOfError, 2);

    var requiredSampleSize = Math.max((numerator/denominator), 100);
    return requiredSampleSize;
  };

  Confidence.prototype.hasEnoughData = function(variantID) {
    var variant = this.getVariant(variantID);
    var requiredSampleSize = this.getRequiredSampleSize(variantID);
    if (variant.eventCount >= requiredSampleSize) {
      return true;
    } else {
      return false;
    }
  };

  Confidence.prototype.getRate = function(variantID) {
    var variant = this.getVariant(variantID);
    if (variant.eventCount === 0) {
      throw new Error('Total is zero: cannot divide by zero to produce rate.');
    } else if (variant.eventCount < 0) {
      throw new Error('Total is negative: cannot use a negative number to produce rate.');
    } else {
      var rate = variant.conversionCount / variant.eventCount;
      return rate;
    }
  };

  // Calculate the interval for which we are <zscore> confident
  // rate +- (zscore * standard error)
  Confidence.prototype.getConfidenceInterval = function(variantID) {
    var confidenceInterval = {};
    var rate = this.getRate(variantID);
    var standardError = this.getStandardError(variantID);
    //lower limit
    var min = rate - (this._zScore * standardError);
    //upper limit
    var max = rate + (this._zScore * standardError);

    confidenceInterval = { min: min, max: max };

    return confidenceInterval;
  };

  // Calculate standard error:
  // SE = sqrt(rate*(1-rate)/total)
  Confidence.prototype.getStandardError = function(variantID) {
    var variant = this.getVariant(variantID);

    //Throw error if rate is not okay.
    var rate = this.getRate(variantID);

    //Check total Count - if event count is 0
    var standardError = Math.sqrt(rate * (1 - rate) / variant.eventCount);
    return standardError;
  };
  return Confidence;
}));
<commit_msg>Optional Variant Name parameter<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.Confidence = factory();
  }
}(this, function () {
  /** Private Constants */
  var DEFAULT_Z_SCORE = 1.96;
  var DEFAULT_MARGIN_OF_ERROR = 0.01;
  var VERSION = '1.1.0';

  var Confidence = function(settings) {
    settings = settings || { };

    this._zScore = settings.zScore || DEFAULT_Z_SCORE;
    this._marginOfError = settings.marginOfError || DEFAULT_MARGIN_OF_ERROR;
    this._variants = { };
    this._confidenceIntervals = { };
  };

  Confidence.version = VERSION;

  /** Public Constants **/

  Confidence.prototype.addVariant = function(variant) {
    // TODO verify variant first
    // variant must have properties conversionCount, eventCount
    if (variant.hasOwnProperty('id') &&
      variant.hasOwnProperty('conversionCount') &&
      variant.hasOwnProperty('eventCount')) {
      if(!variant.hasOwnProperty('name')) {
        variant['name'] = 'Variant ' + variant.id;
      }
      this._variants[variant.id] = variant;
    } else {
      throw new Error('variant object needs conversionCount and eventCount properties');
    }
  };

  Confidence.prototype.getVariant = function(variantID) {
    if (this._variants.hasOwnProperty(variantID)) {
      return this._variants[variantID];
    } else {
      throw new Error('The variant you requested does not exist.');
    }
  };

  Confidence.prototype.hasVariants = function(variants) {
    for(var variant in variants) {
      if(variants.hasOwnProperty(variant)) {
        return true;
      }
    }
    return false;
  };

  Confidence.prototype.getResult = function() {
    if (this.hasVariants(this._variants)) {

      confidenceIntervals = {};

      var result;
      // for each variant in variants
      for (var variantID in this._variants) {
        // get sample size required for statistically significant answer
        var requiredSampleSize = this.getRequiredSampleSize(variantID);

        // do we have a winner to pass into the result
        var hasWinner = false;

        // verify whether we have enough data
        var hasEnoughData = this.hasEnoughData(variantID);

        // If we don't have enough data yet, we cannot yet declare a result.
        if (!hasEnoughData) {
          result = {
            hasWinner: hasWinner,
            hasEnoughData: hasEnoughData,
            winnerID: null,
            winnerName: null,
            confidenceInterval: null,
            readable: "There is not enough data to determine a conclusive result."
          };
          return result;
        }

        //calculate confidence interval
        var confidenceInterval = this.getConfidenceInterval(variantID);

        confidenceIntervals[variantID] = confidenceInterval;
      }

      // At this point, we have enough data to determine whether there is a winner or not
      result = this.analyzeConfidenceIntervals(confidenceIntervals);
      return result;
    } else {
      throw new Error('There are no variants available.');
    }
  };

  Confidence.prototype.analyzeConfidenceIntervals = function(confidenceIntervals) {
    // TODO if confidence interval bad format, throw an error

    var minimums = [];
    var maximums = [];

    // split confidence intervals into a list of mins and maxes.
    for (var id in confidenceIntervals) {
      // instantiate object
      var min = confidenceIntervals[id].min;
      minimums.push({ id: id, val: min });

      var max = confidenceIntervals[id].max;
      maximums.push({ id: id, val: max });
    }

    // sort list of minimums greatest to least
    minimums = this.sortList(minimums);

    // identify ID with the largest min
    var idWithLargestMin = minimums[0].id;
    var largestMin = minimums[0].val;

    // sort list of maximums greatest to least
    maximums = this.sortList(maximums);

    // remove the ID with the largest min from the list of maximums.
    for (var index = 0; index < maximums.length; index++) {
      var obj = maximums[index];

      if (obj.id == idWithLargestMin) {
        maximums.splice(index, 1);
      }
    }

    // identify ID with the largest max and its value
    var idWithLargestMax = maximums[0].id;
    var largestMax = maximums[0].val;

    var result;

    var hasWinner;
    var hasEnoughData;

    // if highest min > highest max, declare the ID of the winner to be the min
    if (largestMin > largestMax) {
      winningVariantName = this._variants[idWithLargestMin].name;
      var roundedMin = (Math.round(10000 * confidenceIntervals[idWithLargestMin].min)/100);
      var roundedMax = (Math.round(10000 * confidenceIntervals[idWithLargestMin].max)/100);

      var message = "With 95% confidence, the true population parameter of the \"";
      message += winningVariantName + "\" variant will fall between ";
      message += roundedMin + "% and ";
      message += roundedMax + "%.";
      hasWinner = true;
      hasEnoughData = true;

      result = {
        hasWinner: hasWinner,
        hasEnoughData: hasEnoughData,
        winnerID: idWithLargestMin,
        winnerName: winningVariantName,
        confidenceInterval: { min: roundedMin, max: roundedMax },
        readable: message
      };
      return result;
    } else {
      // otherwise, there is no winner
      var messageNoWinner = "There is no winner, the results are too close.";

      hasWinner = false;
      hasEnoughData = true;

      result = {
        hasWinner: hasWinner,
        hasEnoughData: hasEnoughData,
        winnerID: null,
        winnerName: null,
        confidenceInterval: null,
        readable: messageNoWinner
      };
    }

    return result;
  };

  // Sorts list from greatest to least
  Confidence.prototype.sortList = function(list) {
    list.sort(function(a, b) {
      return b.val - a.val;
    });
    return list;
  };

  // Are these result statistically significant?
  // (zscore^2 * stdErr * (1 - stdErr)) / marginErr^2
  Confidence.prototype.getRequiredSampleSize = function(variantID) {
    var standardError = this.getStandardError(variantID);
    var numerator = (Math.pow(this._zScore, 2) * standardError * (1 - standardError));
    var denominator = Math.pow(this._marginOfError, 2);

    var requiredSampleSize = Math.max((numerator/denominator), 100);
    return requiredSampleSize;
  };

  Confidence.prototype.hasEnoughData = function(variantID) {
    var variant = this.getVariant(variantID);
    var requiredSampleSize = this.getRequiredSampleSize(variantID);
    if (variant.eventCount >= requiredSampleSize) {
      return true;
    } else {
      return false;
    }
  };

  Confidence.prototype.getRate = function(variantID) {
    var variant = this.getVariant(variantID);
    if (variant.eventCount === 0) {
      throw new Error('Total is zero: cannot divide by zero to produce rate.');
    } else if (variant.eventCount < 0) {
      throw new Error('Total is negative: cannot use a negative number to produce rate.');
    } else {
      var rate = variant.conversionCount / variant.eventCount;
      return rate;
    }
  };

  // Calculate the interval for which we are <zscore> confident
  // rate +- (zscore * standard error)
  Confidence.prototype.getConfidenceInterval = function(variantID) {
    var confidenceInterval = {};
    var rate = this.getRate(variantID);
    var standardError = this.getStandardError(variantID);
    //lower limit
    var min = rate - (this._zScore * standardError);
    //upper limit
    var max = rate + (this._zScore * standardError);

    confidenceInterval = { min: min, max: max };

    return confidenceInterval;
  };

  // Calculate standard error:
  // SE = sqrt(rate*(1-rate)/total)
  Confidence.prototype.getStandardError = function(variantID) {
    var variant = this.getVariant(variantID);

    //Throw error if rate is not okay.
    var rate = this.getRate(variantID);

    //Check total Count - if event count is 0
    var standardError = Math.sqrt(rate * (1 - rate) / variant.eventCount);
    return standardError;
  };
  return Confidence;
}));
<|endoftext|>


<commit_before>// HEPGEN-JS SETTINGS (please configure)
// ------------------------------------------------------

var call_id = Math.random().toString(36).substring(7) + '@127.0.0.1';

var config = {
        NAME: 'LOG Lines',
        HEP_SERVER: '127.0.0.1',
        HEP_PORT: 9060,
        HEP_ID: '2001',
        HEP_AUTH: 'myHep',
        // the Messages to send
        MESSAGES: [
          {
                // Session Log
                  rcinfo: {
                          type: 'HEP',
                          version: 3,
                          payload_type: 100,
                          captureId: '2001',
                          capturePass: 'myHep',
                          ip_family: 2,
                          protocol: 17,
                          proto_type: 100,
                          srcIp: '192.168.1.1',
                          dstIp: '192.168.1.2',
                          srcPort: 0,
                          dstPort: 0,
                          correlation_id: call_id
                  },
    		          pause: 1000,
                  payload: 'SYSLOG: Processing OPTIONS request from nodejs using Call-Id: '+call_id
          },
          {
                // Session Log
                  rcinfo: {
                          type: 'HEP',
                          version: 3,
                          payload_type: 100,
                          captureId: '2001',
                          capturePass: 'myHep',
                          ip_family: 2,
                          protocol: 17,
                          proto_type: 100,
                          srcIp: '192.168.1.1',
                          dstIp: '192.168.1.2',
                          srcPort: 0,
                          dstPort: 0,
                          correlation_id: call_id
                  },
    		          pause: 1000,
                  payload: '{ "this": { "is": "a JSON object" }, "int": 1234 }'
          }
      ]
};

// ------------------------------------------------------

module.exports = config;
<commit_msg>Update log.js<commit_after>// HEPGEN-JS SETTINGS (please configure)
// ------------------------------------------------------

var call_id = Math.random().toString(36).substring(7) + '@127.0.0.1';

var config = {
        NAME: 'LOG Lines',
        HEP_SERVER: '127.0.0.1',
        HEP_PORT: 9060,
        HEP_ID: '2001',
        HEP_AUTH: 'myHep',
        // the Messages to send
        MESSAGES: [
          {
                // Session Log
                  rcinfo: {
                          type: 'HEP',
                          version: 3,
                          payload_type: 100,
                          captureId: '2001',
                          capturePass: 'myHep',
                          ip_family: 2,
                          protocol: 17,
                          proto_type: 100,
                          srcIp: '192.168.1.1',
                          dstIp: '192.168.1.2',
                          srcPort: 0,
                          dstPort: 0,
                          correlation_id: call_id
                  },
    		          pause: 1000,
                  payload: 'SYSLOG: Processing OPTIONS request from nodejs using Call-Id: '+call_id
          },
          {
                // Session Log
                  rcinfo: {
                          type: 'HEP',
                          version: 3,
                          payload_type: 100,
                          captureId: '2001',
                          capturePass: 'myHep',
                          ip_family: 2,
                          protocol: 17,
                          proto_type: 100,
                          srcIp: '192.168.1.1',
                          dstIp: '192.168.1.2',
                          srcPort: 0,
                          dstPort: 0,
                          correlation_id: call_id
                  },
    		          pause: 1000,
                  payload: '{ "this": { "is": "a JSON object" }, "int": 1234 }'
          },
          {
                  rcinfo: {
    			  type: 'API',
    			  method: 'POST',
			  url: 'http://some.api/post',
			  port: 1234,
			  headers: {
                            'Content-Type': 'application/json'
                          }
    		    },
    		    pause: 0,
            	    payload: {
				  "streams": [
				    {
				      "labels": "{foo=\"bar\"}",
				      "entries": [{ "ts": "2018-12-18T08:28:06.801064-04:00", "line": "baz" }]
				    }
				  ]
			      }
            }
      ]
};

// ------------------------------------------------------

module.exports = config;
<|endoftext|>


<commit_before>"use strict";
// Config file loader

var fs = require('fs');

// for "ini" type files
var regex = {
    section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
    param:   /^\s*([\w@\._]+)\s*=\s*(.*)\s*$/,
    comment: /^\s*[;#].*$/,
    line:    /^\s*(.*)\s*$/,
    blank:   /^\s*$/
};

var cfreader = exports;

cfreader.watch_files = true;
cfreader._config_cache = {};

cfreader.read_config = function(name, type) {
    // Check cache first
    if (cfreader._config_cache[name]) {
        return cfreader._config_cache[name];
    }

    // load config file
    var result = cfreader.load_config(name, type);

    if (cfreader.watch_files) {
        fs.unwatchFile(name);
        fs.watchFile(name, function (curr, prev) {
            // file has changed
            if (curr.mtime.getTime() !== prev.mtime.getTime()) {
                cfreader.load_config(name, type);
            }
        });
    }

    return result;
}

cfreader.empty_config = function(type) {
    if (type === 'ini') {
        return { main: {} };
    }
    else if (type === 'json') {
        return {};
    }
    else {
        return [];
    }
};

cfreader.load_config = function(name, type) {

    var result;

    if (type === 'ini' || /\.ini$/.test(name)) {
        result = cfreader.load_ini_config(name);
    }
    else if (type === 'json' || /\.json$/.test(name)) {
        result = cfreader.load_json_config(name);
    }
    else {
        result = cfreader.load_flat_config(name, type);
        if (result && type !== 'list' && type !== 'data') {
            result = result[0];
            if (/^\d+$/.test(result)) {
                result = parseInt(result);
            }
        }
    }

    cfreader._config_cache[name] = result;

    return result;
};

cfreader.load_json_config = function(name) {
    return JSON.parse(fs.readFileSync(name));
}

cfreader.load_ini_config = function(name) {
    var result       = cfreader.empty_config('ini');
    var current_sect = result.main;

    var data = new String(fs.readFileSync(name));
    var lines = data.split(/\r\n|\r|\n/);
    var match;

    lines.forEach( function(line) {
        if (regex.comment.test(line)) {
            return;
        }
        else if (regex.blank.test(line)) {
            return;
        }
        else if (match = regex.param.exec(line)) {
            if (/^\d+$/.test(match[2])) {
                current_sect[match[1]] = parseInt(match[2]);
            }
            else {
                current_sect[match[1]] = match[2];
            }
        }
        else if (match = regex.section.exec(line)) {
            current_sect = result[match[1]] = {};
        }
        else {
            // error ?
        };
    });

    return result;
};

cfreader.load_flat_config = function(name, type) {
    var result = [];
    var data   = new String(fs.readFileSync(name));
    if (type === 'data') {
        while (data.length > 0) {
            var match = data.match(/^([^\n]*)\n?/);
            result.push(match[1]);
            data = data.slice(match[0].length);
        }
        return result;
    }
    var lines  = data.split(/\r\n|\r|\n/);

    lines.forEach( function(line) {
        var line_data;
        if (regex.comment.test(line)) {
            return;
        }
        else if (regex.blank.test(line)) {
            return;
        }
        else if (line_data = regex.line.exec(line)) {
            result.push(line_data[1]);
        }
    });

    return result;
};
<commit_msg>Read files as UTF8<commit_after>"use strict";
// Config file loader

var fs = require('fs');

// for "ini" type files
var regex = {
    section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
    param:   /^\s*([\w@\._]+)\s*=\s*(.*)\s*$/,
    comment: /^\s*[;#].*$/,
    line:    /^\s*(.*)\s*$/,
    blank:   /^\s*$/
};

var cfreader = exports;

cfreader.watch_files = true;
cfreader._config_cache = {};

cfreader.read_config = function(name, type) {
    // Check cache first
    if (cfreader._config_cache[name]) {
        return cfreader._config_cache[name];
    }

    // load config file
    var result = cfreader.load_config(name, type);

    if (cfreader.watch_files) {
        fs.unwatchFile(name);
        fs.watchFile(name, function (curr, prev) {
            // file has changed
            if (curr.mtime.getTime() !== prev.mtime.getTime()) {
                cfreader.load_config(name, type);
            }
        });
    }

    return result;
}

cfreader.empty_config = function(type) {
    if (type === 'ini') {
        return { main: {} };
    }
    else if (type === 'json') {
        return {};
    }
    else {
        return [];
    }
};

cfreader.load_config = function(name, type) {

    var result;

    if (type === 'ini' || /\.ini$/.test(name)) {
        result = cfreader.load_ini_config(name);
    }
    else if (type === 'json' || /\.json$/.test(name)) {
        result = cfreader.load_json_config(name);
    }
    else {
        result = cfreader.load_flat_config(name, type);
        if (result && type !== 'list' && type !== 'data') {
            result = result[0];
            if (/^\d+$/.test(result)) {
                result = parseInt(result);
            }
        }
    }

    cfreader._config_cache[name] = result;

    return result;
};

cfreader.load_json_config = function(name) {
    return JSON.parse(fs.readFileSync(name));
}

cfreader.load_ini_config = function(name) {
    var result       = cfreader.empty_config('ini');
    var current_sect = result.main;

    var data = fs.readFileSync(name, "UTF-8");
    var lines = data.split(/\r\n|\r|\n/);
    var match;

    lines.forEach( function(line) {
        if (regex.comment.test(line)) {
            return;
        }
        else if (regex.blank.test(line)) {
            return;
        }
        else if (match = regex.param.exec(line)) {
            if (/^\d+$/.test(match[2])) {
                current_sect[match[1]] = parseInt(match[2]);
            }
            else {
                current_sect[match[1]] = match[2];
            }
        }
        else if (match = regex.section.exec(line)) {
            current_sect = result[match[1]] = {};
        }
        else {
            // error ?
        };
    });

    return result;
};

cfreader.load_flat_config = function(name, type) {
    var result = [];
    var data   = fs.readFileSync(name, "UTF-8");
    if (type === 'data') {
        while (data.length > 0) {
            var match = data.match(/^([^\n]*)\n?/);
            result.push(match[1]);
            data = data.slice(match[0].length);
        }
        return result;
    }
    var lines  = data.split(/\r\n|\r|\n/);

    lines.forEach( function(line) {
        var line_data;
        if (regex.comment.test(line)) {
            return;
        }
        else if (regex.blank.test(line)) {
            return;
        }
        else if (line_data = regex.line.exec(line)) {
            result.push(line_data[1]);
        }
    });

    return result;
};
<|endoftext|>


<commit_before>const Collection = require('discord.js').Collection;
const bot = require('../Discord/index.js');
const fs = require('fs');
const path = require('path');
const Log = require('../Util/Log');

class Events {
  constructor() {
    this.events = {};
    this.eventDir = path.resolve(__dirname, './Events');
    this.eventsList = new Collection();

    this.bot = bot;
    this.setup();
  }

  async setGitlab(gitlab) {
    this.gitlab = gitlab;
  }

  async setup() {
    fs.readdir(this.eventDir, (err, files) => {
      if (err) throw err;

      files.forEach(file => {
        let eventName = file.replace(`.js`, ``);
        try {
          let event = require(`./Events/${eventName}`);
          this.eventsList.set(eventName, new event(this.gitlab, this.bot));
          Log.info(`GitHub | Loading Event ${eventName.replace(`-`, `/`)} 👌`);
        } catch (e) {
          Log.info(`GitHub | Loading Event ${eventName} ❌`);
          Log.error(e);
        }
      });

      return;
    });
  }

  use(data, eventName, choice = 'channel') {
    const action = data.object_attributes && data.object_attribute.action ? data.object_attribute.action : '';
    eventName = eventName.replace(` Hook`, '').replace(/ /g, '_').toLowerCase();
    let event = action ? `${eventName}-${action}` : eventName;
    try {
      event = this.eventsList.get(event) || this.eventsList.get('Unknown');
      if (choice === 'channel') {
        let text = event.text(data, eventName, action);
        return Array.isArray(text) ? text.join('\n') : text;
      }
      let embedContent = event.embed(data, eventName, action);
      return this.parseEmbed(embedContent, data);
    } catch (e) {
      Log.error(e);
    }
  }

  parseEmbed(embed, data) {
    switch (embed.color) {
      case 'success':
        embed.color = 0x3CA553;
        break;
      case 'warning':
        embed.color = 0xFB5432;
        break;
      case 'danger':
      case 'error':
        embed.color = 0xCE0814;
        break;
      default:
        if (embed.color) embed.color = parseInt(`0x${embed.color.replace(`0x`, ``)}`, 16);
        break;
    }
    embed.author = {
      name: data.user_name,
      icon_url: data.user_avatar || null,
    };
    embed.footer = {
      text: data.project.path_with_namespace,
    };
    embed.url = embed.url || data.project.web_url;
    embed.timestamp = new Date();
    return embed;
  }
}

module.exports = new Events();
<commit_msg>Improved Gitlab event handler<commit_after>const Collection = require('discord.js').Collection;
const bot = require('../Discord/index.js');
const fs = require('fs');
const path = require('path');
const Log = require('../Util/Log');

class Events {
  constructor() {
    this.events = {};
    this.eventDir = path.resolve(__dirname, './Events');
    this.eventsList = new Collection();

    this.bot = bot;
    this.setup();
  }

  async setGitlab(gitlab) {
    this.gitlab = gitlab;
  }

  async setup() {
    fs.readdir(this.eventDir, (err, files) => {
      if (err) throw err;

      files.forEach(file => {
        let eventName = file.replace(`.js`, ``);
        try {
          let event = require(`./Events/${eventName}`);
          this.eventsList.set(eventName, new event(this.gitlab, this.bot));
          Log.info(`GitHub | Loading Event ${eventName.replace(`-`, `/`)} 👌`);
        } catch (e) {
          Log.info(`GitHub | Loading Event ${eventName} ❌`);
          Log.error(e);
        }
      });

      return;
    });
  }

  use(data, eventName, choice = 'channel') {
    const action = data.object_attributes ? data.object_attributes.action : '';
    eventName = eventName.replace(` Hook`, '').replace(/ /g, '_').toLowerCase();
    let event = action ? `${eventName}-${action}` : eventName;
    try {
      event = this.eventsList.get(event) || this.eventsList.get('Unknown');
      if (choice === 'channel') {
        let text = event.text(data, eventName, action);
        return Array.isArray(text) ? text.join('\n') : text;
      }
      let embedContent = event.embed(data, eventName, action);
      return this.parseEmbed(embedContent, data);
    } catch (e) {
      Log.error(e);
    }
  }

  parseEmbed(embed, data) {
    switch (embed.color) {
      case 'success':
        embed.color = 0x3CA553;
        break;
      case 'warning':
        embed.color = 0xFB5432;
        break;
      case 'danger':
      case 'error':
        embed.color = 0xCE0814;
        break;
      default:
        if (embed.color) embed.color = typeof embed.color === 'string' ? parseInt(`0x${embed.color.replace(`0x`, ``)}`, 16) : embed.color;
        break;
    }
    embed.author = {
      name: data.user_name,
      icon_url: data.user_avatar || null,
    };
    embed.footer = {
      text: data.project.path_with_namespace,
    };
    embed.url = embed.url || data.project.web_url;
    embed.timestamp = new Date();
    return embed;
  }
}

module.exports = new Events();
<|endoftext|>


<commit_before>/**
 * Pluggable Version for [react-navigation](https://reactnavigation.org/).
 * The BottomNavigation gets its options from a separate namespace in
 * `tabBarOptions` inside TabNavigatorConfig, namely `bottomNavigationOptions`.
 * @flow
 */

import React, { PureComponent } from 'react'
import BottomNavigation, { Tab } from '../'

type NCProps = {
  // I could use react-navigation's type definitions, but I don't want to
  // include it as a dependency or risk throwing an error because the package
  // is not found. So: `any`
  navigationState: any,
  jumpToIndex: (index: number) => void,
  getLabel: (scene: any) => ?(React.Element<*> | string),
  getLabelText?: (scene: any) => ?(React.Element<*> | string),
  renderIcon: (scene: any) => React.Element<*>,
  style?: any,
  bottomNavigationOptions: any,
  activeTintColor?: string,
  inactiveTintColor?: string
}

export default
class NavigationComponent extends PureComponent<void, NCProps, void> {
  render() {
    // react-navigation passed props
    const {
      activeTintColor,
      inactiveTintColor,
      navigationState,
      bottomNavigationOptions,
      getLabel: navigationGetLabel,
      getLabelText: navigationGetLabelOld,
      renderIcon,
      jumpToIndex,
      style
    } = this.props

    const bnOptions = bottomNavigationOptions || {}

    // Support for earlier version of react-navigation (up to 1.0.0-beta5)
    const getLabel = navigationGetLabel || navigationGetLabelOld

    // BottomNavigation's style
    const { style: bnStyle } = bnOptions

    // Builded props for BottomNavigation
    const bnProps = {
      labelColor: bnOptions.labelColor,
      innerStyle: bnOptions.innerStyle,
      activeLabelColor: bnOptions.activeLabelColor,
      rippleColor: bnOptions.rippleColor,
      backgroundColor: bnOptions.backgroundColor,
      shifting: bnOptions.shifting
    }

    return (
      <BottomNavigation
        activeTab={navigationState.index}
        // Style has default `height: 56`, so you can in theory skip styling
        // completely. After that, it uses the styles inside the
        // bottomNavigationOptions namespace. Aa a last resort, the styles from
        // `tabBarOptions` will be added.
        style={[ { height: 56 }, bnStyle || style ]}
        onTabChange={(index) => jumpToIndex(index)}
        {...bnProps}
      >
        {navigationState.routes.map((route, index) => {
          const focused = index === navigationState.index

          // scene object for `getLabel` and `renderIcon`
          const scene = {
            route,
            index,
            focused,
            tintColor: focused ? activeTintColor : inactiveTintColor
          }
          const label = getLabel(scene)
          const icon = renderIcon(scene)

          // Prepare props for the tabs
          const tabs = bnOptions.tabs || {}
          const tabOptions = tabs[route.key] || {}
          const tabProps = {
            icon: tabOptions.icon || icon,
            activeIcon: tabOptions.activeIcon,
            label: tabOptions.label || label,
            labelColor: tabOptions.labelColor,
            activeLabelColor: tabOptions.activeLabelColor,
            barBackgroundColor: tabOptions.barBackgroundColor
          }

          return <Tab key={index} {...tabProps} />
        })}
      </BottomNavigation>
    )
  }
}
<commit_msg>Add support for react-navigation's `tabBarOnPress`<commit_after>/**
 * Pluggable Version for [react-navigation](https://reactnavigation.org/).
 * The BottomNavigation gets its options from a separate namespace in
 * `tabBarOptions` inside TabNavigatorConfig, namely `bottomNavigationOptions`.
 * @flow
 */

import React, { PureComponent } from 'react'
import BottomNavigation, { Tab } from '../'

type NCProps = {
  // I could use react-navigation's type definitions, but I don't want to
  // include it as a dependency or risk throwing an error because the package
  // is not found. So: `any`
  navigationState: any,
  jumpToIndex: (index: number) => void,
  getLabel: (scene: any) => ?(React.Element<*> | string),
  getLabelText?: (scene: any) => ?(React.Element<*> | string),
  renderIcon: (scene: any) => React.Element<*>,
  style?: any,
  bottomNavigationOptions: any,
  activeTintColor?: string,
  inactiveTintColor?: string
}

export default
class NavigationComponent extends PureComponent<void, NCProps, void> {
  render() {
    // react-navigation passed props
    const {
      activeTintColor,
      inactiveTintColor,
      navigationState,
      bottomNavigationOptions,
      getLabel: navigationGetLabel,
      getLabelText: navigationGetLabelOld,
      getOnPress: navigationGetOnPress,
      renderIcon,
      jumpToIndex,
      style
    } = this.props

    const bnOptions = bottomNavigationOptions || {}

    // Support for earlier version of react-navigation (up to 1.0.0-beta5)
    const getLabel = navigationGetLabel || navigationGetLabelOld

    // BottomNavigation's style
    const { style: bnStyle } = bnOptions

    // Builded props for BottomNavigation
    const bnProps = {
      labelColor: bnOptions.labelColor,
      innerStyle: bnOptions.innerStyle,
      activeLabelColor: bnOptions.activeLabelColor,
      rippleColor: bnOptions.rippleColor,
      backgroundColor: bnOptions.backgroundColor,
      shifting: bnOptions.shifting
    }

    return (
      <BottomNavigation
        activeTab={navigationState.index}
        // Style has default `height: 56`, so you can in theory skip styling
        // completely. After that, it uses the styles inside the
        // bottomNavigationOptions namespace. As a last resort, the styles from
        // `tabBarOptions` will be added.
        style={[ { height: 56 }, bnStyle || style ]}
        onTabChange={(index) => jumpToIndex(index)}
        {...bnProps}
      >
        {navigationState.routes.map((route, index) => {
          const focused = index === navigationState.index

          // scene object for `getLabel` and `renderIcon`
          const scene = {
            route,
            index,
            focused,
            tintColor: focused ? activeTintColor : inactiveTintColor
          }
          const onPress = navigationGetOnPress(scene)
          const label = getLabel(scene)
          const icon = renderIcon(scene)

          // Prepare props for the tabs
          const tabs = bnOptions.tabs || {}
          const tabOptions = tabs[route.key] || {}
          const tabProps = {
            icon: tabOptions.icon || icon,
            activeIcon: tabOptions.activeIcon,
            label: tabOptions.label || label,
            labelColor: tabOptions.labelColor,
            activeLabelColor: tabOptions.activeLabelColor,
            barBackgroundColor: tabOptions.barBackgroundColor
          }

          return <Tab
            key={index}
            onPress={onPress ? () => { onPress(scene, jumpToIndex) } : null}
            {...tabProps}
          />
        })}
      </BottomNavigation>
    )
  }
}
<|endoftext|>


<commit_before>var db = require('./db/api');
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
require('dotenv').config();
passport.serializeUser(function(user, done){
  done(null, user);
});
passport.deserializeUser(function(obj, done){
  done(null, obj);
});
passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: 'http://localhost:3000/auth/google/callback'
},
function(accessToken, refreshToken, profile, done){
   db.findUserById(profile.id).then(function(id){
     if(id){
       return done(null, profile);
     }else{
       db.createUser(profile).then(function(id){
         return done(null, profile);
       });
     }
   });
 }));
 module.exports = {
   passport: passport
 };
<commit_msg>fix callback url<commit_after>var db = require('./db/api');
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
require('dotenv').config();
passport.serializeUser(function(user, done){
  done(null, user);
});
passport.deserializeUser(function(obj, done){
  done(null, obj);
});
passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,

  callbackURL: 'http://the-hive-g25.herokuapp.com/auth/google/callback'
  },

function(accessToken, refreshToken, profile, done){
   db.findUserById(profile.id).then(function(id){
     if(id){
       return done(null, profile);
     }else{
       db.createUser(profile).then(function(id){
         return done(null, profile);
       });
     }
   });
 }));
 module.exports = {
   passport: passport
 };
<|endoftext|>


<commit_before>/**
 * @class  Auth
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Authentication module interfaced with an API server
 *
 * This module works with global events.
 *
 * Listen for
 *
 * * `auth.success`: Login success
 * * `auth.fail': Login failed
 * * `auth.logut': User want to logout
 * * `auth.login`: The app has no stored credentials
 *
 * then just call `T('auth').handle()` in the `alloy.js` file and wait for one of 4 events.
 *
 */

var config = _.extend({}, Alloy.CFG.T.auth);
exports.config = config;

var Me = null;
var authInfo = null;
var Net = require('T/net');

function getCurrentDriver(){
	if (!Ti.App.Properties.hasProperty('auth.driver')) return false;
	return Ti.App.Properties.getString('auth.driver');
}

/**
 * Require the selected driver
 *
 * @param  {String} driver The driver
 * @return {Object}
 */
function loadDriver(driver) {
	if (!driver) return false;
	return require('T/auth.'+driver);
}
exports.loadDriver = loadDriver;

/**
 * Require current-used driver, false if no driver is stored
 *
 * @return {Object}
 */
function loadCurrentDriver() {
	return loadDriver(getCurrentDriver());
}
exports.loadCurrentDriver = loadCurrentDriver;

/**
 * Trigger the handleLogin on current-used driver
 *
 */
function handleLogin() {
	if (!getCurrentDriver()) {
		Ti.API.warn("Auth: no driver stored to handle authentication");
		return false;
	}

	try {
		loadCurrentDriver().handleLogin();
	} catch (e) {
		Ti.App.fireEvent('app.login');
	}
}
exports.handleLogin = handleLogin;

/**
 * Try to login in offline mode, filling the user information from offline data
 *
 * Fire an **app.login** event in case of no offline data is present
 *
 * Otherwise, an **auth.success** event is fired
 *
 * @param  {Function} success Success callback
 */
function handleOfflineLogin(success){
	if (!Ti.App.Properties.hasProperty('auth.me')) {
		Ti.App.fireEvent('app.login');
		return;
	}

	Me = Alloy.createModel('user', Ti.App.Properties.getObject('auth.me'));
	Ti.App.fireEvent('auth.success');
	if (success) success();
}
exports.handleOfflineLogin = handleOfflineLogin;

/**
 * Try to login, switching automatically to offline mode if an internet connection is not detected
 *
 * If fail, it fails silently
 *
 */
function handle() {
	if (Net.isOnline()) {
		if (Net.usePingServer()) {
			Net.connectToServer(handleLogin);
		} else {
			handleLogin();
		}
	} else {
		handleOfflineLogin();
	}
}
exports.handle = handle;

/**
 * Login in the API server
 *
 * Fire an *auth.fail* in case of fail
 *
 * Fire an *auth.success* if success
 *
 * @param  {Object}   data   Data sent to the server
 * @param  {String}   driver Driver used to login
 * @param  {Function} cb     Success callback
 */
function login(data, driver, cb) {
	data.method = driver;

	Net.send({
		url: '/auth',
		method: 'POST',
		data: data,
		silent: data.silent || false,
		success: function(response){
			authInfo = response;

			if (!authInfo.id) {
				Ti.API.error("Auth: authInfo.id is null");
				Ti.App.fireEvent('auth.fail', {
					message: L('auth_error'),
					silent: data.silent
				});
				return;
			}

			Me = Alloy.createModel('user', {
				id: authInfo.id
			});

			Me.fetch({
				networkArgs: {
					refresh: true,
					cache: false,
					silent: data.silent
				},

				success: function(){
					Ti.App.Properties.setObject('auth.me', Me.toJSON());
					Ti.App.Properties.setString('auth.driver', driver);
					Ti.App.fireEvent('auth.success', authInfo);

					if (cb) cb();
				},

				error: function(e){
					Ti.App.fireEvent('auth.fail', {
						message: e.message,
						silent: data.silent
					});
				}
			});
		},
		error: function(e){
			Ti.App.fireEvent('auth.fail', {
				message: e.message,
				silent: data.silent
			});
		}
	});
}
exports.login = login;

/**
 * Get the object returned from the API server when authenticated
 *
 * @return {Object}
 */
function getAuthInfo() {
	return authInfo;
}
exports.getAuthInfo = getAuthInfo;

/**
 * Get current User model
 * @return {Object}
 */
function getCurrentUser(){
	return Me;
}
exports.getCurrentUser = getCurrentUser;

/**
 * @method  me
 * @inheritDoc #getCurrentUser
 * Alias for {@link #getCurrentUser}
 */
exports.me = getCurrentUser;

/**
 * @method user
 * @inheritDoc #getCurrentUser
 * Alias for {@link #getCurrentUser}
 */
exports.user = getCurrentUser;

/**
 * Logout calling "current-driver" logout, logout from the API server and empty all auth infos
 *
 * Fire an *auth.logout* in any case when completed
 *
 * @param  {Function} cb Success callback
 */
function logout(cb) {
	var id = Me ? Me.id: null;

	if (getCurrentDriver()) {
		try {
			loadCurrentDriver().logout();
		} catch (e) {}
	}

	Me = null;
	authInfo = null;

	Ti.App.Properties.removeProperty('auth.me');
	Ti.App.Properties.removeProperty('auth.driver');
	Net.resetCache();

	if (Net.isOnline()) {

		Net.send({
			url: '/logout',
			method: 'POST',
			silent: true,
			success: function(){},
			error: function(){},
			complete: function(){
				Net.resetCookies();
				Ti.App.fireEvent('auth.logout', { id: id });

				if (cb) cb();
			},
		});

	} else {
		Net.resetCookies();
		Ti.App.fireEvent('auth.logout', { id: id });
	}

}
exports.logout = logout;

<commit_msg>Updated docs<commit_after>/**
 * @class  Auth
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Authentication module interfaced with an API server
 *
 * This module works with global events.
 *
 * Listen for
 *
 * * `auth.success`: Login success
 * * `auth.fail`: Login failed
 * * `auth.logut`: User want to logout
 * * `auth.login`: The app has no stored credentials
 *
 * then just call `T('auth').handle()` in the `alloy.js` file and wait for one of 4 events.
 *
 */

var config = _.extend({}, Alloy.CFG.T.auth);
exports.config = config;

var Me = null;
var authInfo = null;
var Net = require('T/net');

function getCurrentDriver(){
	if (!Ti.App.Properties.hasProperty('auth.driver')) return false;
	return Ti.App.Properties.getString('auth.driver');
}

/**
 * Require the selected driver
 *
 * @param  {String} driver The driver
 * @return {Object}
 */
function loadDriver(driver) {
	if (!driver) return false;
	return require('T/auth.'+driver);
}
exports.loadDriver = loadDriver;

/**
 * Require current-used driver, false if no driver is stored
 *
 * @return {Object}
 */
function loadCurrentDriver() {
	return loadDriver(getCurrentDriver());
}
exports.loadCurrentDriver = loadCurrentDriver;

/**
 * Trigger the handleLogin on current-used driver
 *
 */
function handleLogin() {
	if (!getCurrentDriver()) {
		Ti.API.warn("Auth: no driver stored to handle authentication");
		return false;
	}

	try {
		loadCurrentDriver().handleLogin();
	} catch (e) {
		Ti.App.fireEvent('app.login');
	}
}
exports.handleLogin = handleLogin;

/**
 * Try to login in offline mode, filling the user information from offline data
 *
 * Fire an **app.login** event in case of no offline data is present
 *
 * Otherwise, an **auth.success** event is fired
 *
 * @param  {Function} success Success callback
 */
function handleOfflineLogin(success){
	if (!Ti.App.Properties.hasProperty('auth.me')) {
		Ti.App.fireEvent('app.login');
		return;
	}

	Me = Alloy.createModel('user', Ti.App.Properties.getObject('auth.me'));
	Ti.App.fireEvent('auth.success');
	if (success) success();
}
exports.handleOfflineLogin = handleOfflineLogin;

/**
 * Try to login, switching automatically to offline mode if an internet connection is not detected
 *
 * If fail, it fails silently
 *
 */
function handle() {
	if (Net.isOnline()) {
		if (Net.usePingServer()) {
			Net.connectToServer(handleLogin);
		} else {
			handleLogin();
		}
	} else {
		handleOfflineLogin();
	}
}
exports.handle = handle;

/**
 * Login in the API server
 *
 * Fire an *auth.fail* in case of fail
 *
 * Fire an *auth.success* if success
 *
 * @param  {Object}   data   Data sent to the server
 * @param  {String}   driver Driver used to login
 * @param  {Function} cb     Success callback
 */
function login(data, driver, cb) {
	data.method = driver;

	Net.send({
		url: '/auth',
		method: 'POST',
		data: data,
		silent: data.silent || false,
		success: function(response){
			authInfo = response;

			if (!authInfo.id) {
				Ti.API.error("Auth: authInfo.id is null");
				Ti.App.fireEvent('auth.fail', {
					message: L('auth_error'),
					silent: data.silent
				});
				return;
			}

			Me = Alloy.createModel('user', {
				id: authInfo.id
			});

			Me.fetch({
				networkArgs: {
					refresh: true,
					cache: false,
					silent: data.silent
				},

				success: function(){
					Ti.App.Properties.setObject('auth.me', Me.toJSON());
					Ti.App.Properties.setString('auth.driver', driver);
					Ti.App.fireEvent('auth.success', authInfo);

					if (cb) cb();
				},

				error: function(e){
					Ti.App.fireEvent('auth.fail', {
						message: e.message,
						silent: data.silent
					});
				}
			});
		},
		error: function(e){
			Ti.App.fireEvent('auth.fail', {
				message: e.message,
				silent: data.silent
			});
		}
	});
}
exports.login = login;

/**
 * Get the object returned from the API server when authenticated
 *
 * @return {Object}
 */
function getAuthInfo() {
	return authInfo;
}
exports.getAuthInfo = getAuthInfo;

/**
 * Get current User model
 * @return {Object}
 */
function getCurrentUser(){
	return Me;
}
exports.getCurrentUser = getCurrentUser;

/**
 * @method  me
 * @inheritDoc #getCurrentUser
 * Alias for {@link #getCurrentUser}
 */
exports.me = getCurrentUser;

/**
 * @method user
 * @inheritDoc #getCurrentUser
 * Alias for {@link #getCurrentUser}
 */
exports.user = getCurrentUser;

/**
 * Logout calling "current-driver" logout, logout from the API server and empty all auth infos
 *
 * Fire an *auth.logout* in any case when completed
 *
 * @param  {Function} cb Success callback
 */
function logout(cb) {
	var id = Me ? Me.id: null;

	if (getCurrentDriver()) {
		try {
			loadCurrentDriver().logout();
		} catch (e) {}
	}

	Me = null;
	authInfo = null;

	Ti.App.Properties.removeProperty('auth.me');
	Ti.App.Properties.removeProperty('auth.driver');
	Net.resetCache();

	if (Net.isOnline()) {

		Net.send({
			url: '/logout',
			method: 'POST',
			silent: true,
			success: function(){},
			error: function(){},
			complete: function(){
				Net.resetCookies();
				Ti.App.fireEvent('auth.logout', { id: id });

				if (cb) cb();
			},
		});

	} else {
		Net.resetCookies();
		Ti.App.fireEvent('auth.logout', { id: id });
	}

}
exports.logout = logout;

<|endoftext|>


<commit_before>const git = require('simple-git')
const fb = require('./fb')

var ref = fb.child("servers")

ref.child(process.env.DEVICE).on('value', autoPull)

// process.on('SIGINT', function() {
//   process.exit()
// });

var running = false

setInterval(function() {
  if (running == true) return false
  running = true
  autoPull()
}, 30000)

function autoPull (data) {
  // console.log(data.val())
  git()
    .exec(function() {
      console.log('Starting pull ...')
    })
    .pull('origin', 'master', {'--no-rebase': null})
    .pull('origin', 'master', function(err, update) {
      if(update && update.summary.changes) {
        // console.log(update)
        console.log('processing and restarting app ...')
      }
    })
    .exec(function() {
      console.log('pull done.')
      running = false
    })
}
<commit_msg>update project<commit_after>const git = require('simple-git')
const fb = require('./fb')

var ref = fb.child("servers")

ref.child(process.env.DEVICE).on('value', autoPull)

// process.on('SIGINT', function() {
//   process.exit()
// });

var running = false

setInterval(function() {
  if (running == true) return false
  running = true
  autoPull()
}, 30000)

function autoPull (data) {
  // console.log(data.val())
  git()
    .exec(function() {
      console.log('Starting pull ...')
    })
    .pull('origin', 'master', {'--no-rebase': null})
    // .pull('origin', 'master', function(err, update) {
    //   if(update && update.summary.changes) {
    //     // console.log(update)
    //     console.log('processing and restarting app ...')
    //   }
    // })
    .exec(function() {
      console.log('pull done.')
      running = false
    })
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var props = require('props');
var dive = require('dive');
var ejs = require('ejs');
var async = require('async');
var clone = require('clone');
var append = require('append');

// Main function
var bake = function(conf, hooks, cb) {

  // File counter
  var todo = 0;

  if (typeof conf != 'object')
    return cb(new Error('parameter conf must be a valid configuration object'));

  // Set values for inputDir, outputDir and tplDir
  var root = conf.root || process.cwd();
  var inputDir = conf.directories.input || 'pub';
  var outputDir = conf.directories.output || 'pub';
  var tplDir = conf.directories.templates || 'tpl';

  inputDir = path.resolve(root, inputDir);
  outputDir = path.resolve(root, outputDir);
  tplDir = path.resolve(root, tplDir);

  // Set values for fileExt
  var fileExt = conf.fileExtensions || { txt: 'html' };
  var fileExtPattern
      = new RegExp('\\.(' + Object.keys(fileExt).join('|') + ')$', 'i');

  var ignore = conf.ignore || [];

  // Status log
  console.log('Beginning to bake ' + inputDir + '.');

  // Dive into the public directory
  dive(inputDir, function(err, master) {
    // Throw errors
    if (err)
      return cb(err);

    // Matching variable
    var match;

    // Match the master-file's name against enabled file extensions
    if (ignore.indexOf(master) == -1
        && (match = master.match(fileExtPattern))) {

      // Get the file extension of the master file
      var masterExt = match[1];

      // Increase file counter
      ++todo;

      // Read the master-file's contents
      fs.readFile(master, 'utf8', function(err, data) {
        // Throw errors
        if (err)
          return cb(err);

        // Get the properties
        // prop is the file specific property object
        var prop = props(data);

        // Amend prop by properties in conf.properties if defined
        if (conf.properties)
          prop = append(clone(conf.properties), prop);

        // Assert that prop.template is set
        if (typeof prop.template == 'undefined')
          prop.template = 'default.tpl';

        // __propBefore hook
        if (hooks.__propBefore)
          hooks.__propBefore(master, prop, propBeforeCB);
        else
          propBeforeCB(null, prop);

        function propBeforeCB(err, prop) {
          if (err)
            return cb(err);

          // tasks for async
          var tasks = {};

          // Various property hooks
          for (var key in prop) {(function (prop, key) {
            if (hooks[key])
              tasks[key] = function (callback) {
                return hooks[key](master, prop, callback);
              };
            else
              tasks[key] = function (callback) {
                return callback(null, prop[key]);
              };
          })(prop, key);}

          // run tasks in parallel
          async.parallel(tasks, function (err, prop) {
            if (err)
              return cb(err);

            // __propAfter hook
            if (hooks.__propAfter)
              hooks.__propAfter(master, prop, propAfterCB);
            else
              propAfterCB(null, prop);

            function propAfterCB(err, prop) {
              if (err)
                return cb(err);

              // Read the template file
              fs.readFile(path.resolve(tplDir, prop.template), 'utf8',
                  function(err, result) {
                // Throw errors
                if (err)
                  return cb(err);

                // (Pre-)Insert the content (so ejs-tags in
                // prop.__content are parsed, too.
                result = result.replace(/<%=\s+__content\s+%>/g,
                    prop.__content);

                // Result's filename
                var resName = master.replace(fileExtPattern,
                    '.' + fileExt[masterExt]);

                // New file's path
                if (typeof prop._id == 'undefined') {
                  prop._id = resName.replace(inputDir, '');
                  prop._id = prop._id.replace(new RegExp('\\\\', 'g'), '/');
                }

                // Render ejs-template
                result = ejs.render(result, { locals: prop });

                // Remove first slash
                if (/^\//.test(prop._id))
                  prop._id = prop._id.substring(1);

                // absolute path
                resName = path.resolve(outputDir, prop._id);

                // Write contents
                fs.writeFile(resName, result, function(err) {
                  // Throw errors
                  if (err)
                    return cb(err);

                  // __writeAfter hook
                  if (hooks.__writeAfter)
                    hooks.__writeAfter(master, prop, writeAfterCB);
                  else
                    writeAfterCB(null);

                  function writeAfterCB(err) {
                    if (err)
                      return cb(err);

                    // Log status on success
                    console.log('  * ' + resName + ' written.');

                    // When file counter is zero
                    if (!--todo) {
                      // __complete hook
                      if (hooks.__complete)
                        hooks.__complete(master, prop, cb);
                      else
                        return cb(null);
                    }
                  }
                });
              });
            }
          });
        }
      });
    }
  });
};

module.exports = bake;
<commit_msg>Fix ignoration<commit_after>var fs = require('fs');
var path = require('path');
var props = require('props');
var dive = require('dive');
var ejs = require('ejs');
var async = require('async');
var clone = require('clone');
var append = require('append');

// Main function
var bake = function(conf, hooks, cb) {

  // File counter
  var todo = 0;

  if (typeof conf != 'object')
    return cb(new Error('parameter conf must be a valid configuration object'));

  // Set values for inputDir, outputDir and tplDir
  var root = conf.root || process.cwd();
  var inputDir = conf.directories.input || 'pub';
  var outputDir = conf.directories.output || 'pub';
  var tplDir = conf.directories.templates || 'tpl';

  inputDir = path.resolve(root, inputDir);
  outputDir = path.resolve(root, outputDir);
  tplDir = path.resolve(root, tplDir);

  // Set values for fileExt
  var fileExt = conf.fileExtensions || { txt: 'html' };
  var fileExtPattern
      = new RegExp('\\.(' + Object.keys(fileExt).join('|') + ')$', 'i');

  var ignore = conf.ignore || [];

  // Status log
  console.log('Beginning to bake ' + inputDir + '.');

  // Dive into the public directory
  dive(inputDir, function(err, master) {
    // Throw errors
    if (err)
      return cb(err);

    // Matching variable
    var match;
    var pathFromRoot = master.replace(inputDir, '').substr(1);

    // Match the master-file's name against enabled file extensions
    if ((match = master.match(fileExtPattern))
        && ignore.indexOf(pathFromRoot) == -1) {

      // Get the file extension of the master file
      var masterExt = match[1];

      // Increase file counter
      ++todo;

      // Read the master-file's contents
      fs.readFile(master, 'utf8', function(err, data) {
        // Throw errors
        if (err)
          return cb(err);

        // Get the properties
        // prop is the file specific property object
        var prop = props(data);

        // Amend prop by properties in conf.properties if defined
        if (conf.properties)
          prop = append(clone(conf.properties), prop);

        // Assert that prop.template is set
        if (typeof prop.template == 'undefined')
          prop.template = 'default.tpl';

        // __propBefore hook
        if (hooks.__propBefore)
          hooks.__propBefore(master, prop, propBeforeCB);
        else
          propBeforeCB(null, prop);

        function propBeforeCB(err, prop) {
          if (err)
            return cb(err);

          // tasks for async
          var tasks = {};

          // Various property hooks
          for (var key in prop) {(function (prop, key) {
            if (hooks[key])
              tasks[key] = function (callback) {
                return hooks[key](master, prop, callback);
              };
            else
              tasks[key] = function (callback) {
                return callback(null, prop[key]);
              };
          })(prop, key);}

          // run tasks in parallel
          async.parallel(tasks, function (err, prop) {
            if (err)
              return cb(err);

            // __propAfter hook
            if (hooks.__propAfter)
              hooks.__propAfter(master, prop, propAfterCB);
            else
              propAfterCB(null, prop);

            function propAfterCB(err, prop) {
              if (err)
                return cb(err);

              // Read the template file
              fs.readFile(path.resolve(tplDir, prop.template), 'utf8',
                  function(err, result) {
                // Throw errors
                if (err)
                  return cb(err);

                // (Pre-)Insert the content (so ejs-tags in
                // prop.__content are parsed, too.
                result = result.replace(/<%=\s+__content\s+%>/g,
                    prop.__content);

                // Result's filename
                var resName = master.replace(fileExtPattern,
                    '.' + fileExt[masterExt]);

                // New file's path
                if (typeof prop._id == 'undefined') {
                  prop._id = resName.replace(inputDir, '');
                  prop._id = prop._id.replace(new RegExp('\\\\', 'g'), '/');
                }

                // Render ejs-template
                result = ejs.render(result, { locals: prop });

                // Remove first slash
                if (/^\//.test(prop._id))
                  prop._id = prop._id.substring(1);

                // absolute path
                resName = path.resolve(outputDir, prop._id);

                // Write contents
                fs.writeFile(resName, result, function(err) {
                  // Throw errors
                  if (err)
                    return cb(err);

                  // __writeAfter hook
                  if (hooks.__writeAfter)
                    hooks.__writeAfter(master, prop, writeAfterCB);
                  else
                    writeAfterCB(null);

                  function writeAfterCB(err) {
                    if (err)
                      return cb(err);

                    // Log status on success
                    console.log('  * ' + resName + ' written.');

                    // When file counter is zero
                    if (!--todo) {
                      // __complete hook
                      if (hooks.__complete)
                        hooks.__complete(master, prop, cb);
                      else
                        return cb(null);
                    }
                  }
                });
              });
            }
          });
        }
      });
    }
  });
};

module.exports = bake;
<|endoftext|>


<commit_before>const webid = require('webid/tls')
const debug = require('../../debug').authentication

function initialize (app, argv) {
  app.use('/', handler)
}

function handler (req, res, next) {
  // User already logged in? skip
  if (req.session.userId) {
    debug('User: ' + req.session.userId)
    res.set('User', req.session.userId)
    return next()
  }

  // No certificate? skip
  const certificate = getCertificateViaTLS(req)
  console.log(req.method)
  console.log(req.headers)
  console.log(req.body)
  console.log('CERTIFICATE')
  console.log(certificate)
  if (!certificate) {
    setEmptySession(req)
    return next()
  }

  // Verify webid
  webid.verify(certificate, function (err, result) {
    if (err) {
      debug('Error processing certificate: ' + err.message)
      setEmptySession(req)
      return next()
    }
    req.session.userId = result
    debug('Identified user: ' + req.session.userId)
    res.set('User', req.session.userId)
    return next()
  })
}

// Tries to obtain a client certificate retrieved through the TLS handshake
function getCertificateViaTLS (req) {
  const certificate = req.connection.getPeerCertificate &&
                      req.connection.getPeerCertificate()
  console.log('IN CERT')
  console.log(certificate)
  if (certificate && Object.keys(certificate).length > 0) {
    return certificate
  }
  debug('No peer certificate received during TLS handshake.')
}

function setEmptySession (req) {
  req.session.userId = ''
}

/**
 * Sets the `WWW-Authenticate` response header for 401 error responses.
 * Used by error-pages handler.
 *
 * @param req {IncomingRequest}
 * @param res {ServerResponse}
 */
function setAuthenticateHeader (req, res) {
  let locals = req.app.locals

  res.set('WWW-Authenticate', `WebID-TLS realm="${locals.host.serverUri}"`)
}

module.exports = {
  initialize,
  handler,
  setAuthenticateHeader,
  setEmptySession
}
<commit_msg>Code cleanup<commit_after>const webid = require('webid/tls')
const debug = require('../../debug').authentication

function initialize (app, argv) {
  app.use('/', handler)
}

function handler (req, res, next) {
  // User already logged in? skip
  if (req.session.userId) {
    debug('User: ' + req.session.userId)
    res.set('User', req.session.userId)
    return next()
  }

  // No certificate? skip
  const certificate = getCertificateViaTLS(req)
  if (!certificate) {
    setEmptySession(req)
    return next()
  }

  // Verify webid
  webid.verify(certificate, function (err, result) {
    if (err) {
      debug('Error processing certificate: ' + err.message)
      setEmptySession(req)
      return next()
    }
    req.session.userId = result
    debug('Identified user: ' + req.session.userId)
    res.set('User', req.session.userId)
    return next()
  })
}

// Tries to obtain a client certificate retrieved through the TLS handshake
function getCertificateViaTLS (req) {
  const certificate = req.connection.getPeerCertificate &&
                      req.connection.getPeerCertificate()
  if (certificate && Object.keys(certificate).length > 0) {
    return certificate
  }
  debug('No peer certificate received during TLS handshake.')
}

function setEmptySession (req) {
  req.session.userId = ''
}

/**
 * Sets the `WWW-Authenticate` response header for 401 error responses.
 * Used by error-pages handler.
 *
 * @param req {IncomingRequest}
 * @param res {ServerResponse}
 */
function setAuthenticateHeader (req, res) {
  let locals = req.app.locals

  res.set('WWW-Authenticate', `WebID-TLS realm="${locals.host.serverUri}"`)
}

module.exports = {
  initialize,
  handler,
  setAuthenticateHeader,
  setEmptySession
}
<|endoftext|>


<commit_before>var Hapi = require('hapi');
var Schema = require('protobuf').Schema;
var fs = require('fs');
var request = require('request');
require('buffertools').extend();

var Db = require('./db');
var Config = require('./config');
var Util = require('./utility');

var internals = {
  bitcoinSchema: new Schema(fs.readFileSync('lib/api/protos/bitcoin.desc')),
  bitcoinServerSchema: new Schema(fs.readFileSync('lib/api/protos/bitcoinserver.desc')),
  paymentRequestSchema: new Schema(fs.readFileSync('lib/api/protos/paymentrequest.desc'))
};

// private function to serialize payment details
// param: request object
// param: id
internals.serializePaymentDetails = function (request, id) {
  var output = {
    amount: request.query.amount,
    script: {} // TODO: usually one of the standard Script forms
  };
  var paymentDetail = {
    network: "main",
    outputs: [output],
    time: Date.now() / 1000,
    memo: request.query.memo,
    payment_url: Util.paymentURIFromId(id)
  };

  var paymentDetailsProto = internals.paymentRequestSchema['payments.PaymentDetails'];
  var paymentDetailsSerialized = paymentDetailsProto.serialize(paymentDetail);
  return paymentDetailsSerialized;
};

// private function to deserialize payment details
// param: payment detail buffer
internals.deserializePaymentDetails = function (pdBuffer) {
  var paymentDetailsProto = internals.paymentRequestSchema['payments.PaymentDetails'];
  var paymentDetailsDeserialized = paymentDetailsProto.parse(pdBuffer);
  return paymentDetailsDeserialized;
};

// private function to deserialize payment request
// Will automatically print deserialized payment details (comment out in production)
// param: payment request buffer
internals.deserializePaymentRequest = function (prBuffer) {
  if (Buffer.isBuffer(prBuffer)) {
    var paymentRequestProto = internals.paymentRequestSchema['payments.PaymentRequest'];
    var paymentRequestDeserialized = paymentRequestProto.parse(prBuffer);
    console.log('Deserialized PayReq:', JSON.stringify(paymentRequestDeserialized));
    var paymentDetailsDeserialized = internals.deserializePaymentDetails(paymentRequestDeserialized.serializedPaymentDetails);
    console.log('Deserialized PayDet:', JSON.stringify(paymentDetailsDeserialized));
    return paymentRequestDeserialized;
  } else if (typeof prBuffer == 'string' || prBuffer instanceof String) {
    return internals.deserializePaymentRequest(new Buffer(prBuffer, 'ascii'));
  } else {
    console.log("[deserializePaymentRequest]: Param must be buffer/string");
  }
};

// Private function to post the protobuf to notary service
internals.postToPRS = function (protoBuf) {
  if (Buffer.isBuffer(protoBuf)) {

    // An object of options to indicate where to post to
    var post_options = {
      url: Config.PRS.uri,
      method: 'POST',
      headers: {
        'Content-Type': 'application/octet-stream',
        'Content-Length': protoBuf.length,
        'Accept': 'application/octet-stream'
      },
      body: protoBuf
    };
    var callback = function (error, response, body) {
      if (!error && response.statusCode == 200) {
        internals.deserializePaymentRequest(body);
      } else {
        console.log('[postToPRS]: status: ' + response.statusCode);
        console.log('[postToPRS]: error: ' + error);
        console.log(JSON.stringify(response));
      }
    }
    // Set up the request
    request(post_options, callback);
  } else {
    console.log("[postToPRS]: Param must be buffer");
  }
};

/**
 * Handler for /get/{id}
 * @type {Object}
 */
exports.get = {
  handler: function (request) {
    console.log('[GET]:' + request.params.id);
    var id = Util.idToDBIndex(request.params.id);
    request.reply("this is db index: " + id);
  }
};

/**
 * Handler for /pay/{id}
 * @type {Object}
 */
exports.pay = {
  handler: function (request) {
    console.log('[PAY]:' + request.params.id);
    var id = Util.idToDBIndex(request.params.id);
    request.reply("this is db index: " + id);
  }
};

/**
 * Handler for /create
 * @type {Object}
 */
exports.create = {
  handler: function (request) {
    console.log('[CREATE]:' +
      '\nAddress: ' + request.query.address +
      '\nAmount:' + request.query.amount +
      '\nMemo:' + request.query.memo +
      '\nAck Memo:' + request.query.ackmemo);

    //generate hash from request queries
    var hash = Util.hashForCreateReq(request);

    var dbObj = {
      address: request.query.address,
      amount: request.query.amount,
      memo: request.query.memo,
      ackmemo: request.query.ackmemo,
      hash: hash
    }
    //insert one row into the db
    Db.insert(dbObj);

    //send create db request, get the next db index, convert to id
    var id = Util.dbIndexToId(Db.nextIndex());

    //Serialize payment details
    var serializedPaymentDetails = internals.serializePaymentDetails(request, id);

    //post to signing server, get response
    var resp = internals.postToPRS(serializedPaymentDetails);

    //deserialize the response and cache it in db
    // var deserializedPaymentRequest = internals.deserializePaymentRequest(resp);

    var hashstr = "hash: " + hash;
    request.reply(hashstr);
  },
  validate: {
    query: {
      address: Hapi.types.String().required(),
      amount: Hapi.types.Number().min(0).required(),
      memo: Hapi.types.String().required(),
      ackmemo: Hapi.types.String().required()
    }
  }
};<commit_msg>decide to use async.waterfall for control flow. seems to make sense<commit_after>var Hapi = require('hapi');
var Schema = require('protobuf').Schema;
var FS = require('fs');
var Request = require('request');
var Async = require('async');

var Db = require('./db');
var Config = require('./config');
var Util = require('./utility');

var internals = {
  bitcoinSchema: new Schema(FS.readFileSync('lib/api/protos/bitcoin.desc')),
  bitcoinServerSchema: new Schema(FS.readFileSync('lib/api/protos/bitcoinserver.desc')),
  paymentRequestSchema: new Schema(FS.readFileSync('lib/api/protos/paymentrequest.desc'))
};

// private function that grabs id from db insert return and serialize payment details
// to serialize payment details
// param: id - last id in db, from previous waterfall task (insert db)
// param: cb - callback for next waterfall task
internals.serializePaymentDetails = function (id, cb) {
  var output = {
    amount: internals.dbObj.amount || 0,
    script: {} // TODO: usually one of the standard Script forms
  };
  var paymentDetail = {
    network: "main",
    outputs: [output],
    time: Date.now() / 1000,
    memo: internals.dbObj.memo || '',
    payment_url: Util.paymentURIFromId(id)
  };

  var paymentDetailsProto = internals.paymentRequestSchema['payments.PaymentDetails'];
  var paymentDetailsSerialized = paymentDetailsProto.serialize(paymentDetail);
  //for next task in async.waterfall
  cb(null, paymentDetailsSerialized);
};

// private function to deserialize payment details
// param: payment detail buffer
internals.deserializePaymentDetails = function (pdBuffer) {
  var paymentDetailsProto = internals.paymentRequestSchema['payments.PaymentDetails '];
  var paymentDetailsDeserialized = paymentDetailsProto.parse(pdBuffer);
  return paymentDetailsDeserialized;
};

// private function to deserialize payment request
// Will automatically print deserialized payment details (comment out in production)
// param: payment request buffer
internals.deserializePaymentRequest = function (prBuffer) {
  if (Buffer.isBuffer(prBuffer)) {
    var paymentRequestProto = internals.paymentRequestSchema['payments.PaymentRequest '];
    var paymentRequestDeserialized = paymentRequestProto.parse(prBuffer);
    console.log('Deserialized PayReq: ', JSON.stringify(paymentRequestDeserialized));
    var paymentDetailsDeserialized = internals.deserializePaymentDetails(paymentRequestDeserialized.serializedPaymentDetails);
    console.log('Deserialized PayDet: ', JSON.stringify(paymentDetailsDeserialized));
    return paymentRequestDeserialized;
  } else if (typeof prBuffer == 'string ' || prBuffer instanceof String) {
    return internals.deserializePaymentRequest(new Buffer(prBuffer, 'ascii '));
  } else {
    console.log("[deserializePaymentRequest]: Param must be buffer/string");
  }
};

// Private function to add payment details ONLY to the db
// Wrapper functions
internals.insertPaymentDetailsToDB = function (callback) {
  Db.insert(internals.dbObj, callback);
};

// Private function to post the protobuf to notary service
internals.postToPRS = function (protoBuf, callback) {
  if (Buffer.isBuffer(protoBuf)) {

    // An object of options to indicate where to post to
    var post_options = {
      url: Config.PRS.uri,
      method: '    POST ',
      headers: {
        'Content - Type ': 'application / octet - stream',
        'Content - Length ': protoBuf.length,
        'Accept ': 'application / octet - stream'
      },
      body: protoBuf
    };
    var reqCallback = function (error, response, body) {
      if (!error && response.statusCode == 200) {
        // return internals.deserializePaymentRequest(body);
        return new Buffer(body, 'ascii');
      } else {
        console.log('[postToPRS]: status: ' + response.statusCode);
        console.log('[postToPRS]: error: ' + error);
        console.log(JSON.stringify(response));
      }
    }
    // Set up the request
    callback(null, Request(post_options, reqCallback));
  } else {
    console.log("[postToPRS]: Param must be buffer");
    callback("[postToPRS]: Param must be buffer");
  }
};

internals.updateDBWithPaymentRequestBuffer = function (prBuffer, callback) {
  var id = 0;
  callback(null, id)
};

internals.generateLink = function () {

}

/**
 * Handler for /get/{id}
 * @type {Object}
 */
exports.get = {
  handler: function (request) {
    console.log(' [GET]: ' + request.params.id);
    var id = Util.idToDBIndex(request.params.id);
    request.reply("this is db index: " + id);
  }
};

/**
 * Handler for /pay/{id}
 * @type {Object}
 */
exports.pay = {
  handler: function (request) {
    console.log(' [PAY]: ' + request.params.id);
    var id = Util.idToDBIndex(request.params.id);
    request.reply("this is db index: " + id);
  }
};

/**
 * Handler for /create
 * @type {Object}
 */
exports.create = {
  handler: function (request) {
    console.log(' [CREATE]: ' +
      '\nAddress: ' + request.query.address +
      '\nAmount: ' + request.query.amount +
      '\nMemo: ' + request.query.memo +
      '\nAck Memo: ' + request.query.ackmemo);

    //generate hash from request queries
    var hash = Util.hashForCreateReq(request);

    internals.dbObj = {
      address: request.query.address,
      amount: request.query.amount,
      memo: request.query.memo,
      ackmemo: request.query.ackmemo,
      hash: hash
    }
    Async.waterfall([
      internals.insertPaymentDetailsToDB,
      internals.serializePaymentDetails,
      internals.postToPRS,
      internals.updateDBWithPaymentRequestBuffer
    ], function (err, id) {
      // Last step, generate the link and outputs
      if (err) {
        console.log(err);
      } else if (id) {
        var hashstr = 'hash: ' + hash;
        request.reply(hashstr + '\n' + Util.paymentURIFromId(id));
      }
    });

  },
  validate: {
    query: {
      address: Hapi.types.String().required(),
      amount: Hapi.types.Number().min(0).required(),
      memo: Hapi.types.String().required(),
      ackmemo: Hapi.types.String().required()
    }
  }
};<|endoftext|>


<commit_before>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(<%= configFile %>)[env];
var db        = {};

if(config.use_env_variable){
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
}else{
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>Format model index template<commit_after>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(<%= configFile %>)[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>