<commit_before>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through');
var concat = require('concat-stream');
var parents = require('parents');

module.exports = function (mains, opts) {
    if (!opts) opts = {};
    var cache = opts.cache;
    var pkgCache = opts.packageCache || {};

    var paths = opts.paths || process.env.NODE_PATH;
    if (typeof paths === 'string') {
        paths = process.env.NODE_PATH.split(':');
    }
    if (!paths) paths = [];

    if (!Array.isArray(mains)) mains = [ mains ].filter(Boolean);
    var basedir = opts.basedir || process.cwd();

    var entries = mains.map(function (file) {
        if (file.path) return file.path;
        if (typeof file.pipe === 'function') {
            var n = Math.floor(Math.pow(16,8) * Math.random()).toString(16);
            return path.join(basedir, 'fake_' + n + '.js');
        }
        return path.resolve(file);
    });

    var visited = {};
    var pending = 0;

    var output = through();

    var transforms = [].concat(opts.transform).filter(Boolean);
    var resolve = opts.resolve || browserResolve;

    function pushResult (row) {
        output.queue(row);
        if (--pending === 0) output.queue(null);
    }

    var top = { id: '/', filename: '/', paths: paths };

    (function () {
        var pkgCount = mains.length;
        if (pkgCount === 0) next();

        mains.forEach(function (main) {
            if (typeof main === 'object') return done();
            var id = path.resolve(basedir, main);
            if (pkgCache[id]) return done();

            lookupPkg(main, function (err, pkg) {
                if (err) return output.emit('error', err);
                if (!pkg) pkg = {};
                if (!pkg.__dirname) pkg.__dirname = path.dirname(id);
                pkgCache[id] = pkg;
                done();
            });
        });
        function done () { if (--pkgCount === 0) next() }
    })();

    function next () {
        mains.forEach(function (main, ix) {
            if (typeof main === 'object') {
                walk({ stream: main, file: entries[ix] }, top);
            }
            else walk(main, top)
        });

        if (mains.length === 0) {
            output.pause();
            output.queue(null);
            process.nextTick(function () { output.resume() });
        }
    }

    return output;

    function walk (id, parent, cb) {
        pending ++;

        if (typeof id === 'object') {
            id.stream.pipe(concat({ encoding: 'string' }, function (src) {
                var pkgfile = path.join(basedir, 'package.json');
                fs.readFile(pkgfile, function (err, pkgsrc) {
                    var pkg = {};
                    if (!err) {
                        try { pkg = JSON.parse(pkgsrc) }
                        catch (e) {};
                    }
                    var trx = getTransform(pkg);
                    applyTransforms(id.file, trx, src, pkg);
                });
            }));
            if (cb) cb(false);
            return;
        }

        var c = cache && cache[parent.id];
        var resolver = c && typeof c === 'object'
        && !Buffer.isBuffer(c) && c.deps[id]
            ? function (xid, xparent, cb) {
                var file = cache[parent.id].deps[id];
                cb(null, file, pkgCache && pkgCache[file]);
            }
            : resolve;
        ;

        var pkgdir;
        parent.packageFilter = function (p, x) {
            pkgdir = x;
            if (opts.packageFilter) return opts.packageFilter(p, x);
            else return p;
        };
        if (opts.extensions) parent.extensions = opts.extensions;
        if (opts.modules) parent.modules = opts.modules;

        resolver(id, parent, function f (err, file, pkg) {
            if (err) return output.emit('error', err);
            if (!file) return output.emit('error', new Error([
                'module not found: "' + id + '" from file ',
                parent.filename
            ].join('')));

            if (pkg && pkgdir) pkg.__dirname = pkgdir;
            if (!pkg || !pkg.__dirname) {
                lookupPkg(file, function (err, p) {
                    if (err) return output.emit('error', err);
                    if (!p) p = {};
                    if (!p.__dirname) p.__dirname = path.dirname(file);
                    pkgCache[file] = p;
                    f(err, file, opts.packageFilter ? opts.packageFilter(p) : p);
                });
                return;
            }

            if (cb) cb(file);
            if (visited[file]) {
                if (--pending === 0) output.queue(null);
                return;
            }

            visited[file] = true;
            if (!pkg && pkgCache[file]) pkg = pkgCache[file];

            var trx = getTransform(pkg);

            if (cache && cache[file]) {
                parseDeps(file, cache[file], pkg);
            }
            else fs.readFile(file, 'utf8', function (err, src) {
                if (err) {
                    var e = new Error(
                        err.message
                        + ' while resolving '
                        + JSON.stringify(id)
                        + ' from file '
                        + parent.filename
                    );
                    Object.keys(err).forEach(function (key) {
                        e[key] = err[key];
                    });
                    if (err.code === 'ENOENT') {
                        e.type = 'not found';
                    }
                    e.parent = parent.filename;
                    e.filename = file;
                    return output.emit('error', e);
                }
                applyTransforms(file, trx, src, pkg);
            });
        });
    }

    function getTransform (pkg) {
        var trx = [];
        if (opts.transformKey) {
            var n = pkg;
            var keys = opts.transformKey;
            for (var i = 0; i < keys.length; i++) {
                if (n && typeof n === 'object') n = n[keys[i]];
                else break;
            }
            if (i === keys.length) {
                trx = [].concat(n).filter(Boolean);
            }
        }
        return trx.concat(opts.globalTransform || []);
    }

    function applyTransforms (file, trx, src, pkg) {
        var isTopLevel = mains.some(function (main) {
            var m = path.relative(path.dirname(main), file);
            return m.split('/').indexOf('node_modules') < 0;
        });
        var transf = (isTopLevel ? transforms : []).concat(trx);
        if (transf.length === 0) return done();

        (function ap (trs) {
            if (trs.length === 0) return done();
            var tr = trs[0], trOpts = {};
            if (Array.isArray(tr)) {
                trOpts = tr[1];
                tr = tr[0];
            }

            makeTransform(file, [ tr, trOpts ], function f (err, s) {
                if (err && pkg && pkg.__dirname) {
                    var t = path.resolve(pkg.__dirname, tr);
                    return makeTransform(file, [ t, trOpts ], function (e, s_) {
                        if (e) output.emit('error', e);
                        else f(null, s_);
                    });
                }
                if (err) return output.emit('error', err);

                s.on('error', output.emit.bind(output, 'error'));
                s.pipe(concat({ encoding: 'string' }, function (data) {
                    src = data;
                    ap(trs.slice(1));
                }));
                s.end(src);
            });
        })(transf);

        function done () {
            parseDeps(file, src, pkg);
        }
    }

    function parseDeps (file, src, pkg) {
        var deps;
        if (!Buffer.isBuffer(src) && typeof src === 'object') {
            deps = Object.keys(src.deps).sort();
            src = src.source;
        }
        else if (opts.noParse && opts.noParse.indexOf(file) >= 0) {
            deps = [];
        }
        else if (/\.json$/.test(file)) {
            deps = [];
        }
        else {
            try { var deps = detective(src) }
            catch (ex) {
                var message = ex && ex.message ? ex.message : ex;
                return output.emit('error', new Error(
                    'Parsing file ' + file + ': ' + message
                ));
            }
        }
        var p = deps.length;
        var current = { id: file, filename: file, paths: paths, package: pkg };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }

            walk(id, current, function (r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            var rec = {
                id: file,
                source: src,
                deps: resolved
            };
            if (entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            pushResult(rec);
        }
    }

    function makeTransform (file, tpair, cb) {
        var tr = tpair[0], trOpts = tpair[1];
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            output.emit('transform', t, file);
            return cb(null, t);
        }

        var params = { basedir: path.dirname(file) };
        nodeResolve(tr, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = process.cwd();
                nodeResolve(tr, params, function (e, r) {
                    nr(e, r, true)
                });
                return;
            }

            if (!res) return cb(new Error([
                'cannot find transform module ', tr,
                ' while transforming ', file
            ].join('')));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            output.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

function lookupPkg (file, cb) {
    var dirs = parents(path.dirname(file));
    (function next () {
        if (dirs.length === 0) return cb(null, undefined);
        var dir = dirs.shift();
        var pkgfile = path.join(dir, 'package.json');
        fs.readFile(pkgfile, function (err, src) {
            if (err) return next();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return cb(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;
            cb(null, pkg);
        });
    })();
}
<commit_msg>pass dir as second argument to packageFilter<commit_after>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through');
var concat = require('concat-stream');
var parents = require('parents');

module.exports = function (mains, opts) {
    if (!opts) opts = {};
    var cache = opts.cache;
    var pkgCache = opts.packageCache || {};

    var paths = opts.paths || process.env.NODE_PATH;
    if (typeof paths === 'string') {
        paths = process.env.NODE_PATH.split(':');
    }
    if (!paths) paths = [];

    if (!Array.isArray(mains)) mains = [ mains ].filter(Boolean);
    var basedir = opts.basedir || process.cwd();

    var entries = mains.map(function (file) {
        if (file.path) return file.path;
        if (typeof file.pipe === 'function') {
            var n = Math.floor(Math.pow(16,8) * Math.random()).toString(16);
            return path.join(basedir, 'fake_' + n + '.js');
        }
        return path.resolve(file);
    });

    var visited = {};
    var pending = 0;

    var output = through();

    var transforms = [].concat(opts.transform).filter(Boolean);
    var resolve = opts.resolve || browserResolve;

    function pushResult (row) {
        output.queue(row);
        if (--pending === 0) output.queue(null);
    }

    var top = { id: '/', filename: '/', paths: paths };

    (function () {
        var pkgCount = mains.length;
        if (pkgCount === 0) next();

        mains.forEach(function (main) {
            if (typeof main === 'object') return done();
            var id = path.resolve(basedir, main);
            if (pkgCache[id]) return done();

            lookupPkg(main, function (err, pkg) {
                if (err) return output.emit('error', err);
                if (!pkg) pkg = {};
                if (!pkg.__dirname) pkg.__dirname = path.dirname(id);
                pkgCache[id] = pkg;
                done();
            });
        });
        function done () { if (--pkgCount === 0) next() }
    })();

    function next () {
        mains.forEach(function (main, ix) {
            if (typeof main === 'object') {
                walk({ stream: main, file: entries[ix] }, top);
            }
            else walk(main, top)
        });

        if (mains.length === 0) {
            output.pause();
            output.queue(null);
            process.nextTick(function () { output.resume() });
        }
    }

    return output;

    function walk (id, parent, cb) {
        pending ++;

        if (typeof id === 'object') {
            id.stream.pipe(concat({ encoding: 'string' }, function (src) {
                var pkgfile = path.join(basedir, 'package.json');
                fs.readFile(pkgfile, function (err, pkgsrc) {
                    var pkg = {};
                    if (!err) {
                        try { pkg = JSON.parse(pkgsrc) }
                        catch (e) {};
                    }
                    var trx = getTransform(pkg);
                    applyTransforms(id.file, trx, src, pkg);
                });
            }));
            if (cb) cb(false);
            return;
        }

        var c = cache && cache[parent.id];
        var resolver = c && typeof c === 'object'
        && !Buffer.isBuffer(c) && c.deps[id]
            ? function (xid, xparent, cb) {
                var file = cache[parent.id].deps[id];
                cb(null, file, pkgCache && pkgCache[file]);
            }
            : resolve;
        ;

        var pkgdir;
        parent.packageFilter = function (p, x) {
            pkgdir = x;
            if (opts.packageFilter) return opts.packageFilter(p, x);
            else return p;
        };
        if (opts.extensions) parent.extensions = opts.extensions;
        if (opts.modules) parent.modules = opts.modules;

        resolver(id, parent, function f (err, file, pkg) {
            if (err) return output.emit('error', err);
            if (!file) return output.emit('error', new Error([
                'module not found: "' + id + '" from file ',
                parent.filename
            ].join('')));

            if (pkg && pkgdir) pkg.__dirname = pkgdir;
            if (!pkg || !pkg.__dirname) {
                lookupPkg(file, function (err, p) {
                    if (err) return output.emit('error', err);
                    if (!p) p = {};
                    if (!p.__dirname) p.__dirname = path.dirname(file);
                    pkgCache[file] = p;
                    f(err, file, opts.packageFilter ? opts.packageFilter(p, p.__dirname) : p);
                });
                return;
            }

            if (cb) cb(file);
            if (visited[file]) {
                if (--pending === 0) output.queue(null);
                return;
            }

            visited[file] = true;
            if (!pkg && pkgCache[file]) pkg = pkgCache[file];

            var trx = getTransform(pkg);

            if (cache && cache[file]) {
                parseDeps(file, cache[file], pkg);
            }
            else fs.readFile(file, 'utf8', function (err, src) {
                if (err) {
                    var e = new Error(
                        err.message
                        + ' while resolving '
                        + JSON.stringify(id)
                        + ' from file '
                        + parent.filename
                    );
                    Object.keys(err).forEach(function (key) {
                        e[key] = err[key];
                    });
                    if (err.code === 'ENOENT') {
                        e.type = 'not found';
                    }
                    e.parent = parent.filename;
                    e.filename = file;
                    return output.emit('error', e);
                }
                applyTransforms(file, trx, src, pkg);
            });
        });
    }

    function getTransform (pkg) {
        var trx = [];
        if (opts.transformKey) {
            var n = pkg;
            var keys = opts.transformKey;
            for (var i = 0; i < keys.length; i++) {
                if (n && typeof n === 'object') n = n[keys[i]];
                else break;
            }
            if (i === keys.length) {
                trx = [].concat(n).filter(Boolean);
            }
        }
        return trx.concat(opts.globalTransform || []);
    }

    function applyTransforms (file, trx, src, pkg) {
        var isTopLevel = mains.some(function (main) {
            var m = path.relative(path.dirname(main), file);
            return m.split('/').indexOf('node_modules') < 0;
        });
        var transf = (isTopLevel ? transforms : []).concat(trx);
        if (transf.length === 0) return done();

        (function ap (trs) {
            if (trs.length === 0) return done();
            var tr = trs[0], trOpts = {};
            if (Array.isArray(tr)) {
                trOpts = tr[1];
                tr = tr[0];
            }

            makeTransform(file, [ tr, trOpts ], function f (err, s) {
                if (err && pkg && pkg.__dirname) {
                    var t = path.resolve(pkg.__dirname, tr);
                    return makeTransform(file, [ t, trOpts ], function (e, s_) {
                        if (e) output.emit('error', e);
                        else f(null, s_);
                    });
                }
                if (err) return output.emit('error', err);

                s.on('error', output.emit.bind(output, 'error'));
                s.pipe(concat({ encoding: 'string' }, function (data) {
                    src = data;
                    ap(trs.slice(1));
                }));
                s.end(src);
            });
        })(transf);

        function done () {
            parseDeps(file, src, pkg);
        }
    }

    function parseDeps (file, src, pkg) {
        var deps;
        if (!Buffer.isBuffer(src) && typeof src === 'object') {
            deps = Object.keys(src.deps).sort();
            src = src.source;
        }
        else if (opts.noParse && opts.noParse.indexOf(file) >= 0) {
            deps = [];
        }
        else if (/\.json$/.test(file)) {
            deps = [];
        }
        else {
            try { var deps = detective(src) }
            catch (ex) {
                var message = ex && ex.message ? ex.message : ex;
                return output.emit('error', new Error(
                    'Parsing file ' + file + ': ' + message
                ));
            }
        }
        var p = deps.length;
        var current = { id: file, filename: file, paths: paths, package: pkg };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }

            walk(id, current, function (r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            var rec = {
                id: file,
                source: src,
                deps: resolved
            };
            if (entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            pushResult(rec);
        }
    }

    function makeTransform (file, tpair, cb) {
        var tr = tpair[0], trOpts = tpair[1];
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            output.emit('transform', t, file);
            return cb(null, t);
        }

        var params = { basedir: path.dirname(file) };
        nodeResolve(tr, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = process.cwd();
                nodeResolve(tr, params, function (e, r) {
                    nr(e, r, true)
                });
                return;
            }

            if (!res) return cb(new Error([
                'cannot find transform module ', tr,
                ' while transforming ', file
            ].join('')));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            output.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

function lookupPkg (file, cb) {
    var dirs = parents(path.dirname(file));
    (function next () {
        if (dirs.length === 0) return cb(null, undefined);
        var dir = dirs.shift();
        var pkgfile = path.join(dir, 'package.json');
        fs.readFile(pkgfile, function (err, src) {
            if (err) return next();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return cb(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;
            cb(null, pkg);
        });
    })();
}
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var Writable = require('stream').Writable;
var _ = require('lodash');
var TokenCache = require('google-oauth-jwt').TokenCache;
var request = require('request');
var tokens = new TokenCache();
/**
 * skipper-gcs
 *
 * @param  {Object} globalOpts
 * @return {Object}
 */
module.exports = function GCSStore(globalOpts) {
  globalOpts = globalOpts || {};
  _.defaults(globalOpts, {
    email: '',
    keyFile: '',
    bucket: '',
    scopes: ['https://www.googleapis.com/auth/devstorage.full_control']
  });
  var adapter = {
    ls: function(dirname, cb) { return cb(new Error('TODO')); },
    read: function(fd, cb) { return cb(new Error('TODO')); },
    rm: function(fd, cb) { return cb(new Error('TODO')); },
    /**
     * A simple receiver for Skipper that writes Upstreams to Google Cloud Storage
     *
     * @param  {Object} options
     * @return {Stream.Writable}
     */
    receive: function GCSReceiver(options) {
      options = options || {};
      options = _.defaults(options, globalOpts);
      var receiver__ = Writable({
        objectMode: true
      });
      // This `_write` method is invoked each time a new file is received
      // from the Readable stream (Upstream) which is pumping filestreams
      // into this receiver.  (filename === `__newFile.filename`).
      receiver__._write = function onFile(__newFile, encoding, done) {
        tokens.get({ email: options.email, keyFile: options.keyFile, scopes: options.scopes }, function(err, token) {
          // console.log('oauth token: ', token);
          var filename = typeof options.filename === 'undefined' ? __newFile.fd : options.filename + '.' + __newFile.filename.split('.').pop();
          var filepath = typeof options.path === 'undefined' ? filename : options.path + '/' + filename;
          var url = 'https://www.googleapis.com/upload/storage/v1/b/' + options.bucket + '/o?uploadType=media&name=' + encodeURIComponent(filepath);
          // console.log('file post url: ', url);
          __newFile.pipe(request.post({
            url: url,
            headers: { Authorization: 'Bearer ' + token, 'x-goog-api-version': 2 }
          }, function(err, res, body) {
            if (err) {
              receiver__.emit('error', err);
            } else {
              // console.log('upload response body: ', body);
              __newFile.extra = body;
              if (options.publicly) {
                request.post({
                  url: 'https://www.googleapis.com/storage/v1/b/' + options.bucket + '/o/' + encodeURIComponent(filepath) + '/acl',
                  headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token, 'x-goog-api-version': 2 },
                  json: { 'entity': 'allUsers', 'role': 'READER' }
                }, function(err, res, body) {
                  if (err) {
                    receiver__.emit('error', err);
                  } else {
                    // console.log('acl response body: ', body);
                    done();
                  }
                });
              } else {
                done();
              }
            }
          }));
        });
      }
      return receiver__;
    }
  };
  return adapter
};<commit_msg>Parse body that responsed from google to json.<commit_after>/**
 * Module dependencies
 */
var Writable = require('stream').Writable;
var _ = require('lodash');
var TokenCache = require('google-oauth-jwt').TokenCache;
var request = require('request');
var tokens = new TokenCache();
/**
 * skipper-gcs
 *
 * @param  {Object} globalOpts
 * @return {Object}
 */
module.exports = function GCSStore(globalOpts) {
  globalOpts = globalOpts || {};
  _.defaults(globalOpts, {
    email: '',
    keyFile: '',
    bucket: '',
    scopes: ['https://www.googleapis.com/auth/devstorage.full_control']
  });
  var adapter = {
    ls: function(dirname, cb) { return cb(new Error('TODO')); },
    read: function(fd, cb) { return cb(new Error('TODO')); },
    rm: function(fd, cb) { return cb(new Error('TODO')); },
    /**
     * A simple receiver for Skipper that writes Upstreams to Google Cloud Storage
     *
     * @param  {Object} options
     * @return {Stream.Writable}
     */
    receive: function GCSReceiver(options) {
      options = options || {};
      options = _.defaults(options, globalOpts);
      var receiver__ = Writable({
        objectMode: true
      });
      // This `_write` method is invoked each time a new file is received
      // from the Readable stream (Upstream) which is pumping filestreams
      // into this receiver.  (filename === `__newFile.filename`).
      receiver__._write = function onFile(__newFile, encoding, done) {
        tokens.get({ email: options.email, keyFile: options.keyFile, scopes: options.scopes }, function(err, token) {
          // console.log('oauth token: ', token);
          var filename = typeof options.filename === 'undefined' ? __newFile.fd : options.filename + '.' + __newFile.filename.split('.').pop();
          var filepath = typeof options.path === 'undefined' ? filename : options.path + '/' + filename;
          var url = 'https://www.googleapis.com/upload/storage/v1/b/' + options.bucket + '/o?uploadType=media&name=' + encodeURIComponent(filepath);
          // console.log('file post url: ', url);
          __newFile.pipe(request.post({
            url: url,
            headers: { Authorization: 'Bearer ' + token, 'x-goog-api-version': 2 }
          }, function(err, res, body) {
            if (err) {
              receiver__.emit('error', err);
            } else {
              // console.log('upload response body: ', body);
              __newFile.extra = JSON.parse(body);
              if (options.publicly) {
                request.post({
                  url: 'https://www.googleapis.com/storage/v1/b/' + options.bucket + '/o/' + encodeURIComponent(filepath) + '/acl',
                  headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token, 'x-goog-api-version': 2 },
                  json: { 'entity': 'allUsers', 'role': 'READER' }
                }, function(err, res, body) {
                  if (err) {
                    receiver__.emit('error', err);
                  } else {
                    // console.log('acl response body: ', body);
                    done();
                  }
                });
              } else {
                done();
              }
            }
          }));
        });
      }
      return receiver__;
    }
  };
  return adapter
};<|endoftext|>


<commit_before>'use strict';

const replace = require('broccoli-string-replace');
const Favicon = require('broccoli-favicon').default;
const mergeTrees = require('broccoli-merge-trees');
const deepMerge = require('lodash.merge');

let htmlCache = null;

module.exports = {
  name: require('./package').name,

  included(parent) {
    this._super.included.apply(this, arguments);

    // Set default options
    let isProductionEnv = parent.env === 'production'

    let defaultOptions = {
      enabled: parent.env != 'test',
      faviconsConfig: {
        path: parent.project.config(parent.env).rootUrl,
        appName: parent.project.pkg.name,
        appShortName: parent.project.pkg.name,
        appDescription: parent.project.pkg.description,
        developerName: parent.project.pkg.author,
        version: parent.project.version,
        icons: {
          favicons: true,
          android: isProductionEnv,
          appleIcon: isProductionEnv,
          appleStartup: isProductionEnv,
          coast: isProductionEnv,
          firefox: isProductionEnv,
          windows: isProductionEnv,
          yandex: isProductionEnv
        }
      }
    }

    this.addonConfig = deepMerge({}, defaultOptions, (parent.options['ember-cli-favicon'] || {}));

    // Set success callback
    let currentCallback = this.addonConfig.onSuccess || function() {};

    this.addonConfig.onSuccess = function(html) {
      htmlCache = html;
      return currentCallback(...arguments);
    };

    // Support for fingerprint
    parent.options.fingerprint = parent.options.fingerprint || {};
    parent.options.fingerprint.exclude = parent.options.fingerprint.exclude || [];
    parent.options.fingerprint.exclude.push(
      'android-chrome',
      'apple-touch-icon',
      'apple-touch-startup-image',
      'coast',
      'favicon',
      'mstile',
      'firefox_app',
      'yandex-browser'
    );

    this.publicTree = parent.options.trees.public;
  },

  treeForPublic(tree) {
    if (this.addonConfig.enabled) {
      let faviconTree = new Favicon(this.publicTree, this.addonConfig)
      return mergeTrees([ faviconTree, tree ].filter(Boolean), { overwrite: true });
    } else {
      return tree;
    }
  },

  postprocessTree(type, tree) {
    if (type === 'all' && this.addonConfig.enabled) {
      return replace(tree, {
        files: [ 'index.html' ],
        patterns: [{
          match: /<\/head>/i,
          replacement: function() {
            return '  ' + (htmlCache || []).join('\n    ') + '\n  </head>';
          }
        }]
      });
    }

    return tree;
  }
};
<commit_msg>Fix path property (rootURL)<commit_after>'use strict';

const replace = require('broccoli-string-replace');
const Favicon = require('broccoli-favicon').default;
const mergeTrees = require('broccoli-merge-trees');
const deepMerge = require('lodash.merge');

let htmlCache = null;

module.exports = {
  name: require('./package').name,

  included(parent) {
    this._super.included.apply(this, arguments);

    // Set default options
    let isProductionEnv = parent.env === 'production'

    let defaultOptions = {
      enabled: parent.env != 'test',
      faviconsConfig: {
        path: parent.project.config(parent.env).rootURL,
        appName: parent.project.pkg.name,
        appShortName: parent.project.pkg.name,
        appDescription: parent.project.pkg.description,
        developerName: parent.project.pkg.author,
        version: parent.project.version,
        icons: {
          favicons: true,
          android: isProductionEnv,
          appleIcon: isProductionEnv,
          appleStartup: isProductionEnv,
          coast: isProductionEnv,
          firefox: isProductionEnv,
          windows: isProductionEnv,
          yandex: isProductionEnv
        }
      }
    }

    this.addonConfig = deepMerge({}, defaultOptions, (parent.options['ember-cli-favicon'] || {}));

    // Set success callback
    let currentCallback = this.addonConfig.onSuccess || function() {};

    this.addonConfig.onSuccess = function(html) {
      htmlCache = html;
      return currentCallback(...arguments);
    };

    // Support for fingerprint
    parent.options.fingerprint = parent.options.fingerprint || {};
    parent.options.fingerprint.exclude = parent.options.fingerprint.exclude || [];
    parent.options.fingerprint.exclude.push(
      'android-chrome',
      'apple-touch-icon',
      'apple-touch-startup-image',
      'coast',
      'favicon',
      'mstile',
      'firefox_app',
      'yandex-browser'
    );

    this.publicTree = parent.options.trees.public;
  },

  treeForPublic(tree) {
    if (this.addonConfig.enabled) {
      let faviconTree = new Favicon(this.publicTree, this.addonConfig)
      return mergeTrees([ faviconTree, tree ].filter(Boolean), { overwrite: true });
    } else {
      return tree;
    }
  },

  postprocessTree(type, tree) {
    if (type === 'all' && this.addonConfig.enabled) {
      return replace(tree, {
        files: [ 'index.html' ],
        patterns: [{
          match: /<\/head>/i,
          replacement: function() {
            return '  ' + (htmlCache || []).join('\n    ') + '\n  </head>';
          }
        }]
      });
    }

    return tree;
  }
};
<|endoftext|>


<commit_before>'use strict'

var express = require('express')
var bodyParser = require('body-parser')
var request = require('request')

var Config = require('./config')
var FB = require('./connectors/facebook')
var Bot = require('./bot')

// LETS MAKE A SERVER!
var app = express()
app.set('port', (process.env.PORT) || 5000)
// SPIN UP SERVER
app.listen(app.get('port'), function () {
  console.log('Running on port', app.get('port'))
})
// PARSE THE BODY
app.use(bodyParser.json())

// index page
app.get('/', function (req, res) {
  res.send('hello world i am a chat bot')
})

// for facebook to verify
app.get('/webhooks', function (req, res) {
  if (req.query['hub.verify_token'] === Config.VERIFICATION_TOKEN) {
    res.send(req.query['hub.challenge'])
  }
  res.send('Error, wrong token')
})

// to send messages to facebook
app.post('/webhooks', function (req, res) {
  var entry = FB.getMessageEntry(req.body)
  // IS THE ENTRY A VALID MESSAGE?
  if (entry && entry.message) {
        if (entry.message.attachments) {
          // NOT SMART ENOUGH FOR ATTACHMENTS YET
          FB.newMessage(entry.sender.id, "That's interesting!")
        }
        else {
          // SEND TO BOT FOR PROCESSING
          Bot.read(entry.sender.id, entry.message.text, function (sender, reply) {
            FB.newMessage(sender, reply)
          })
        }

  } else if (entry.postback){
          Bot.read(entry.sender.id, entry.postback.payload, function (sender, reply) {
            FB.newMessage(sender, reply)
          })
        }

  res.sendStatus(200)
})

// app.post('/webhooks', function (req, res) {
//   var entry = FB.getMessageEntry(req.body)
//   // IS THE ENTRY A VALID MESSAGE?
//   runWit(entry)
// })

// function runWit(entry) {
//   if (entry && entry.message) {
//     if (entry.message.attachments) {
//       // NOT SMART ENOUGH FOR ATTACHMENTS YET
//       FB.newMessage(entry.sender.id, "That's interesting!")
//     }
//     else {
//       // SEND TO BOT FOR PROCESSING
//       Bot.read(entry.sender.id, entry.message.text, function (sender, reply) {
//         FB.newMessage(sender, reply)
//       })
//     }
//   } else if (entry.postback){
//       Bot.read(entry.sender.id, entry.postback.payload, function (sender, reply) {
//         FB.newMessage(sender, reply)
//       })
//   }
// }<commit_msg>add log<commit_after>'use strict'

var express = require('express')
var bodyParser = require('body-parser')
var request = require('request')

var Config = require('./config')
var FB = require('./connectors/facebook')
var Bot = require('./bot')

// LETS MAKE A SERVER!
var app = express()
app.set('port', (process.env.PORT) || 5000)
// SPIN UP SERVER
app.listen(app.get('port'), function () {
  console.log('Running on port', app.get('port'))
})
// PARSE THE BODY
app.use(bodyParser.json())

// index page
app.get('/', function (req, res) {
  res.send('hello world i am a chat bot')
})

// for facebook to verify
app.get('/webhooks', function (req, res) {
  if (req.query['hub.verify_token'] === Config.VERIFICATION_TOKEN) {
    res.send(req.query['hub.challenge'])
  }
  res.send('Error, wrong token')
})

// to send messages to facebook
app.post('/webhooks', function (req, res) {
  var entry = FB.getMessageEntry(req.body)
  // IS THE ENTRY A VALID MESSAGE?
  if (entry && entry.message && !entry.message.is_echo) {
        if (entry.message.attachments) {
          // NOT SMART ENOUGH FOR ATTACHMENTS YET
          FB.newMessage(entry.sender.id, "That's interesting!")
        }
        else {
          // SEND TO BOT FOR PROCESSING
          Bot.read(entry.sender.id, entry.message.text, function (sender, reply) {
            FB.newMessage(sender, reply)
          })
        }

  } else if (entry.postback){
          Bot.read(entry.sender.id, entry.postback.payload, function (sender, reply) {
            FB.newMessage(sender, reply)
          })
        }

  res.sendStatus(200)
})

// app.post('/webhooks', function (req, res) {
//   var entry = FB.getMessageEntry(req.body)
//   // IS THE ENTRY A VALID MESSAGE?
//   runWit(entry)
// })

// function runWit(entry) {
//   if (entry && entry.message) {
//     if (entry.message.attachments) {
//       // NOT SMART ENOUGH FOR ATTACHMENTS YET
//       FB.newMessage(entry.sender.id, "That's interesting!")
//     }
//     else {
//       // SEND TO BOT FOR PROCESSING
//       Bot.read(entry.sender.id, entry.message.text, function (sender, reply) {
//         FB.newMessage(sender, reply)
//       })
//     }
//   } else if (entry.postback){
//       Bot.read(entry.sender.id, entry.postback.payload, function (sender, reply) {
//         FB.newMessage(sender, reply)
//       })
//   }
// }<|endoftext|>


<commit_before>'use strict';

import { NativeModules, NativeAppEventEmitter } from 'react-native';

const NativeCallDetector = NativeModules.CallDetectionManager;
module.exports = NativeCallDetector
// NativeCallDetector.startListener();

// class CallDetector {
//     static listeners = {};

//     name;
//     subscription;

//     constructor(name, callback) {
//         if(CallDetector.listeners[name]) CallDetector.listeners[name].dispose();
//         CallDetector.listeners[name] = this;
//         this.subscription = NativeAppEventEmitter.addListener('PhoneCallUpdate', callback);
//     }

//     dispose() {
//         if(this.subscription) this.subscription.remove();
//         CallDetector.stopListener()
//         delete CallDetector.listeners[this.name];
//     }
// }

// export default module.exports = CallDetector;
<commit_msg>updated index js<commit_after>import { NativeModules } from 'react-native'
module.exports = NativeModules.CallDetectionManager

// NativeCallDetector.startListener();

// class CallDetector {
//     static listeners = {};

//     name;
//     subscription;

//     constructor(name, callback) {
//         if(CallDetector.listeners[name]) CallDetector.listeners[name].dispose();
//         CallDetector.listeners[name] = this;
//         this.subscription = NativeAppEventEmitter.addListener('PhoneCallUpdate', callback);
//     }

//     dispose() {
//         if(this.subscription) this.subscription.remove();
//         CallDetector.stopListener()
//         delete CallDetector.listeners[this.name];
//     }
// }

// export default module.exports = CallDetector;
<|endoftext|>


<commit_before>/*eslint strict:0*/

/**
 * Creates a generic function
 * @arg {function(methods, arguments[])} getMethod
 * Getter that maps arbitrary arguments to a method in the methods record.
 * @arg {function(method, arguments[])} applyMethod
 * Function that maps arbitrary arguments to a method.
 * @arg {function} defaultMethod
 * Function to use when no method is found.
 * @arg {*} methods Data structure to hold the methods.
 * @return {function(...*)} Generic function.
 */

module.exports = function create(getMethod, applyMethod, defaultMethod, methods) {
    return function generic(/* arguments */) {
        var meth = getMethod(methods, arguments);
        var fn = typeof meth === 'function' ? meth : defaultMethod;
        return applyMethod(fn, arguments);
    };
};
<commit_msg>refine jsdoc<commit_after>/*eslint strict:0*/

/** @typedef {*} methods */

/** @typedef {function} method */

/**
 * Function to select a specific method from the set of methods based on the arguments.
 * @callback getMethod
 * @arg {methods} methods Data structure to hold the methods.
 * @arg {*[]} args Arguments array.
 * @return {method} Method to invoke.
 */

/**
 * Function that applies arbitrary arguments to a method.
 * @callback applyMethod
 * @arg {method} method Method to use.
 * @arg {*[]} args Arguments array to apply to the method.
 * @return {*} Any value.
 */

/**
 * Creates a generic function
 * @arg {getMethod} getMethod
 * Function to select a specific method from the set of methods based on the arguments.
 * @arg {applyMethod} applyMethod
 * Function that applies arbitrary arguments to a method.
 * @arg {method} defaultMethod
 * Function to use when no method is found.
 * @arg {methods} methods Data structure to hold the methods.
 * @return {function} Generic function.
 */

module.exports = function create(getMethod, applyMethod, defaultMethod, methods) {
    return function generic(/* arguments */) {
        var method = getMethod(methods, arguments);
        var fn = typeof method === 'function' ? method : defaultMethod;
        return applyMethod(fn, arguments);
    };
};
<|endoftext|>


<commit_before>/*
* HTTP Cloud Function.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.helloHttp = function helloHttp (req, res) {
  response = "This is a sample response from your webhook!" //Default response from the webhook to show it's working

  res.setHeader('Content-Type', 'application/json'); //Requires application/json MIME type
  res.send(JSON.stringify({ "speech": response, "displayText": response
  //"speech" is the spoken version of the response, "displayText" is the visual version
  }));
};<commit_msg>new webhook<commit_after>/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.post('/hook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';

        if (req.body) {
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    speech += 'action: ' + requestBody.result.action;
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            source: 'apiai-webhook-sample'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<|endoftext|>


<commit_before>const logSymbols = require('log-symbols');
const linguist = require('./lib/linguist');

const rulesToRun = [
  require('./rules/file_existence').bind(null, {name: 'License file', files: ['LICENSE*', 'COPYING*']}),
  require('./rules/file_existence').bind(null, {name: 'Readme file', files: ['README*']}),
  require('./rules/file_existence').bind(null, {name: 'Contributing file', files: ['CONTRIBUT*']}),
  require('./rules/file_contents').bind(null, {file: 'README.md', content: 'License'}),
  require('./rules/file_type_exclusion').bind(null, {type: ['*.dll', '*.exe']}),
  require('./rules/licensee_check').bind(null, {name: 'Licensee Check'}),
  require('./rules/directory_existence').bind(null, {name: 'Test directory', directories: ['spec*', 'test*']}),
  require('./rules/file_starts_with').bind(null, {name: 'Source license headers', files: ['**/*.js'], ignore: 'node_modules/**', patterns: [/Copyright/i, /All rights reserved/i], line_count: 5})
]

const languageSpecificRules = {
  'Java' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['pom.xml', 'build.xml']}),
  ],
  'Ruby' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['Gemfile']}),
  ],
  'JavaScript' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['package.json']}),
  ]
}

const targetDir = process.argv[2];
rulesToRun.forEach(rule => {
  const result = rule(targetDir);
  renderResults(result.failures, false);
  renderResults(result.passes, true);
});

try {
  languages=linguist.identifyLanguagesSync(targetDir)

  for (var language in languages) {

    console.log(`Language Checks [${language}]:`);

    if(languageSpecificRules[language] == null) {

      console.log('  n/a');

    } else {

      languageSpecificRules[language].forEach(rule => {
        const result = rule(targetDir);
        renderResults(result.failures, false);
        renderResults(result.passes, true);
      });

    }
  }
} catch(e) {
  console.log("NOTE: Linguist not installed")
  // Linguist wasn't installed (one presumes)
}

function renderResults(results, success) {
  if (results) {
    results.forEach(result => renderResult(result, success));
  }
}

function renderResult(message, success) {
  console.log(success ? logSymbols.success : logSymbols.error, message);
}
<commit_msg>Adding maven src/test as a valid test location<commit_after>const logSymbols = require('log-symbols');
const linguist = require('./lib/linguist');

const rulesToRun = [
  require('./rules/file_existence').bind(null, {name: 'License file', files: ['LICENSE*', 'COPYING*']}),
  require('./rules/file_existence').bind(null, {name: 'Readme file', files: ['README*']}),
  require('./rules/file_existence').bind(null, {name: 'Contributing file', files: ['CONTRIBUT*']}),
  require('./rules/file_contents').bind(null, {file: 'README.md', content: 'License'}),
  require('./rules/file_type_exclusion').bind(null, {type: ['*.dll', '*.exe']}),
  require('./rules/licensee_check').bind(null, {name: 'Licensee Check'}),
  require('./rules/directory_existence').bind(null, {name: 'Test directory', directories: ['spec*', 'test*', 'src/test']}),
  require('./rules/file_starts_with').bind(null, {name: 'Source license headers', files: ['**/*.js'], ignore: 'node_modules/**', patterns: [/Copyright/i, /All rights reserved/i], line_count: 5})
]

const languageSpecificRules = {
  'Java' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['pom.xml', 'build.xml']}),
  ],
  'Ruby' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['Gemfile']}),
  ],
  'JavaScript' : [
    require('./rules/file_existence').bind(null, {name: 'Build file', files: ['package.json']}),
  ]
}

const targetDir = process.argv[2];
rulesToRun.forEach(rule => {
  const result = rule(targetDir);
  renderResults(result.failures, false);
  renderResults(result.passes, true);
});

try {
  languages=linguist.identifyLanguagesSync(targetDir)

  for (var language in languages) {

    console.log(`Language Checks [${language}]:`);

    if(languageSpecificRules[language] == null) {

      console.log('  n/a');

    } else {

      languageSpecificRules[language].forEach(rule => {
        const result = rule(targetDir);
        renderResults(result.failures, false);
        renderResults(result.passes, true);
      });

    }
  }
} catch(e) {
  console.log("NOTE: Linguist not installed")
  // Linguist wasn't installed (one presumes)
}

function renderResults(results, success) {
  if (results) {
    results.forEach(result => renderResult(result, success));
  }
}

function renderResult(message, success) {
  console.log(success ? logSymbols.success : logSymbols.error, message);
}
<|endoftext|>


<commit_before>define(['require', 'exports'], function(require, exports) {
	var defaultData = exports.defaultData = {
		root: parentify(nameify({
			name: 'FILESYSTEM_ROOT_/',
			files: {
				home: {
					files: {
						user: {
							files: {
								'README.md': {
									contents: ''
								}
							}
						}
					}
				}
			}
		}))
	};

	function clone(o) {
		function O() {}
		O.prototype = o;
		return new O;
	}

	var Filesystem = exports.Filesystem = (function() {
		function Filesystem() {
			this.data = nameify(parentify(data || clone(defaultData)));
			this.currentDir = this.data.root;
		}

		//var currentDir = exports.currentDir = fs.root;

		Filesystem.prototype.getFile = function getFile(path, curDir) {
				var tmpDir, pathArr;

				if(!curDir) curDir = this.currentDir;
				if(!path || path.length == 0) return curDir;
				if(path.length > 0 && path[0] == '/') curDir = this.data.root;

				tmpDir = curDir;
				pathArr = path.split('/');

				pathArr.forEach(function(part) {
					if(part) {
						if(part == '..') {
							tmpDir = tmpDir.parent || tmpDir;
						} else if(part == '.') {
							return;
						} else if(this.isDir(tmpDir)) {
							if(this.hasFile(tmpDir, part)) tmpDir = tmpDir.files[part];
							else throw new Error("FileNotFoundError: Can not find file: '" +
								part +
								"' in directory: '" +
								this.pathTo(tmpDir));
							if(this.isSymlink(tmpDir)) {
								tmpDir = this.getSymlink(tmpDir);
							}
						} else {
							return false;
						}
					}
				});

				return tmpDir;
		};

		Filesystem.prototype.pathTo = function pathTo(file, /* internal */ isNested) {
			if(!isNested && file.name == this.data.root.name) return '/';
			if(!!file === false || (!!file && !!file.name && file.name == fs.root.name)) {
				return "";
			}

			return this.pathTo(file.parent, true) + '/' + file.name;
		};

		Filesystem.prototype.changeDir = function changeDir(dir) {
			if(dir && this.isDir(dir)) this.currentDir = dir;

			return dir;
		}

		Filesystem.prototype.createFile = function createFile(fileName, curDir) {
			var split, dir;

			if(!curDir) curDir = this.currentDir;

			split = fileName.split('/');
			dir = this.getFile(split.slice(0, split.length - 2).join('/'), curDir);

			console.log('dir:', dir);

			if(!this.hasFile(dir, split[split.length - 1])) {
				return dir.files[split[split.length - 1]] = {
					name: split[split.length - 1]
				};
			}
		};

		Filesystem.prototype.getSymlink = function getSymlink(file, curDir) {
			if(this.isSymlink(file)) return this.getFile(file.symlink, curDir);

			return file;
		}

		Filesystem.prototype.writeData = function writeData(file, data) {
			if(file && data) file.contents = data;

			return file;
		};

		Filesystem.prototype.initDir = function initDir(file) {
			if(file && !file.files) file.files = {};

			return file;
		};

		Filesystem.prototype.symlink = function symlink(file, where) {
			file.symlink = where;

			return file;
		};

		Filesystem.prototype.readFile = function readFile(file) {
			if(!file) return undefined;

			file = this.getSymlink(file);

			if(file && this.isFile(file)) return file.contents;
		}

		Filesystem.prototype.listFiles = function listFiles(dir) {
			dir = dir || this.currentDir;

			if(!this.isDir(dir)) return undefined;

			return Object.keys(dir.files).map(function(name) {
				return dir.files[name];
			});
		}

		Filesystem.prototype.hasFile = function hasFile(dir, name) {
			return dir && dir.files && dir.files[name];
		};

		Filesystem.prototype.isDir = function isDir(file) {
			return file && file.files;
		};

		Filesystem.prototype.isFile = function isFile(file) {
			return file && file.contents !== null && file.contents !== undefined;
		};

		Filesystem.prototype.isSymlink = function isSymlink(file) {
			return file && file.symlink;
		}

		return Filesystem;
	})();

	function parentify(data) {
		for(var key in data.files) {
			data.files[key].parent = data;

			if(data.files[key].files) data.files[key] = parentify(data.files[key]);
		}

		return data;
	}

	function nameify(data) {
		for(var key in data.files) {
			data.files[key].name = key;

			if(data.files[key].files) data.files[key] = nameify(data.files[key]);
		}

		return data;
	}
});
<commit_msg>fixed bug where data is not found<commit_after>define(['require', 'exports'], function(require, exports) {
	var defaultData = exports.defaultData = {
		root: parentify(nameify({
			name: 'FILESYSTEM_ROOT_/',
			files: {
				home: {
					files: {
						user: {
							files: {
								'README.md': {
									contents: ''
								}
							}
						}
					}
				}
			}
		}))
	};

	function clone(o) {
		function O() {}
		O.prototype = o;
		return new O;
	}

	var Filesystem = exports.Filesystem = (function() {
		function Filesystem(data) {
			this.data = nameify(parentify(data || clone(defaultData)));
			this.currentDir = this.data.root;
		}

		//var currentDir = exports.currentDir = fs.root;

		Filesystem.prototype.getFile = function getFile(path, curDir) {
				var tmpDir, pathArr;

				if(!curDir) curDir = this.currentDir;
				if(!path || path.length == 0) return curDir;
				if(path.length > 0 && path[0] == '/') curDir = this.data.root;

				tmpDir = curDir;
				pathArr = path.split('/');

				pathArr.forEach(function(part) {
					if(part) {
						if(part == '..') {
							tmpDir = tmpDir.parent || tmpDir;
						} else if(part == '.') {
							return;
						} else if(this.isDir(tmpDir)) {
							if(this.hasFile(tmpDir, part)) tmpDir = tmpDir.files[part];
							else throw new Error("FileNotFoundError: Can not find file: '" +
								part +
								"' in directory: '" +
								this.pathTo(tmpDir));
							if(this.isSymlink(tmpDir)) {
								tmpDir = this.getSymlink(tmpDir);
							}
						} else {
							return false;
						}
					}
				});

				return tmpDir;
		};

		Filesystem.prototype.pathTo = function pathTo(file, /* internal */ isNested) {
			if(!isNested && file.name == this.data.root.name) return '/';
			if(!!file === false || (!!file && !!file.name && file.name == fs.root.name)) {
				return "";
			}

			return this.pathTo(file.parent, true) + '/' + file.name;
		};

		Filesystem.prototype.changeDir = function changeDir(dir) {
			if(dir && this.isDir(dir)) this.currentDir = dir;

			return dir;
		}

		Filesystem.prototype.createFile = function createFile(fileName, curDir) {
			var split, dir;

			if(!curDir) curDir = this.currentDir;

			split = fileName.split('/');
			dir = this.getFile(split.slice(0, split.length - 2).join('/'), curDir);

			console.log('dir:', dir);

			if(!this.hasFile(dir, split[split.length - 1])) {
				return dir.files[split[split.length - 1]] = {
					name: split[split.length - 1]
				};
			}
		};

		Filesystem.prototype.getSymlink = function getSymlink(file, curDir) {
			if(this.isSymlink(file)) return this.getFile(file.symlink, curDir);

			return file;
		}

		Filesystem.prototype.writeData = function writeData(file, data) {
			if(file && data) file.contents = data;

			return file;
		};

		Filesystem.prototype.initDir = function initDir(file) {
			if(file && !file.files) file.files = {};

			return file;
		};

		Filesystem.prototype.symlink = function symlink(file, where) {
			file.symlink = where;

			return file;
		};

		Filesystem.prototype.readFile = function readFile(file) {
			if(!file) return undefined;

			file = this.getSymlink(file);

			if(file && this.isFile(file)) return file.contents;
		}

		Filesystem.prototype.listFiles = function listFiles(dir) {
			dir = dir || this.currentDir;

			if(!this.isDir(dir)) return undefined;

			return Object.keys(dir.files).map(function(name) {
				return dir.files[name];
			});
		}

		Filesystem.prototype.hasFile = function hasFile(dir, name) {
			return dir && dir.files && dir.files[name];
		};

		Filesystem.prototype.isDir = function isDir(file) {
			return file && file.files;
		};

		Filesystem.prototype.isFile = function isFile(file) {
			return file && file.contents !== null && file.contents !== undefined;
		};

		Filesystem.prototype.isSymlink = function isSymlink(file) {
			return file && file.symlink;
		}

		return Filesystem;
	})();

	function parentify(data) {
		for(var key in data.files) {
			data.files[key].parent = data;

			if(data.files[key].files) data.files[key] = parentify(data.files[key]);
		}

		return data;
	}

	function nameify(data) {
		for(var key in data.files) {
			data.files[key].name = key;

			if(data.files[key].files) data.files[key] = nameify(data.files[key]);
		}

		return data;
	}
});
<|endoftext|>


<commit_before>module.exports = function (Socket) {

    Socket.prototype.givePromise = function(event, callback, timeout) {
        var self = this;

        var timedOutOrEventEmitted = function(data){
            self.removeListener(event, timedOutOrEventEmitted);
            callback(data, self);
            this.promiseDelay = clearTimeout(self.promiseDelay);
        };
        this.on(event, timedOutOrEventEmitted);
        this.promiseDelay = setTimeout(timedOutOrEventEmitted, timeout);
    };
};
<commit_msg>added emit method<commit_after>module.exports = function (Socket) {

    Socket.prototype.givePromise = function(event, args, callback, timeout) {
        var self = this;

        var timedOutOrEventEmitted = function(data){
            self.removeListener(event, timedOutOrEventEmitted);
            callback(data, self);
            self.promiseDelay = clearTimeout(self.promiseDelay);
        };
        this.emit(event, args);
        this.on(event, timedOutOrEventEmitted);
        this.promiseDelay = setTimeout(timedOutOrEventEmitted, timeout);
    };
};
<|endoftext|>


<commit_before>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
'user strict'
var MAX_LOGS = process.env.LOGSENE_BULK_SIZE || 1000
var MAX_STORED_REQUESTS = process.env.LOGSENE_MAX_STORED_REQUESTS || 10000
var MAX_CLIENT_SOCKETS = Number(process.env.MAX_CLIENT_SOCKETS) || 10
var request = require('request')
var os = require('os')
var events = require('events')
var ipAddress = require('ip').address()
var util = require('util')
var path = require('path')
var stringifySafe = require('json-stringify-safe')
var streamBuffers = require('stream-buffers')
var initialBufferSize = 1024 * 256
var incrementBuffer = 1024 * 256
/**
 * token - the LOGSENE Token
 * type - type of log (string)
 * url - optional alternative URL for Logsene receiver (e.g. for on premises version)
 */
function Logsene (token, type, url, storageDirectory) {
  if (!token) {
    throw new Error('Logsene token not specified')
  }
  this.setUrl(url || process.env.LOGSENE_URL || 'https://logsene-receiver.sematext.com/_bulk')
  this.token = token
  this.type = type || 'logs'
  this.hostname = os.hostname()
  this.bulkReq = new streamBuffers.WritableStreamBuffer({
    initialSize: initialBufferSize,
    incrementAmount: incrementBuffer
  })
  this.offset
  this.logCount = 0
  this.sourceName = null
  if (process.mainModule && process.mainModule.filename) {
    this.sourceName = path.basename(process.mainModule.filename)
  }
  events.EventEmitter.call(this)
  var self = this
  var tid = setInterval(function () {
    if (self.logCount > 0) {
      self.send()
    }
  }, process.env.LOGSENE_LOG_INTERVAL || 10000)
  if (tid.unref) {
    tid.unref()
  }
  process.on('exit', function () {
    self.send()
  })
  if (process.env.LOGSENE_TMP_DIR || storageDirectory) {
    this.diskBuffer(true, process.env.LOGSENE_TMP_DIR || storageDirectory)
  }
}
util.inherits(Logsene, events.EventEmitter)

Logsene.prototype.setUrl = function (url) {
  this.url = url
  var Agent = null
  if (/^https/.test(url)) {
    Agent = require('https').Agent
  } else {
    Agent = require('http').Agent
  }
  this.httpAgent = new Agent({maxSockets: MAX_CLIENT_SOCKETS})
}
var DiskBuffer = require('./DiskBuffer.js')

Logsene.prototype.diskBuffer = function (enabled, dir) {
  if (enabled) {
    var tmpDir = path.join((dir || require('os').tmpdir()), this.token)
    this.db = DiskBuffer.createDiskBuffer({
      tmpDir: tmpDir,
      maxStoredRequests: MAX_STORED_REQUESTS,
      interval: process.env.LOGSENE_DISK_BUFFER_INTERVAL || 120000
    })
    this.db.syncFileListFromDir()
    this.db.on('retransmit-req', function (event) {
      this.shipFile(event.fileName, event.buffer, function (err, res) {
        this.db.rmFile(event.fileName)
        this.db.retransmitNext()
      }.bind(this))
    }.bind(this))
  }
  this.persistence = enabled
}

/**
 * Add log message to send buffer
 * @param level - log level e.g. 'info', 'warning', 'error'
 * @param message - text message
 * @param fields - Object with custom fields or overwrite of any other field e.g. e.g. "{@timestamp: new Date.toISOString()}"
 * @param callback (err, msg object)
 */
Logsene.prototype.log = function (level, message, fields, callback) {
  var type = fields ? fields._type : this.type
  if (fields && fields._type) {
    delete fields._type
  }
  var msg = {'@timestamp': new Date(), message: message, severity: level, host: this.hostname, ip: ipAddress}
  for (var x in fields) {
    // rename fields for Elasticsearch 2.x
    msg[x.replace(/\./g, '_').replace(/^_+/, '')] = fields[x]
  }
  if (typeof msg['@timestamp'] === 'number') {
    msg['@timestamp'] = new Date(msg['@timestamp'])
  }
  this.bulkReq.write(JSON.stringify({'index': {'_index': this.token, '_type': type || this.type}}) + '\n')
  this.bulkReq.write(stringifySafe(msg) + '\n')
  this.logCount++
  if (this.logCount === MAX_LOGS) {
    this.bulkReq.end()
    this.send()
  }
  if (callback) {
    callback(null, msg)
  }
}

/**
 * Sending log entry  to LOGSENE - this function is triggered every 100 log message or 30 seconds.
 * @callback {function} optional callback function
 */
Logsene.prototype.send = function (callback) {
  var self = this
  var count = this.logCount
  this.logCount = 0
  var options = {
    url: this.url,
    logCount: count,
    headers: {
      'User-Agent': 'logsene-js',
      'Content-Type': 'application/json',
      'Connection': 'Close'
    },
    body: this.bulkReq.getContents(),
    agent: self.httpAgent,
    method: 'POST'
  }
  this.bulkReq = null
  this.bulkReq = new streamBuffers.WritableStreamBuffer({
    initialSize: initialBufferSize,
    incrementAmount: incrementBuffer
  })
  if (options.body === false) {
    return
  }
  var req = request.post(options, function (err, res) {
    if (err) {
      self.emit('error', {source: 'logsene', err: err})
      if (self.persistence) {
        options.agent = false
        self.db.store({options: options}, function () {
          delete options.body
        })
        return
      }
      req.destroy()
    } else {
      self.emit('log', {source: 'logsene', count: count})
      if (callback) {
        callback(null, res)
      }
      delete options.body
      req.destroy()
    }
  })
}

Logsene.prototype.shipFile = function (name, data, cb) {
  var self = this
  var options = JSON.parse(data)
  options.url = self.url
  options.agent = self.httpAgent
  var req = request.post(options, function (err, res) {
    if (cb) {
      cb(err, res)
    }
    if (err) {
      self.emit('error', {source: 'logsene', err: err})
      if (self.persistence) {
        options.agent = false
        self.db.store({options: options}, function () {
          delete options.body
        })
      }
    } else {
      self.emit('file shipped', {file: name, count: options.count})
      self.emit('rt', {count: options.count, source: 'logsene', file: name, url: String(options.url), request: null, response: null})
    }
    req.destroy()
  })
}

module.exports = Logsene
<commit_msg>emit logged event for better testing<commit_after>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
'user strict'
var MAX_LOGS = process.env.LOGSENE_BULK_SIZE || 1000
var MAX_STORED_REQUESTS = process.env.LOGSENE_MAX_STORED_REQUESTS || 10000
var MAX_CLIENT_SOCKETS = Number(process.env.MAX_CLIENT_SOCKETS) || 10
var request = require('request')
var os = require('os')
var events = require('events')
var ipAddress = require('ip').address()
var util = require('util')
var path = require('path')
var stringifySafe = require('json-stringify-safe')
var streamBuffers = require('stream-buffers')
var initialBufferSize = 1024 * 256
var incrementBuffer = 1024 * 256
/**
 * token - the LOGSENE Token
 * type - type of log (string)
 * url - optional alternative URL for Logsene receiver (e.g. for on premises version)
 */
function Logsene (token, type, url, storageDirectory) {
  if (!token) {
    throw new Error('Logsene token not specified')
  }
  this.setUrl(url || process.env.LOGSENE_URL || 'https://logsene-receiver.sematext.com/_bulk')
  this.token = token
  this.type = type || 'logs'
  this.hostname = os.hostname()
  this.bulkReq = new streamBuffers.WritableStreamBuffer({
    initialSize: initialBufferSize,
    incrementAmount: incrementBuffer
  })
  this.offset
  this.logCount = 0
  this.sourceName = null
  if (process.mainModule && process.mainModule.filename) {
    this.sourceName = path.basename(process.mainModule.filename)
  }
  events.EventEmitter.call(this)
  var self = this
  var tid = setInterval(function () {
    if (self.logCount > 0) {
      self.send()
    }
  }, process.env.LOGSENE_LOG_INTERVAL || 10000)
  if (tid.unref) {
    tid.unref()
  }
  process.on('exit', function () {
    self.send()
  })
  if (process.env.LOGSENE_TMP_DIR || storageDirectory) {
    this.diskBuffer(true, process.env.LOGSENE_TMP_DIR || storageDirectory)
  }
}
util.inherits(Logsene, events.EventEmitter)

Logsene.prototype.setUrl = function (url) {
  this.url = url
  var Agent = null
  if (/^https/.test(url)) {
    Agent = require('https').Agent
  } else {
    Agent = require('http').Agent
  }
  this.httpAgent = new Agent({maxSockets: MAX_CLIENT_SOCKETS})
}
var DiskBuffer = require('./DiskBuffer.js')

Logsene.prototype.diskBuffer = function (enabled, dir) {
  if (enabled) {
    var tmpDir = path.join((dir || require('os').tmpdir()), this.token)
    this.db = DiskBuffer.createDiskBuffer({
      tmpDir: tmpDir,
      maxStoredRequests: MAX_STORED_REQUESTS,
      interval: process.env.LOGSENE_DISK_BUFFER_INTERVAL || 120000
    })
    this.db.syncFileListFromDir()
    this.db.on('retransmit-req', function (event) {
      this.shipFile(event.fileName, event.buffer, function (err, res) {
        this.db.rmFile(event.fileName)
        this.db.retransmitNext()
      }.bind(this))
    }.bind(this))
  }
  this.persistence = enabled
}

/**
 * Add log message to send buffer
 * @param level - log level e.g. 'info', 'warning', 'error'
 * @param message - text message
 * @param fields - Object with custom fields or overwrite of any other field e.g. e.g. "{@timestamp: new Date.toISOString()}"
 * @param callback (err, msg object)
 */
Logsene.prototype.log = function (level, message, fields, callback) {
  var type = fields ? fields._type : this.type
  if (fields && fields._type) {
    delete fields._type
  }
  var msg = {'@timestamp': new Date(), message: message, severity: level, host: this.hostname, ip: ipAddress}
  for (var x in fields) {
    // rename fields for Elasticsearch 2.x
    msg[x.replace(/\./g, '_').replace(/^_+/, '')] = fields[x]
  }
  if (typeof msg['@timestamp'] === 'number') {
    msg['@timestamp'] = new Date(msg['@timestamp'])
  }
  this.emit('logged', {msg: msg})
  this.bulkReq.write(JSON.stringify({'index': {'_index': this.token, '_type': type || this.type}}) + '\n')
  this.bulkReq.write(stringifySafe(msg) + '\n')
  this.logCount++
  if (this.logCount === MAX_LOGS) {
    this.bulkReq.end()
    this.send()
  }
  if (callback) {
    callback(null, msg)
  }
}

/**
 * Sending log entry  to LOGSENE - this function is triggered every 100 log message or 30 seconds.
 * @callback {function} optional callback function
 */
Logsene.prototype.send = function (callback) {
  var self = this
  var count = this.logCount
  this.logCount = 0
  var options = {
    url: this.url,
    logCount: count,
    headers: {
      'User-Agent': 'logsene-js',
      'Content-Type': 'application/json',
      'Connection': 'Close'
    },
    body: this.bulkReq.getContents(),
    agent: self.httpAgent,
    method: 'POST'
  }
  this.bulkReq = null
  this.bulkReq = new streamBuffers.WritableStreamBuffer({
    initialSize: initialBufferSize,
    incrementAmount: incrementBuffer
  })
  if (options.body === false) {
    return
  }
  var req = request.post(options, function (err, res) {
    if (err) {
      self.emit('error', {source: 'logsene', err: err})
      if (self.persistence) {
        options.agent = false
        self.db.store({options: options}, function () {
          delete options.body
        })
        return
      }
      req.destroy()
    } else {
      self.emit('log', {source: 'logsene', count: count})
      if (callback) {
        callback(null, res)
      }
      delete options.body
      req.destroy()
    }
  })
}

Logsene.prototype.shipFile = function (name, data, cb) {
  var self = this
  var options = JSON.parse(data)
  options.url = self.url
  options.agent = self.httpAgent
  var req = request.post(options, function (err, res) {
    if (cb) {
      cb(err, res)
    }
    if (err) {
      self.emit('error', {source: 'logsene', err: err})
      if (self.persistence) {
        options.agent = false
        self.db.store({options: options}, function () {
          delete options.body
        })
      }
    } else {
      self.emit('file shipped', {file: name, count: options.count})
      self.emit('rt', {count: options.count, source: 'logsene', file: name, url: String(options.url), request: null, response: null})
    }
    req.destroy()
  })
}

module.exports = Logsene
<|endoftext|>


<commit_before>/* jshint node: true */
/* global window: false */
/* global document: false */
/* global location: false */
/* global CustomEvent: false */
/* global io: false */
'use strict';

var async = require('async');
var url = require('url');
var eve = require('eve');
var qsa = require('fdom/qsa');
var on = require('fdom/on');
var extend = require('cog/extend');
var defaults = require('cog/defaults');
var logger = require('cog/logger');
var debug = logger('glue');
var signaller = require('rtc-signaller');
var media = require('rtc-media');
var captureConfig = require('rtc-captureconfig');
var transform = require('sdp-transform');
var resetEl = require('rtc-core/reset');
// var liner = require('sdp-lines');

var reSep = /[\s\,]\s*/;
var reTrailingSlash = /\/$/;
var canGetSources = typeof MediaStreamTrack != 'undefined' &&
  MediaStreamTrack.getSources;

// initialise our config (using rtc- named metadata tags)
var config = defaults({}, require('fdom/meta')(/^rtc-(.*)$/), {
  room: location.hash.slice(1),
  signalhost: location.origin || 'http://rtc.io/switchboard/'
});

var SessionManager = require('./sessionmanager');
var sessionMgr;
var sources;

/**
  # rtc-glue

  Glue is a high-level approach to building WebRTC applications. It is
  primarily designed for web application coders who would prefer to spend
  their time in HTML and CSS rather than JS.

  ## Example Usage

  Glue works by looking for HTML tags that follow particular conventions
  with regards to named attributed, etc.  For instance, consider the
  following HTML:

  <<< examples/capture-only.html

  It is then possible to tweak the `getUserMedia` constraints using some
  flags in the `rtc-capture` attribute:

  <<< examples/capture-tweakres.html

  For those who prefer using separate attributes, you can achieve similar
  behaviour using the `rtc-resolution` (or `rtc-res`) attribute:

  <<< examples/res-attribute.html

  ## Conferencing Example

  The following is a simple example of conferencing using some hosted rtc.io
  signalling:

  <<< examples/conference-simple.html

  ## Getting Glue

  Primarily glue is designed for use in a standalone situation, and thus
  comes pre-packaged in a UMDjs
  [distribution](https://github.com/rtc-io/rtc-glue/tree/master/dist). If
  you prefer working with browserify, then it will still work quite nicely
  and you should just `npm install rtc-glue` like you would with other
  modules of the rtc.io suite.

  ## Running the Examples

  This module of the [rtc.io](https://rtc.io/) suite is a little different
  to others in that it comes with a ready to run js file.  Simply start
  a webserver in the root of the directory after cloning.  If you are looking
  for a good one, I'd recommend [st](https://github.com/isaacs/st).

  ## Targeted Media Capture

  The draft
  [Media Capture spec](http://dev.w3.org/2011/webrtc/editor/getusermedia.html)
  introduces the ability to query media devices on the machine.  This is
  currently available through the `MediaStreamTrack.getSources` function.

  If available then you can target the capture of a particular input device
  through the use of a numbered device capture specification.  For example:

  ```html
  <video rtc-capture="camera:1"></video>
  ```

  Would atttempt to capture the 2nd (0-indexed) camera available on the
  machine (if it is able to query devices).  The following is a larger
  example:

  <<< examples/capture-multicam.html

  ## On Custom Attributes

  While we haven't 100% decided we are leaning towards the use of custom
  `rtc-*` attributes for influencing the behaviour of the `rtc-glue` library.
  While currently this is in violation with the HTML5 spec, it is an area
  of active discussion in W3C land (given [AngularJS](http://angularjs.org/)
  has adopted the `ng-*` attributes and is proving popular).

  ### Document Metadata

  In the `rtc-glue` library we use document level `<meta>` tags to provide
  glue with configuration information.  There are a number of configurable
  options, each which is used in the form of:

  ```html
  <meta name="rtc-%flagname%" content="config content" />
  ```

  #### rtc-room

  A custom room that new conversations will be created in.  If not specified
  this will default to a value of `auto`.

  #### rtc-role

  In some conference scenarios, different participants are assigned different
  roles (e.g. student/teacher, consultant/customer, etc).  By specifying the
  `rtc-role` metadata you this role information will be announced as part
  of the `rtc-quickconnect` initialization.

  ## Reference

  ### Element Attributes

  #### rtc-capture

  The presence of the `rtc-capture` attribute in a `video` or `audio` element
  indicates that it is a getUserMedia capture target.

  #### rtc-peer

  To be completed.

**/
var glue = module.exports = function(scope, opts) {
  var startupOps = [];
  var debugTarget;

  // initialise the remote elements
  var peers = qsa('*[rtc-peer]', scope).map(initPeer);

  // if we have peers, then we are going to need primus
  if (peers.length > 0) {
    startupOps.push(loadPrimus);
  }

  // apply any external opts to the configuration
  extend(config, opts);

  // determine if we are debugging
  debugTarget = (config || {}).debug;
  if (debugTarget) {
    if (debugTarget === true) {
      logger.enable('*');
    }
    else if (Array.isArray(debugTarget)) {
      logger.enable.apply(logger, debugTarget);
    }
    else {
      logger.enable(debugTarget);
    }
  }

  // run the startup operations
  async.parallel(startupOps, function(err) {
    // TODO: check errors
    debug('startup ops completed, starting glue', config);
    eve('glue.ready');

    // if we don't have a room name, generate a room name
    if (! config.room) {
      config.room = generateRoomName();
    }

    // create the session manager
    sessionMgr = typeof Primus != 'undefined' && new SessionManager(config);

    if (sessionMgr) {
      sessionMgr.once('active', function() {
        qsa('*[rtc-capture]', scope).forEach(initCapture);

        // if we have any peers, then announce ourselves via the session manager
        if (peers.length > 0) {
          sessionMgr.announce();
        }

        // trigger a glue session active event
        eve('glue.connected', null, sessionMgr.signaller, sessionMgr);
      });
    }
    else {
      qsa('*[rtc-capture]', scope).forEach(initCapture);
    }
  });
};

// wire in the events helper
glue.events = require('./events');

// expose the config through glue
glue.config = config;

// autoload glue
if (typeof window != 'undefined') {
  on('load', window, function() {
    // check if we can autoload
    if (config.autoload === undefined || config.autoload) {
      glue();
    }
  });
}

/**
  ### Internal Functions
**/

/**
  #### initPeer(el)

  Handle the initialization of a rtc-remote target
**/
function initPeer(el) {
  var propValue = el.getAttribute('rtc-peer');
  var targetStream = el.getAttribute('rtc-stream');
  var peerRoles = propValue ? propValue.split(reSep) : ['*'];

  // create a data container that we will attach to the element
  var data = el._rtc || (el._rtc = {});

  function attachStream(stream) {
    debug('attaching stream');
    media(stream).render(el);
    data.streamId = stream.id;
  }

  function addStream(stream, peer) {
    // if we don't have a stream or already have a stream id then bail
    if (data.streamId) {
      return;
    }

    // if we have a particular target stream, then go looking for it
    if (targetStream) {
      debug('requesting stream data');
      sessionMgr.getStreamData(stream, function(data) {
        debug('got stream data', data);

        // if it's a match, then attach
        if (data && data.name === targetStream) {
          attachStream(stream);
        }
      });
    }
    // otherwise, automatically associate with the element
    else {
      attachStream(stream);
    }
  }

  // iterate through the peers and monitor events for that peer
  peerRoles.forEach(function(role) {
    eve.on('glue.peer.active.' + role, function(peer, peerId) {
      // if the element already has a peer, then do nothing
      if (data.peerId) {
        return;
      }

      debug('peer active', peer.getRemoteStreams());

      // associate the peer id with the element
      data.peerId = peerId;

      // add existing streams
      [].slice.call(peer.getRemoteStreams()).forEach(addStream);

      // listen for add straem events
      peer.addEventListener('addstream', function(evt) {
        addStream(evt.stream, peer);
      });
    });
  });

  eve.on('glue.peer.leave', function(peer, peerId) {
    // if the peer leaving matches the remote peer, then cleanup
    if (data.peerId === peerId) {
      // reset the target media element
      resetEl(el);

      // reset the rtc data
      data = el._rtc = {};
    }
  });

  return el;
}

/**
  #### initCapture(el)

  Handle the initialization of an rtc-capture target
**/
function initCapture(el) {
  // read the capture instructions
  var configText = el.getAttribute('rtc-capture') || '';
  var res = el.getAttribute('rtc-resolution') || el.getAttribute('rtc-res');
  var fps = el.getAttribute('rtc-fps');

  if (res) {
    configText += ' min:' + res + ' max:' + res;
  }

  if (fps) {
    configText += ' minfps:' + fps + ' maxfps:' + fps;
  }

  // patch in a capture method to the element
  el.capture = enableCapture(el, captureConfig(configText));

  // trigger capture
  el.capture(function(stream) {
    // broadcast the stream through the session manager
    if (sessionMgr) {
      sessionMgr.broadcast(stream, { name: el.id });
    }
  });
}

/** internal helpers */

function enableCapture(el, config) {

  function cap(callback) {
    var stream = media({
      constraints: config.toConstraints({
        sources: sources
      })
    });

    // render the stream to the target element
    stream.render(el);

    // capture and report errors
    stream.on('error', function(err) {
      console.log(
        'Error attempting to capture media, requested constraints',
        stream.constraints
      );
    });

    // emit a capture event through the element
    stream.on('capture', function(stream) {
      // dispatch the capture event
      el.dispatchEvent(new CustomEvent('capture', {
        detail: { stream: stream }
      }));

      // trigger the callback if one supplied
      if (typeof callback == 'function') {
        callback(stream);
      }
    });
  }

  return function(callback) {
    // if we already have sources, or cannot get source information
    // then skip straight to capture
    if (sources || (! canGetSources)) {
      return cap(callback);
    }

    // get and update sources
    MediaStreamTrack.getSources(function(s) {
      // update the sources
      sources = s;

      // capture
      cap(callback)
    });
  };
}

function generateRoomName() {
  location.hash = Math.pow(2, 53) * Math.random();

  return location.hash.slice(1);
}

function loadPrimus(callback) {
  return signaller.loadPrimus(config.signalhost, callback);
}<commit_msg>Provide the session manager with the number of capture tags found<commit_after>/* jshint node: true */
/* global window: false */
/* global document: false */
/* global location: false */
/* global CustomEvent: false */
/* global io: false */
'use strict';

var async = require('async');
var url = require('url');
var eve = require('eve');
var qsa = require('fdom/qsa');
var on = require('fdom/on');
var extend = require('cog/extend');
var defaults = require('cog/defaults');
var logger = require('cog/logger');
var debug = logger('glue');
var signaller = require('rtc-signaller');
var media = require('rtc-media');
var captureConfig = require('rtc-captureconfig');
var transform = require('sdp-transform');
var resetEl = require('rtc-core/reset');
// var liner = require('sdp-lines');

var reSep = /[\s\,]\s*/;
var reTrailingSlash = /\/$/;
var canGetSources = typeof MediaStreamTrack != 'undefined' &&
  MediaStreamTrack.getSources;

// initialise our config (using rtc- named metadata tags)
var config = defaults({}, require('fdom/meta')(/^rtc-(.*)$/), {
  room: location.hash.slice(1),
  signalhost: location.origin || 'http://rtc.io/switchboard/'
});

var SessionManager = require('./sessionmanager');
var sessionMgr;
var sources;

logger.enable('*');

/**
  # rtc-glue

  Glue is a high-level approach to building WebRTC applications. It is
  primarily designed for web application coders who would prefer to spend
  their time in HTML and CSS rather than JS.

  ## Example Usage

  Glue works by looking for HTML tags that follow particular conventions
  with regards to named attributed, etc.  For instance, consider the
  following HTML:

  <<< examples/capture-only.html

  It is then possible to tweak the `getUserMedia` constraints using some
  flags in the `rtc-capture` attribute:

  <<< examples/capture-tweakres.html

  For those who prefer using separate attributes, you can achieve similar
  behaviour using the `rtc-resolution` (or `rtc-res`) attribute:

  <<< examples/res-attribute.html

  ## Conferencing Example

  The following is a simple example of conferencing using some hosted rtc.io
  signalling:

  <<< examples/conference-simple.html

  ## Getting Glue

  Primarily glue is designed for use in a standalone situation, and thus
  comes pre-packaged in a UMDjs
  [distribution](https://github.com/rtc-io/rtc-glue/tree/master/dist). If
  you prefer working with browserify, then it will still work quite nicely
  and you should just `npm install rtc-glue` like you would with other
  modules of the rtc.io suite.

  ## Running the Examples

  This module of the [rtc.io](https://rtc.io/) suite is a little different
  to others in that it comes with a ready to run js file.  Simply start
  a webserver in the root of the directory after cloning.  If you are looking
  for a good one, I'd recommend [st](https://github.com/isaacs/st).

  ## Targeted Media Capture

  The draft
  [Media Capture spec](http://dev.w3.org/2011/webrtc/editor/getusermedia.html)
  introduces the ability to query media devices on the machine.  This is
  currently available through the `MediaStreamTrack.getSources` function.

  If available then you can target the capture of a particular input device
  through the use of a numbered device capture specification.  For example:

  ```html
  <video rtc-capture="camera:1"></video>
  ```

  Would atttempt to capture the 2nd (0-indexed) camera available on the
  machine (if it is able to query devices).  The following is a larger
  example:

  <<< examples/capture-multicam.html

  ## On Custom Attributes

  While we haven't 100% decided we are leaning towards the use of custom
  `rtc-*` attributes for influencing the behaviour of the `rtc-glue` library.
  While currently this is in violation with the HTML5 spec, it is an area
  of active discussion in W3C land (given [AngularJS](http://angularjs.org/)
  has adopted the `ng-*` attributes and is proving popular).

  ### Document Metadata

  In the `rtc-glue` library we use document level `<meta>` tags to provide
  glue with configuration information.  There are a number of configurable
  options, each which is used in the form of:

  ```html
  <meta name="rtc-%flagname%" content="config content" />
  ```

  #### rtc-room

  A custom room that new conversations will be created in.  If not specified
  this will default to a value of `auto`.

  #### rtc-role

  In some conference scenarios, different participants are assigned different
  roles (e.g. student/teacher, consultant/customer, etc).  By specifying the
  `rtc-role` metadata you this role information will be announced as part
  of the `rtc-quickconnect` initialization.

  ## Reference

  ### Element Attributes

  #### rtc-capture

  The presence of the `rtc-capture` attribute in a `video` or `audio` element
  indicates that it is a getUserMedia capture target.

  #### rtc-peer

  To be completed.

**/
var glue = module.exports = function(scope, opts) {
  var startupOps = [];
  var debugTarget;

  // initialise the remote elements
  var peers = qsa('*[rtc-peer]', scope).map(initPeer);

  // if we have peers, then we are going to need primus
  if (peers.length > 0) {
    startupOps.push(loadPrimus);
  }

  // apply any external opts to the configuration
  extend(config, opts);

  // determine if we are debugging
  debugTarget = (config || {}).debug;
  if (debugTarget) {
    if (debugTarget === true) {
      logger.enable('*');
    }
    else if (Array.isArray(debugTarget)) {
      logger.enable.apply(logger, debugTarget);
    }
    else {
      logger.enable(debugTarget);
    }
  }

  // run the startup operations
  async.parallel(startupOps, function(err) {
    var captureTags = qsa('*[rtc-capture]', scope);

    // TODO: check errors
    debug('startup ops completed, starting glue', config);
    eve('glue.ready');

    // if we don't have a room name, generate a room name
    if (! config.room) {
      config.room = generateRoomName();
    }

    // create the session manager
    sessionMgr = typeof Primus != 'undefined' && new SessionManager(config);

    if (sessionMgr) {
      // tell the session manager how many capture sources we have
      sessionMgr.streamCount = captureTags.length;

      // wait until active
      sessionMgr.once('active', function() {
        captureTags.forEach(initCapture);

        // if we have any peers, then announce ourselves via the session manager
        if (peers.length > 0) {
          sessionMgr.announce();
        }

        // trigger a glue session active event
        eve('glue.connected', null, sessionMgr.signaller, sessionMgr);
      });
    }
    else {
      captureTags.forEach(initCapture);
    }
  });
};

// wire in the events helper
glue.events = require('./events');

// expose the config through glue
glue.config = config;

// autoload glue
if (typeof window != 'undefined') {
  on('load', window, function() {
    // check if we can autoload
    if (config.autoload === undefined || config.autoload) {
      glue();
    }
  });
}

/**
  ### Internal Functions
**/

/**
  #### initPeer(el)

  Handle the initialization of a rtc-remote target
**/
function initPeer(el) {
  var propValue = el.getAttribute('rtc-peer');
  var targetStream = el.getAttribute('rtc-stream');
  var peerRoles = propValue ? propValue.split(reSep) : ['*'];

  // create a data container that we will attach to the element
  var data = el._rtc || (el._rtc = {});

  function attachStream(stream) {
    debug('attaching stream');
    media(stream).render(el);
    data.streamId = stream.id;
  }

  function addStream(stream, peer) {
    // if we don't have a stream or already have a stream id then bail
    if (data.streamId) {
      return;
    }

    // if we have a particular target stream, then go looking for it
    if (targetStream) {
      debug('requesting stream data');
      sessionMgr.getStreamData(stream, function(data) {
        debug('got stream data', data);

        // if it's a match, then attach
        if (data && data.name === targetStream) {
          attachStream(stream);
        }
      });
    }
    // otherwise, automatically associate with the element
    else {
      attachStream(stream);
    }
  }

  // iterate through the peers and monitor events for that peer
  peerRoles.forEach(function(role) {
    eve.on('glue.peer.active.' + role, function(peer, peerId) {
      // if the element already has a peer, then do nothing
      if (data.peerId) {
        return;
      }

      debug('peer active', peer.getRemoteStreams());

      // associate the peer id with the element
      data.peerId = peerId;

      // add existing streams
      [].slice.call(peer.getRemoteStreams()).forEach(addStream);

      // listen for add stream events
      // NOTE: currently not in use as we have move to a non-reactive
      // coupling approach to ensure firefox compatibility
      // peer.addEventListener('addstream', function(evt) {
      //   addStream(evt.stream, peer);
      // });
    });
  });

  eve.on('glue.peer.leave', function(peer, peerId) {
    // if the peer leaving matches the remote peer, then cleanup
    if (data.peerId === peerId) {
      // reset the target media element
      resetEl(el);

      // reset the rtc data
      data = el._rtc = {};
    }
  });

  return el;
}

/**
  #### initCapture(el)

  Handle the initialization of an rtc-capture target
**/
function initCapture(el) {
  // read the capture instructions
  var configText = el.getAttribute('rtc-capture') || '';
  var res = el.getAttribute('rtc-resolution') || el.getAttribute('rtc-res');
  var fps = el.getAttribute('rtc-fps');

  if (res) {
    configText += ' min:' + res + ' max:' + res;
  }

  if (fps) {
    configText += ' minfps:' + fps + ' maxfps:' + fps;
  }

  // patch in a capture method to the element
  el.capture = enableCapture(el, captureConfig(configText));

  // trigger capture
  el.capture(function(stream) {
    // broadcast the stream through the session manager
    if (sessionMgr) {
      sessionMgr.broadcast(stream, { name: el.id });
    }
  });
}

/** internal helpers */

function enableCapture(el, config) {

  function cap(callback) {
    var stream = media({
      constraints: config.toConstraints({
        sources: sources
      })
    });

    // render the stream to the target element
    stream.render(el);

    // capture and report errors
    stream.on('error', function(err) {
      console.log(
        'Error attempting to capture media, requested constraints',
        stream.constraints
      );
    });

    // emit a capture event through the element
    stream.on('capture', function(stream) {
      // dispatch the capture event
      el.dispatchEvent(new CustomEvent('capture', {
        detail: { stream: stream }
      }));

      // trigger the callback if one supplied
      if (typeof callback == 'function') {
        callback(stream);
      }
    });
  }

  return function(callback) {
    // if we already have sources, or cannot get source information
    // then skip straight to capture
    if (sources || (! canGetSources)) {
      return cap(callback);
    }

    // get and update sources
    MediaStreamTrack.getSources(function(s) {
      // update the sources
      sources = s;

      // capture
      cap(callback)
    });
  };
}

function generateRoomName() {
  location.hash = Math.pow(2, 53) * Math.random();

  return location.hash.slice(1);
}

function loadPrimus(callback) {
  return signaller.loadPrimus(config.signalhost, callback);
}<|endoftext|>


<commit_before>/**
 *
 *
 *
 */

var port = process.env.PORT || 8080;
var basicauth = process.env.basicauth || 'nickolanack:nick';
console.log('Running bridge with custom http server: ' + port + ', and ' + basicauth + ' for server connections');
var http = require('http');

var rproxy = require('node-rproxy');
var Bridge = rproxy.Bridge;
var TinyServer = require('tinywebjs');

var data = {};
var domains = [];

var getData = function() {

	return {
		'/': data,
		'domains': domains
	};

}

var bridge = new Bridge({
	server: (new TinyServer({
		port: port,
		documentRoot: __dirname + '/html/'
	}).addHandler('count', function(request, response) {

		response.end(JSON.stringify(getData()));

	})).server,
	basicauth: basicauth
});

rproxy.util.logBridgeProxy(bridge);

var clients = 0;
var servers = 0;
var paired = 0;
var closed = 0;
var buffers = 0;

var getDomain = function(ws) {

	var domain = ws.upgradeReq.url.toLowerCase();
	if (!domain) {
		domain = '/';
	}

	if (domains.indexOf(domain) < 0) {
		domains.push(domain);
	}

	return domain;

}

bridge.on('server.connect', function(ws) {
	servers++;

	getDomain(ws);

	updateData();
}).on('client.connect', function(ws) {

	getDomain(ws);

	clients++;
	updateData();
}).on('server.close', function() {
	servers--;
	updateData();
}).on('client.close', function() {
	clients--;
	updateData();
}).on('pair', function() {
	clients--;
	servers--;
	paired++;
	updateData();
}).on('unpair', function() {
	paired--;
	closed++
	updateData();
}).on('buffer.create', function() {
	buffers++;
	updateData();
}).on('buffer.close', function() {
	buffers--;
	updateData();
});

var updateData = function() {

	data = {
		'primed-server-conections': servers,
		'waiting-client-conections': clients,
		'active-bridges': paired,
		'closed-bridges': closed,
		'open-buffers': buffers
	}
}<commit_msg>manage domains<commit_after>/**
 *
 *
 *
 */

var port = process.env.PORT || 8080;
var basicauth = process.env.basicauth || 'nickolanack:nick';
console.log('Running bridge with custom http server: ' + port + ', and ' + basicauth + ' for server connections');
var http = require('http');

var rproxy = require('node-rproxy');
var Bridge = rproxy.Bridge;
var TinyServer = require('tinywebjs');

var data = {};
var domains = [];

var getData = function() {

	return {
		'/': data,
		'domains': domains
	};

}

var bridge = new Bridge({
	server: (new TinyServer({
		port: port,
		documentRoot: __dirname + '/html/'
	}).addHandler('count', function(request, response) {

		response.end(JSON.stringify(getData()));

	})).server,
	basicauth: basicauth
});

//rproxy.util.logBridgeProxy(bridge);

var clients = 0;
var servers = 0;
var paired = 0;
var closed = 0;
var buffers = 0;

var getDomain = function(ws) {

	var domain = ws.upgradeReq.url.toLowerCase();
	if (!domain) {
		domain = '/';
	}
	return domain;

}

var addDomain = function(ws) {

	var domain = getDomain(ws)

	if (domains.indexOf(domain) < 0) {
		domains.push(domain);
	}

	return domain;

}

var removeDomain = function(ws) {

	var domain = getDomain(ws)
	var i = domains.indexOf(domain);
	if (i >= 0) {
		domains.splice(i, 1);
	}

	return domain;

}

bridge.on('server.connect', function(ws) {
	servers++;

	addDomain(ws, true);

	updateData();
}).on('client.connect', function(ws) {

	getDomain(ws);

	clients++;
	updateData();
}).on('server.close', function(ws) {

	removeDomain(ws);

	servers--;
	updateData();

}).on('client.close', function() {
	clients--;
	updateData();
}).on('pair', function(server, client) {
	clients--;
	servers--;
	paired++;
	updateData();

	console.log('server:' + getDomain(server));
	console.log('client:' + getDomain(client));

}).on('unpair', function() {
	paired--;
	closed++
	updateData();
}).on('buffer.create', function() {
	buffers++;
	updateData();
}).on('buffer.close', function() {
	buffers--;
	updateData();
});

var updateData = function() {

	data = {
		'primed-server-conections': servers,
		'waiting-client-conections': clients,
		'active-bridges': paired,
		'closed-bridges': closed,
		'open-buffers': buffers
	}
}<|endoftext|>