<commit_before>var fs = require('fs')
var tmpdir = require('os').tmpdir();
var path = require('path')

var isWindows = process.platform === 'win32'
// These can be overridden for testing
var options = {
  isWindows: isWindows,
  canSymlink: testCanSymlink(),
  fs: fs
}

function testCanSymlink () {
  // We can't use options here because this function gets called before
  // its defined
  if (isWindows === false) { return true; }

  var canLinkSrc  = path.join(tmpdir, "canLinkSrc.tmp")
  var canLinkDest = path.join(tmpdir, "canLinkDest.tmp")

  try {
    fs.writeFileSync(canLinkSrc, '');
  } catch (e) {
    return false
  }

  try {
    fs.symlinkSync(canLinkSrc, canLinkDest)
  } catch (e) {
    fs.unlinkSync(canLinkSrc)
    return false
  }

  fs.unlinkSync(canLinkSrc)
  fs.unlinkSync(canLinkDest)

  return true
}

module.exports = symlinkOrCopy;
function symlinkOrCopy () {
  throw new Error("This function does not exist. Use require('symlink-or-copy').sync")
}

module.exports.setOptions = setOptions
function setOptions(newOptions) {
  options = newOptions
}

module.exports.sync = symlinkOrCopySync
function symlinkOrCopySync (srcPath, destPath) {
  if (options.isWindows) {
    symlinkWindows(srcPath, destPath)
  } else {
    symlink(srcPath, destPath)
  }
}

function symlink(srcPath, destPath) {
  var lstat = options.fs.lstatSync(srcPath)
  if (lstat.isSymbolicLink()) {
    // When we encounter symlinks, follow them. This prevents indirection
    // from growing out of control.
    // Note: At the moment `realpathSync` on Node is 70x slower than native,
    // because it doesn't use the standard library's `realpath`:
    // https://github.com/joyent/node/issues/7902
    // Can someone please send a patch to Node? :)
    srcPath = options.fs.realpathSync(srcPath)
  } else if (srcPath[0] !== '/') {
    // Resolve relative paths.
    // Note: On Mac and Linux (unlike Windows), process.cwd() never contains
    // symlink components, due to the way getcwd is implemented. As a
    // result, it's correct to use naive string concatenation in this code
    // path instead of the slower path.resolve(). (It seems unnecessary in
    // principle that path.resolve() is slower. Does anybody want to send a
    // patch to Node?)
    srcPath = process.cwd() + '/' + srcPath
  }
  options.fs.symlinkSync(srcPath, destPath);
}

function symlinkWindows(srcPath, destPath) {
  var stat = options.fs.lstatSync(srcPath)
  var isDir = stat.isDirectory()
  var wasResolved = false;

  if (stat.isSymbolicLink()) {
    srcPath = options.fs.realpathSync(srcPath);
    isDir = options.fs.lstatSync(srcPath).isDirectory();
    wasResolved = true;
  }

  // Instruct Win32 to suspend path parsing by prefixing the path with a \\?\.
  // Fix for https://github.com/broccolijs/broccoli-merge-trees/issues/42
  var WINDOWS_PREFIX = "\\\\?\\";
  srcPath = WINDOWS_PREFIX + (wasResolved ? srcPath : path.resolve(srcPath));
  destPath = WINDOWS_PREFIX + path.resolve(path.normalize(destPath));

  if (options.canSymlink) {
    options.fs.symlinkSync(srcPath, destPath, isDir ? 'dir' : 'file');
  } else {
    if (isDir) {
      options.fs.symlinkSync(srcPath, destPath, 'junction');
    } else {
      options.fs.writeFileSync(destPath, options.fs.readFileSync(srcPath), { flag: 'wx', mode: stat.mode })
      options.fs.utimesSync(destPath, stat.atime, stat.mtime)
    }
  }
}
<commit_msg>extract constant<commit_after>var fs = require('fs')
var tmpdir = require('os').tmpdir();
var path = require('path')

var isWindows = process.platform === 'win32'
// These can be overridden for testing
var options = {
  isWindows: isWindows,
  canSymlink: testCanSymlink(),
  fs: fs
}

function testCanSymlink () {
  // We can't use options here because this function gets called before
  // its defined
  if (isWindows === false) { return true; }

  var canLinkSrc  = path.join(tmpdir, "canLinkSrc.tmp")
  var canLinkDest = path.join(tmpdir, "canLinkDest.tmp")

  try {
    fs.writeFileSync(canLinkSrc, '');
  } catch (e) {
    return false
  }

  try {
    fs.symlinkSync(canLinkSrc, canLinkDest)
  } catch (e) {
    fs.unlinkSync(canLinkSrc)
    return false
  }

  fs.unlinkSync(canLinkSrc)
  fs.unlinkSync(canLinkDest)

  return true
}

module.exports = symlinkOrCopy;
function symlinkOrCopy () {
  throw new Error("This function does not exist. Use require('symlink-or-copy').sync")
}

module.exports.setOptions = setOptions
function setOptions(newOptions) {
  options = newOptions
}

module.exports.sync = symlinkOrCopySync
function symlinkOrCopySync (srcPath, destPath) {
  if (options.isWindows) {
    symlinkWindows(srcPath, destPath)
  } else {
    symlink(srcPath, destPath)
  }
}

function symlink(srcPath, destPath) {
  var lstat = options.fs.lstatSync(srcPath)
  if (lstat.isSymbolicLink()) {
    // When we encounter symlinks, follow them. This prevents indirection
    // from growing out of control.
    // Note: At the moment `realpathSync` on Node is 70x slower than native,
    // because it doesn't use the standard library's `realpath`:
    // https://github.com/joyent/node/issues/7902
    // Can someone please send a patch to Node? :)
    srcPath = options.fs.realpathSync(srcPath)
  } else if (srcPath[0] !== '/') {
    // Resolve relative paths.
    // Note: On Mac and Linux (unlike Windows), process.cwd() never contains
    // symlink components, due to the way getcwd is implemented. As a
    // result, it's correct to use naive string concatenation in this code
    // path instead of the slower path.resolve(). (It seems unnecessary in
    // principle that path.resolve() is slower. Does anybody want to send a
    // patch to Node?)
    srcPath = process.cwd() + '/' + srcPath
  }
  options.fs.symlinkSync(srcPath, destPath);
}

// Instruct Win32 to suspend path parsing by prefixing the path with a \\?\.
// Fix for https://github.com/broccolijs/broccoli-merge-trees/issues/42
var WINDOWS_PREFIX = "\\\\?\\";

function symlinkWindows(srcPath, destPath) {
  var stat = options.fs.lstatSync(srcPath)
  var isDir = stat.isDirectory()
  var wasResolved = false;

  if (stat.isSymbolicLink()) {
    srcPath = options.fs.realpathSync(srcPath);
    isDir = options.fs.lstatSync(srcPath).isDirectory();
    wasResolved = true;
  }

  srcPath = WINDOWS_PREFIX + (wasResolved ? srcPath : path.resolve(srcPath));
  destPath = WINDOWS_PREFIX + path.resolve(path.normalize(destPath));

  if (options.canSymlink) {
    options.fs.symlinkSync(srcPath, destPath, isDir ? 'dir' : 'file');
  } else {
    if (isDir) {
      options.fs.symlinkSync(srcPath, destPath, 'junction');
    } else {
      options.fs.writeFileSync(destPath, options.fs.readFileSync(srcPath), { flag: 'wx', mode: stat.mode })
      options.fs.utimesSync(destPath, stat.atime, stat.mtime)
    }
  }
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';
const merge = require('merge');
const fs = require('fs');
const path = require('path');
const Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ui-animate',
  included(app, parentAddon) {
      const target = (parentAddon || app);
      this._super.included(target);
      const addonConfig = this.addonConfig = app.project.config(app.env)['uiAnimate'] || {};
      const addonBuildConfig = app.options['uiAnimate'];
      let o = merge({ include: false }, addonConfig, addonBuildConfig);

      if (o.include) {
        target.import('ui-animate/source/_base.css');
        if(typeof o.include === 'string') {
          o.include = o.include.split(',');
        }
        if(o.includeType) {
          if(typeof o.includeType === 'string') {
            o.includeType = o.includeType.split(',');
          }
          o.includeType.forEach(type => {
            const files = fs.readdirSync(type);
            files.forEach(f => o.include.push(`${type}/${f}`));
          });
        }

        o.include.forEach(file => {
          target.import(`ui-animate/source/${file}`);
        });

      } else {
        // target.import(path.join(app.bowerDirectory, 'animate.css/animate.css'));
        target.import('ui-animate/animate.css');
      }
    },

    treeForVendor: function() {
      var pathToAnimateEntryScript = require.resolve('animate.css');
      var pathToAnimatePackageRoot = path.dirname(pathToAnimateEntryScript);
      var tree = this.treeGenerator(pathToAnimatePackageRoot);

      return new Funnel(tree, { destDir: 'ui-animate' });
    },
  };
<commit_msg>removed spurious comment<commit_after>/* jshint node: true */
'use strict';
const merge = require('merge');
const fs = require('fs');
const path = require('path');
const Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ui-animate',
  included(app, parentAddon) {
      const target = (parentAddon || app);
      this._super.included(target);
      const addonConfig = this.addonConfig = app.project.config(app.env)['uiAnimate'] || {};
      const addonBuildConfig = app.options['uiAnimate'];
      let o = merge({ include: false }, addonConfig, addonBuildConfig);

      if (o.include) {
        target.import('ui-animate/source/_base.css');
        if(typeof o.include === 'string') {
          o.include = o.include.split(',');
        }
        if(o.includeType) {
          if(typeof o.includeType === 'string') {
            o.includeType = o.includeType.split(',');
          }
          o.includeType.forEach(type => {
            const files = fs.readdirSync(type);
            files.forEach(f => o.include.push(`${type}/${f}`));
          });
        }

        o.include.forEach(file => {
          target.import(`ui-animate/source/${file}`);
        });

      } else {
        target.import('ui-animate/animate.css');
      }
    },

    treeForVendor: function() {
      var pathToAnimateEntryScript = require.resolve('animate.css');
      var pathToAnimatePackageRoot = path.dirname(pathToAnimateEntryScript);
      var tree = this.treeGenerator(pathToAnimatePackageRoot);

      return new Funnel(tree, { destDir: 'ui-animate' });
    },
  };
<|endoftext|>


<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 mine = require('mine');
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 || {};

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

    var entries = mains.map(function (file) {
        if (file && 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: [] };

    (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, 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 depRows = mine(src) }
            catch (ex) {
                var message = ex && ex.message ? ex.message : ex;
                return output.emit('error', new Error(
                    'Parsing file ' + file + ': ' + message
                ));
            }
            deps = depRows.map(function (d) { return d.name });
        }
        var p = deps.length;
        var current = { id: file, filename: file, 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') return cb(null, tr(file, trOpts));

        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>emit the transform event in the function case<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 mine = require('mine');
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 || {};

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

    var entries = mains.map(function (file) {
        if (file && 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: [] };

    (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, 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 depRows = mine(src) }
            catch (ex) {
                var message = ex && ex.message ? ex.message : ex;
                return output.emit('error', new Error(
                    'Parsing file ' + file + ': ' + message
                ));
            }
            deps = depRows.map(function (d) { return d.name });
        }
        var p = deps.length;
        var current = { id: file, filename: file, 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>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate = function (p, n) { // :: Point -> Int -> Point
    // record rotations
    if (p.n == 0) return new Point(this.z, this.x, this.y)
    if (p.n == 1 || p.n == 3) return new Point(this.y, this.z, this.x)
    if (p.n == 2 || p.n == 6) return new Point(n - this.x, n - this.y, this.z)
    return new Point(n - this.z, this.x, n - this.y)
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.rotateLeft = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.y, this.z, this.x)
    return new Point(this.z, this.x, this.y)
}

Point.prototype.rotateRight = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.z, this.x, this.y)
    return new Point(this.y, this.z, this.x)
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

Point.prototype.mod = function (n) { // :: Int -> Point
    return new Point(this.x % n, this.y % n, this.z % n)
}

Point.prototype.unrotate = function (n) {
    // read this.rotations and undo
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) {
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1, x, dim)
}

function entrySequence (i) {
    if (i) {
        return grayCode(2 * Math.floor((i-1) / 2))
    }
    return 0
}

function directionSequence(i, dim) {
    if (i == 0) return 0
    if (i % 2 == 0) return trailingSetBits(i - 1) % dim
    return trailingSetBits(i) % dim
}

function trailingSetBits (i) {
    var ones = ~i & (i + 1)
    return Math.log(ones) / Math.log(2)
}

function hilbertIndex(dim, point) {
    var index = 0, entry = 0, direction = 0, arr = point.toArray(), code,
        i = precision(Math.max.apply(null, arr)) - 1
    while (i >= 0) {
        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < arr.length; k++) {
            if (arr[arr.length - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1)
        direction = (direction + directionSequence(code, dim) + 1) % dim
        index = (index << dim) | code

        console.log('bits: ' + bits)
        console.log('entry: ' + entry)
        console.log('direction: ' + direction)
        console.log('code: ' + code)
        console.log('index: ' + index + '\n')

        i--
    }

    return index
}

function hilbertIndexInverse(dim, index) {
    var entry = 0, direction = 0, m = precision(index)
    var p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf,0);

    for (var i = m - 1; i >= 0; i--) {

        var mask = 1 << (i * dim), bits = 0, code

        for (var k = dim - 1; k >= 0; k--) {
            if (index & (mask << k)) {
                bits |= (mask << k)
            }
        }

        code = grayInverseTransform(entry, direction, grayCode(bits), dim)

        for (var k = 0; k < dim; k++) {
            if (code & (1 << k)) {
                p[k] |= (1 << i)
            }
        }

        entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
        direction = (direction + directionSequence(bits, dim) + 1) % dim
    }

    return p
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = function (dim, x, y, z) {
    return hilbertIndex(dim, new Point(x, y, z))
}
exports.hilbertInverse = function (dim, index) {
    return hilbertIndexInverse(dim, index)
}

exports.grayInverse = grayInverse
exports.grayCode = grayCode
<commit_msg>Fix inverse.<commit_after>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate = function (p, n) { // :: Point -> Int -> Point
    // record rotations
    if (p.n == 0) return new Point(this.z, this.x, this.y)
    if (p.n == 1 || p.n == 3) return new Point(this.y, this.z, this.x)
    if (p.n == 2 || p.n == 6) return new Point(n - this.x, n - this.y, this.z)
    return new Point(n - this.z, this.x, n - this.y)
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.rotateLeft = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.y, this.z, this.x)
    return new Point(this.z, this.x, this.y)
}

Point.prototype.rotateRight = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.z, this.x, this.y)
    return new Point(this.y, this.z, this.x)
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

Point.prototype.mod = function (n) { // :: Int -> Point
    return new Point(this.x % n, this.y % n, this.z % n)
}

Point.prototype.unrotate = function (n) {
    // read this.rotations and undo
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) {
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1, x, dim)
}

function entrySequence (i) {
    if (i) {
        return grayCode(2 * Math.floor((i-1) / 2))
    }
    return 0
}

function directionSequence(i, dim) {
    if (i == 0) return 0
    if (i % 2 == 0) return trailingSetBits(i - 1) % dim
    return trailingSetBits(i) % dim
}

function trailingSetBits (i) {
    var ones = ~i & (i + 1)
    return Math.log(ones) / Math.log(2)
}

function hilbertIndex(dim, point) {
    var index = 0, entry = 0, direction = 0, arr = point.toArray(), code,
        i = precision(Math.max.apply(null, arr)) - 1
    while (i >= 0) {
        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < arr.length; k++) {
            if (arr[arr.length - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1)
        direction = (direction + directionSequence(code, dim) + 1) % dim
        index = (index << dim) | code

        console.log('bits: ' + bits)
        console.log('entry: ' + entry)
        console.log('direction: ' + direction)
        console.log('code: ' + code)
        console.log('index: ' + index + '\n')

        i--
    }

    return index
}

function hilbertIndexInverse(dim, index) {
    var entry = 0, direction = 0, m = precision(index)
    var p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf,0);

    for (var i = m - 1; i >= 0; i--) {

        var mask = 1 << (i * dim), bits = 0, code

        for (var k = dim - 1; k >= 0; k--) {
            if (index & (mask << k)) {
                bits |= (1 << k)
            }
        }

        code = grayInverseTransform(entry, direction, grayCode(bits), dim)

        for (var k = 0; k < dim; k++) {
            if (code & (1 << k)) {
                p[k] |= (1 << i)
            }
        }

        entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
        direction = (direction + directionSequence(bits, dim) + 1) % dim
    }

    return p
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = function (dim, x, y, z) {
    return hilbertIndex(dim, new Point(x, y, z))
}
exports.hilbertInverse = function (dim, index) {
    return hilbertIndexInverse(dim, index)
}

exports.grayInverse = grayInverse
exports.grayCode = grayCode
<|endoftext|>


<commit_before>module.exports = function(features){
  var fc = {
    "type": "FeatureCollection",
    "features": features
  };

  return fc;
}<commit_msg>JSdocs.<commit_after>/**
 * Creates a {@link FeatureCollection}
 *
 * @module turf/featurecollection
 * @param {Feature[]} features
 * @returns {FeatureCollection} output
 * @example
 * var pt1 = turf.point(-75.343, 39.984, {name: 'Location A'})
 * var pt2 = turf.point(-75.833, 39.284, {name: 'Location B'})
 * var pt3 = turf.point(-75.534, 39.123, {name: 'Location C'})
 * var fc = turf.featurecollection([pt1, pt2, pt3])
 * console.log(fc)
 */
module.exports = function(features){
  var fc = {
    "type": "FeatureCollection",
    "features": features
  };

  return fc;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var redis = require('redis');
var slack = require('slack-notify')(process.env.SLACK_URL);

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

var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.SPOTIFY_CLIENT_ID,
  clientSecret: process.env.SPOTIFY_CLIENT_SECRET
});
var spotifyUser = process.env.SPOTIFY_USERNAME;
var spotifyPlaylistId = process.env.SPOTIFY_PLAYLIST;
var redisUrl = process.env.REDISTOGO_URL;
var runWebServer = process.env.VCAP_APP || false;

// ------------------
var lastDate;
var redisClient;

if (redisUrl) {
  var rtg = require('url').parse(redisUrl);
  redisClient = redis.createClient(rtg.port, rtg.hostname);
  redisClient.auth(rtg.auth.split(":")[1]);

  redisClient.on('error', function (err) {
    console.log("Redis - Error " + err);
  });
  redisClient.get("lastDate", function(err, value) {
    if (!err) {
      lastDate = new Date(value);
    }
  });
} else {
  fs.readFile('./last_date.txt', {encoding: 'UTF-8'}, function(err, date){
     lastDate = date ? new Date(date) : void 0;
  });
}

var start = false;
function grantClient() {
  spotifyApi.clientCredentialsGrant()
    .then(function(data) {
      console.log('Spotify - got new access token, valid for', data.body.expires_in, 'seconds');

      spotifyApi.setAccessToken(data.body.access_token);
      start = true;

      setTimeout(grantClient, data.body.expires_in*1000);
    }, function(err) {
      console.log('Spotify - Error retrieving an access token using:', process.env.SPOTIFY_CLIENT_SECRET, err);
      process.exit(1);
    });
}

function writeLastDate(date) {
  lastDate = date

  if (redisUrl) {
      redisClient.set('lastDate', date);
  } else {
     fs.writeFile('./last_date.txt', date, function() {});
  }
}

var playlistName;
var playlistUrl;
function fetchPlaylistInfo() {
  if (!start) {
    setTimeout(fetchPlaylistInfo, 1000);
  }
  console.log('Spotify - Fetch playlist info');
  spotifyApi.getPlaylist(spotifyUser, spotifyPlaylistId, {fields: 'name,external_urls.spotify'})
    .then(function(data) {
      playlistName = data.body.name;
      playlistUrl = data.body.external_urls.spotify;
      console.log('Spotify - Playlist:', playlistName, "at", playlistUrl);
    }, function(err) {
      console.log('Spotify - Error retrieving playlist info:', err);
    });
}

function fetchPlaylistTracks(offset) {
  if (!start || playlistUrl === undefined) {
    return;
  }

  if (offset === undefined) {
    offset = 0;
  }

  console.log('Playlist last known song added at:', lastDate);

  spotifyApi.getPlaylistTracks(spotifyUser, spotifyPlaylistId, { offset: offset,
      fields: 'total,items(added_by.id,added_at,track(name,artists.name,album.name))'})
    .then(function(data) {
      console.log('Spotify - Fetched playlist with offset:', offset, "and got", data.body.total);
      var date = 0;
      for (var i in data.body.items) {
        date = new Date(data.body.items[i].added_at);
        if((lastDate === undefined) || (date > lastDate)) {
          post(playlistName, playlistUrl,
            data.body.items[i].added_by ? data.body.items[i].added_by.id : 'Unknown',
            data.body.items[i].track.name,
            data.body.items[i].track.artists);
        }
      }
      if((lastDate === undefined) || (date > lastDate)) {
        console.log('Spotify - last date in playlist', date);
        writeLastDate(date);
      }
      console.log("total ", total, "comp", offset+100)
      if(data.body.total >= (offset + 100)) {
        console.log("run again with ", offset+100)
        fetchPlaylistTracks(offset + 100)
      }
    }, function(err) {
      console.log('Spotify - Error retrieving playlist:', err);
    });
}

slack.onError = function (err) {
  console.log('Slack - Error:', err);
};

var slacker = slack.extend({
  username: 'spotify-playlist',
  icon_url: 'http://icons.iconarchive.com/icons/xenatt/the-circle/256/App-Spotify-icon.png',
  unfurl_media : false
});

function post(list_name, list_url, added_by, trackname, artists) {
  var text = 'New track added by ' + added_by + ' - *' + trackname+'* with '+artists[0].name+' in list <'+list_url+'|'+list_name+'>';
  console.log(text);
  slacker({text: text});
}

function startWebServer() {
  var http = require('http');
  var host = process.env.VCAP_APP_HOST || 'localhost';
  var port = process.env.VCAP_APP_PORT || 1337

  http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('No functions and features at this place...' + process.version);
  }).listen(port, null);

  console.log('Server running to provide incoming network connetion for Bluemix at http://' + host + ':' + port + '/');

  // set the current date as the initial date to avoid writing the whole song history to the slack channel
  now = new Date();
  writeLastDate(now);
}

if(runWebServer) {
  startWebServer();
}
grantClient();
setTimeout(fetchPlaylistInfo, 1000);
setInterval(fetchPlaylistTracks, 1000 * 10);
<commit_msg>Fix body element<commit_after>var fs = require('fs');
var redis = require('redis');
var slack = require('slack-notify')(process.env.SLACK_URL);

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

var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.SPOTIFY_CLIENT_ID,
  clientSecret: process.env.SPOTIFY_CLIENT_SECRET
});
var spotifyUser = process.env.SPOTIFY_USERNAME;
var spotifyPlaylistId = process.env.SPOTIFY_PLAYLIST;
var redisUrl = process.env.REDISTOGO_URL;
var runWebServer = process.env.VCAP_APP || false;

// ------------------
var lastDate;
var redisClient;

if (redisUrl) {
  var rtg = require('url').parse(redisUrl);
  redisClient = redis.createClient(rtg.port, rtg.hostname);
  redisClient.auth(rtg.auth.split(":")[1]);

  redisClient.on('error', function (err) {
    console.log("Redis - Error " + err);
  });
  redisClient.get("lastDate", function(err, value) {
    if (!err) {
      lastDate = new Date(value);
    }
  });
} else {
  fs.readFile('./last_date.txt', {encoding: 'UTF-8'}, function(err, date){
     lastDate = date ? new Date(date) : void 0;
  });
}

var start = false;
function grantClient() {
  spotifyApi.clientCredentialsGrant()
    .then(function(data) {
      console.log('Spotify - got new access token, valid for', data.body.expires_in, 'seconds');

      spotifyApi.setAccessToken(data.body.access_token);
      start = true;

      setTimeout(grantClient, data.body.expires_in*1000);
    }, function(err) {
      console.log('Spotify - Error retrieving an access token using:', process.env.SPOTIFY_CLIENT_SECRET, err);
      process.exit(1);
    });
}

function writeLastDate(date) {
  lastDate = date

  if (redisUrl) {
      redisClient.set('lastDate', date);
  } else {
     fs.writeFile('./last_date.txt', date, function() {});
  }
}

var playlistName;
var playlistUrl;
function fetchPlaylistInfo() {
  if (!start) {
    setTimeout(fetchPlaylistInfo, 1000);
  }
  console.log('Spotify - Fetch playlist info');
  spotifyApi.getPlaylist(spotifyUser, spotifyPlaylistId, {fields: 'name,external_urls.spotify'})
    .then(function(data) {
      playlistName = data.body.name;
      playlistUrl = data.body.external_urls.spotify;
      console.log('Spotify - Playlist:', playlistName, "at", playlistUrl);
    }, function(err) {
      console.log('Spotify - Error retrieving playlist info:', err);
    });
}

function fetchPlaylistTracks(offset) {
  if (!start || playlistUrl === undefined) {
    return;
  }

  if (offset === undefined) {
    offset = 0;
  }

  console.log('Playlist last known song added at:', lastDate);

  spotifyApi.getPlaylistTracks(spotifyUser, spotifyPlaylistId, { offset: offset,
      fields: 'total,items(added_by.id,added_at,track(name,artists.name,album.name))'})
    .then(function(data) {
      console.log('Spotify - Fetched playlist with offset:', offset, "and got", data.body.total);
      console.log(data.body);
      var date = 0;
      for (var i in data.body.items) {
        date = new Date(data.body.items[i].added_at);
        if((lastDate === undefined) || (date > lastDate)) {
          post(playlistName, playlistUrl,
            data.body.items[i].added_by ? data.body.items[i].added_by.id : 'Unknown',
            data.body.items[i].track.name,
            data.body.items[i].track.artists);
        }
      }
      if((lastDate === undefined) || (date > lastDate)) {
        console.log('Spotify - last date in playlist', date);
        writeLastDate(date);
      }
      if(data.body.total >= (offset + 100)) {
        fetchPlaylistTracks(offset + 100)
      }
    }, function(err) {
      console.log('Spotify - Error retrieving playlist:', err);
    });
}

slack.onError = function (err) {
  console.log('Slack - Error:', err);
};

var slacker = slack.extend({
  username: 'spotify-playlist',
  icon_url: 'http://icons.iconarchive.com/icons/xenatt/the-circle/256/App-Spotify-icon.png',
  unfurl_media : false
});

function post(list_name, list_url, added_by, trackname, artists) {
  var text = 'New track added by ' + added_by + ' - *' + trackname+'* with '+artists[0].name+' in list <'+list_url+'|'+list_name+'>';
  console.log(text);
  slacker({text: text});
}

function startWebServer() {
  var http = require('http');
  var host = process.env.VCAP_APP_HOST || 'localhost';
  var port = process.env.VCAP_APP_PORT || 1337

  http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('No functions and features at this place...' + process.version);
  }).listen(port, null);

  console.log('Server running to provide incoming network connetion for Bluemix at http://' + host + ':' + port + '/');

  // set the current date as the initial date to avoid writing the whole song history to the slack channel
  now = new Date();
  writeLastDate(now);
}

if(runWebServer) {
  startWebServer();
}
grantClient();
setTimeout(fetchPlaylistInfo, 1000);
setInterval(fetchPlaylistTracks, 1000 * 10);
<|endoftext|>


<commit_before>var render = require('./lib/render');
var state = require('./lib/state');
var events = require('./lib/events');
var defaulOptions = {
    render: {
        tmpl: "layout",
        title: "",
        position: "beforeend",
        clearList: true,
        leaveKeys: false,
        dontEscape: false,
        dontPrevent: false
    }
};

exports.state = state;

function renderDefOptions (options, data) {

    var renderOptions = {};

    for (var option in defaulOptions.render) {
        renderOptions[option] = options[option] || defaulOptions.render[option];
    }

    return renderOptions;
}

/**
 * Render data to the HTML template.
 *
 * @public
 * @param {object} The event object.
 * @param {object} The data object.
*/
exports.render = function (_options, data, next) {

    // TODO look also in data for render configs?
    var options = renderDefOptions(_options);

    // the template must exist
    var template = (this._config.templates || {})[options.tmpl];
    if (!template) {
        return next(new Error('View.render: Template "' + options.tmpl + '" not found.'));
    }

    // set streams cache
    template.streams = template.streams || {};

    // set document title
    if (template.title) {
        document.title = template.title;
    }

    if (typeof template.render !== 'function') {

        if (!this._markups[template.html]) {
            return next(new Error('View.render: Markup "' + template.html + '" not found.'));
        }

        template.render = render.create(this._markups[template.html]);
    }

    // create html
    template.html = template.render(data, options, render.escFn);

    // get dom parent
    if (typeof template.to === 'string') {
        template.to = document.querySelector(template.to);
    }

    // render html
    if (template.to) {

        // clear html before appending
        if (options.clearList) {
            template.to.innerHTML = '';
        }

        // append dom events
        if (!template.events) {
            template.to.insertAdjacentHTML(options.position, template.html);

        } else {
            var tmpElm = document.createElement(template.to.tagName);
            tmpElm.innerHTML = template.html;

            // setup flow streams
            events(this, template, options, tmpElm, data);

            Array.from(tmpElm.children).forEach(function (elm) {
                template.to.appendChild(elm);
            });
        }
    }

    next(null, data);
}
<commit_msg>reset template DOM target on removal<commit_after>var render = require('./lib/render');
var state = require('./lib/state');
var events = require('./lib/events');
var defaulOptions = {
    render: {
        tmpl: "layout",
        title: "",
        position: "beforeend",
        clearList: true,
        leaveKeys: false,
        dontEscape: false,
        dontPrevent: false
    }
};

exports.state = state;

function renderDefOptions (options, data) {

    var renderOptions = {};

    for (var option in defaulOptions.render) {
        renderOptions[option] = options[option] || defaulOptions.render[option];
    }

    return renderOptions;
}

/**
 * Render data to the HTML template.
 *
 * @public
 * @param {object} The event object.
 * @param {object} The data object.
*/
exports.render = function (_options, data, next) {

    // TODO look also in data for render configs?
    var options = renderDefOptions(_options);

    // the template must exist
    var template = (this._config.templates || {})[options.tmpl];
    if (!template) {
        return next(new Error('View.render: Template "' + options.tmpl + '" not found.'));
    }

    // set streams cache
    template.streams = template.streams || {};

    // set document title
    if (template.title) {
        document.title = template.title;
    }

    // init template
    if (typeof template.render !== 'function') {

        if (!this._markups[template.html]) {
            return next(new Error('View.render: Markup "' + template.html + '" not found.'));
        }

        template.render = render.create(this._markups[template.html]);

        // reset target with selector if target is removed from the document
        template.sel = template.to;
        template.obs = new MutationObserver(function (event) {
            event = event[0];
            Object.keys(event.removedNodes).forEach(function (node) {
                node = event.removedNodes[node];

                // check if template target is under the removed nodes
                if (typeof template.to !== 'string' && node.isSameNode(template.to)) {
                    template.obs.disconnect();
                    template.to = template.sel;
                }
            });
        });
    }

    // create html
    template.html = template.render(data, options, render.escFn);

    // get dom parent
    if (typeof template.to === 'string') {
        template.to = document.querySelector(template.sel);
        template.obs.observe(template.to.parentNode, {childList: true});
    }

    // render html
    if (template.to) {

        // clear html before appending
        if (options.clearList) {
            template.to.innerHTML = '';
        }

        // append dom events
        if (!template.events) {
            template.to.insertAdjacentHTML(options.position, template.html);

        } else {
            var tmpElm = document.createElement(template.to.tagName);
            tmpElm.innerHTML = template.html;

            // setup flow streams
            events(this, template, options, tmpElm, data);

            Array.from(tmpElm.children).forEach(function (elm) {
                template.to.appendChild(elm);
            });
        }
    }

    next(null, data);
}
<|endoftext|>


<commit_before>"use strict";

var gettextParser = require("gettext-parser");
var fs = require("fs");

var DEFAULT_FUNCTION_NAMES = {
    gettext: ["msgid"],
    dgettext: ["domain", "msgid"],
    ngettext: ["msgid", "msgid_plural", "count"],
    dngettext: ["domain", "msgid", "msgid_plural", "count"],
    pgettext: ["msgctxt", "msgid"],
    dpgettext: ["domain", "msgctxt", "msgid"],
    npgettext: ["msgctxt", "msgid", "msgid_plural", "count"],
    dnpgettext: ["domain", "msgctxt", "msgid", "msgid_plural", "count"]
};

var DEFAULT_FILE_NAME = "gettext.po";

var DEFAULT_HEADERS = {
    "content-type": "text/plain; charset=UTF-8",
    "plural-forms": "nplurals = 2; plural = (n !== 1);"
};

exports.default = function(_ref) {
    var currentFileName;
    var data;
    var Plugin = _ref.Plugin;
    //var t = _ref.types;

    return new Plugin("babel-plugin-example", {visitor: {

            CallExpression(node, parent, scope, config) {

                var functionNames = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.functionNames || DEFAULT_FUNCTION_NAMES;

                var fileName = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.fileName || DEFAULT_FILE_NAME;

                var headers = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.headers || DEFAULT_HEADERS;

                if (fileName !== currentFileName) {
                    currentFileName = fileName;

                    data = {
                        charset: "UTF-8",

                        headers: headers,

                        translations: {
                            context: {
                            }
                        }
                    };

                    headers["plural-forms"] = headers["plural-forms"] || DEFAULT_HEADERS["plural-forms"];
                    headers["content-type"] = headers["content-type"] || DEFAULT_HEADERS["content-type"];
                }
                var defaultContext = data.translations.context;
                var nplurals = /nplurals ?= ?(\d)/.exec(headers["plural-forms"])[1];

                if (functionNames.hasOwnProperty(node.callee.name)
                        || node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {

                    var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name];
                    var translate = {};

                    var args = node.arguments;
                    for (var i = 0, l = args.length; i < l; i++) {
                        var name = functionName[i];

                        if (name && name !== "count" && name !== "domain") {
                            var arg = args[i];
                            var value = arg.value;

                            if (value) {
                                translate[name] = value;
                            }

                            if (name === "msgid_plural") {
                                translate.msgstr = [];
                                for (var p = 0; p < nplurals; p++) {
                                    translate.msgstr[p] = "";
                                }
                            }
                        }
                    }

                    var context = defaultContext;
                    var msgctxt = translate.msgctxt;
                    if (msgctxt) {
                        data.translations[msgctxt] = data.translations[msgctxt] || {};
                        context = data.translations[msgctxt];
                    }

                    context[translate.msgid] = translate;

                    var output = gettextParser.po.compile(data);
                    fs.writeFileSync(fileName, output);
                }
            }
        }
    });
};
<commit_msg>Un-ES6 this lib.<commit_after>"use strict";

var gettextParser = require("gettext-parser");
var fs = require("fs");

var DEFAULT_FUNCTION_NAMES = {
    gettext: ["msgid"],
    dgettext: ["domain", "msgid"],
    ngettext: ["msgid", "msgid_plural", "count"],
    dngettext: ["domain", "msgid", "msgid_plural", "count"],
    pgettext: ["msgctxt", "msgid"],
    dpgettext: ["domain", "msgctxt", "msgid"],
    npgettext: ["msgctxt", "msgid", "msgid_plural", "count"],
    dnpgettext: ["domain", "msgctxt", "msgid", "msgid_plural", "count"]
};

var DEFAULT_FILE_NAME = "gettext.po";

var DEFAULT_HEADERS = {
    "content-type": "text/plain; charset=UTF-8",
    "plural-forms": "nplurals = 2; plural = (n !== 1);"
};

exports.default = function(_ref) {
    var currentFileName;
    var data;
    var Plugin = _ref.Plugin;
    //var t = _ref.types;

    return new Plugin("babel-plugin-example", {visitor: {

            CallExpression: function(node, parent, scope, config) {

                var functionNames = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.functionNames || DEFAULT_FUNCTION_NAMES;

                var fileName = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.fileName || DEFAULT_FILE_NAME;

                var headers = config.opts && config.opts.extra && config.opts.extra.gettext
                        && config.opts.extra.gettext.headers || DEFAULT_HEADERS;

                if (fileName !== currentFileName) {
                    currentFileName = fileName;

                    data = {
                        charset: "UTF-8",

                        headers: headers,

                        translations: {
                            context: {
                            }
                        }
                    };

                    headers["plural-forms"] = headers["plural-forms"] || DEFAULT_HEADERS["plural-forms"];
                    headers["content-type"] = headers["content-type"] || DEFAULT_HEADERS["content-type"];
                }
                var defaultContext = data.translations.context;
                var nplurals = /nplurals ?= ?(\d)/.exec(headers["plural-forms"])[1];

                if (functionNames.hasOwnProperty(node.callee.name)
                        || node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {

                    var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name];
                    var translate = {};

                    var args = node.arguments;
                    for (var i = 0, l = args.length; i < l; i++) {
                        var name = functionName[i];

                        if (name && name !== "count" && name !== "domain") {
                            var arg = args[i];
                            var value = arg.value;

                            if (value) {
                                translate[name] = value;
                            }

                            if (name === "msgid_plural") {
                                translate.msgstr = [];
                                for (var p = 0; p < nplurals; p++) {
                                    translate.msgstr[p] = "";
                                }
                            }
                        }
                    }

                    var context = defaultContext;
                    var msgctxt = translate.msgctxt;
                    if (msgctxt) {
                        data.translations[msgctxt] = data.translations[msgctxt] || {};
                        context = data.translations[msgctxt];
                    }

                    context[translate.msgid] = translate;

                    var output = gettextParser.po.compile(data);
                    fs.writeFileSync(fileName, output);
                }
            }
        }
    });
};
<|endoftext|>


<commit_before>'use strict'

if(process.env.ENV === 'dev') delete process.versions['electron']

const fs            = require('fs')
const path          = require('path')
const electron      = require('electron')
const app           = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu          = electron.Menu
const ipcMain       = electron.ipcMain
const dialog        = electron.dialog
const ipfsd         = require('ipfsd-ctl')
const IpfsApi       = require('ipfs-api')
const Logger        = require('logplease')
const utils         = require('./src/utils')

const logger = Logger.create("Orbit.Index-Native")

const MODE = process.env.ENV ? process.env.ENV : 'debug'

const getUserHome = () => {
  return process.env[(process.platform !== 'win32') ? 'HOME' : 'USERPROFILE']
}

const getAppDataDirectory = () => {
  return process.platform !== 'win32'
    ? 'Library/Application Support/orbit-floodsub-ipfs-repo'
    : 'AppData\\Roaming\\orbit-floodsub-ipfs-repo'
}

const dataDirectory = path.join(getUserHome(), getAppDataDirectory())

const appDataPath = path.resolve(MODE === 'dev' ? process.cwd() : process.resourcesPath + "/app")
if (!fs.existsSync(appDataPath))
  fs.mkdirSync(appDataPath)

Logger.setLogfile(path.join(appDataPath, 'debug.log'))
logger.debug("Run index.js in '" + MODE + "' mode")

const connectWindowSize = { width: 500, height: 430, center: true, minWidth: 500, minHeight: 430, "web-preferences": {
      "web-security": false
    } }
const mainWindowSize    = { width: 1200, height: 800, center: true, minWidth: 256, minHeight: 256, "web-preferences": {
      "web-security": false
    } }
let mainWindow = null

const template = require('./menu-native')(app)
const menu = Menu.buildFromTemplate(template)
let events

const setWindowToNormal = () => {
  const pos  = mainWindow.getPosition() || [0, 0]
  const size = mainWindow.getSize() || [connectWindowSize.width, connectWindowSize.height]
  const x    = (pos[0] + size[0]/2) - mainWindowSize.width/2
  const y    = (pos[1] + size[1]/2) - mainWindowSize.height/2
  mainWindow.setSize(mainWindowSize.width, mainWindowSize.height)
  mainWindow.setPosition(x, y)
}

const setWindowToLogin = () => {
  const pos  = mainWindow.getPosition() || [0, 0]
  const size = mainWindow.getSize() || [mainWindowSize.width, mainWindowSize.height]
  const x    = (pos[0] + size[0]/2) - connectWindowSize.width/2
  const y    = (pos[1] + size[1]/2) - connectWindowSize.height/2
  mainWindow.setSize(connectWindowSize.width, connectWindowSize.height)
  mainWindow.setPosition(x, y)
}

const shutdown = () => {
  logger.info("Shutting down...")
  setTimeout(() => {
    logger.info("All done!")
    app.quit()
  }, 1000)
}

app.on('window-all-closed', shutdown)
process.on('SIGINT', () => shutdown)
process.on('SIGTERM', () => shutdown)

process.on('uncaughtException', (error) => {
  logger.warn(error)
})

app.on('ready', () => {
  try {

    mainWindow = new BrowserWindow(connectWindowSize)

    logger.info("Checking for running IPFS daemon...")
    const test = IpfsApi()
    test.version((err, v) => {
      if(v && (v.version.split('.')[1] !== '4' || v.version.split('.')[2] !== '4-dev')) {
        let errStr = ''
        errStr += "Detected a running IPFS daemon version '" + v.version + "'\n"
        errStr += "Please shut down other IPFS daemons before running Orbit\n"

        errStr.split('\n')
          .forEach((e) => logger.error(e))

        mainWindow.loadURL('file://' + __dirname + '/client/dist/error.html?message=' + encodeURIComponent(errStr))
      } else {
        logger.info("Starting the systems")

        Menu.setApplicationMenu(menu)

        mainWindow = new BrowserWindow(connectWindowSize)
        mainWindow.webContents.session.setDownloadPath(path.resolve(getUserHome() + '/Downloads'))

        global.DEV = MODE === 'dev'
        global.isElectron = true

        let opts = {}
        opts['Addresses.API'] = '/ip4/127.0.0.1/tcp/0'
        opts['Addresses.Swarm'] = ['/ip4/0.0.0.0/tcp/0']
        opts['Addresses.Gateway'] = ''

        const loadApp = () => {
          if(MODE === 'dev')
            mainWindow.loadURL('http://localhost:8000/')
          else
            mainWindow.loadURL('file://' + __dirname + '/client/dist/index.html')
        }

        if (!err) {
          global.ipfsInstance = IpfsApi()
          loadApp()
        } else {
          let ipfsDaemon
          ipfsd.local(dataDirectory, opts, (err, node) => {
            if(err) throw err
            ipfsDaemon = node

            logger.info("Initializing IPFS daemon")
            ipfsDaemon.init((err, node) => {
              // Ignore error (usually "repo already exists")
              if (err) {
                console.log(err)
                const repoExists = String(err).match('ipfs configuration file already exists')
                const migrationNeeded = String(err).match('ipfs repo needs migration')

                if(migrationNeeded) {
                  let errStr = `Error initializing IPFS daemon: '${migrationNeeded[0]}'\n`
                  errStr += `Tried to init IPFS repo at '${dataDirectory}', but failed.\n`
                  errStr += `Use $IPFS_PATH to specify another repo path, eg. 'export IPFS_PATH=/tmp/orbit-floodsub'.`

                  errStr.split('\n')
                    .forEach((e) => logger.error(e))

                  dialog.showMessageBox({
                    type: 'error',
                    buttons: ['Ok :('],
                    title: 'Error',
                    message: migrationNeeded[0],
                    detail: errStr
                  }, () => process.exit(1))
                }
              } else {
                logger.info("Starting IPFS daemon")
                ipfsDaemon.startDaemon((err, ipfs) => {
                  if (err) throw err
                  logger.info("IPFS daemon started at", ipfs.apiHost, ipfs.apiPort)
                  global.ipfsInstance = IpfsApi(ipfs.apiHost, ipfs.apiPort)
                  // global.ipfsInstance = ipfs
                  loadApp()
                })
              }
            })
          })
        }

        mainWindow.on('closed', () => {
          mainWindow = null
        })

        ipcMain.on('connected', (event) => {
          setWindowToNormal()
        })

        ipcMain.on('disconnected', (event) => {
          setWindowToLogin()
        })
      }
    })
  } catch(e) {
    logger.error("Error in index-native:", e)
  }
})
<commit_msg>Improve logging re. IPFS data directory<commit_after>'use strict'

if(process.env.ENV === 'dev') delete process.versions['electron']

const fs            = require('fs')
const path          = require('path')
const electron      = require('electron')
const app           = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu          = electron.Menu
const ipcMain       = electron.ipcMain
const dialog        = electron.dialog
const ipfsd         = require('ipfsd-ctl')
const IpfsApi       = require('ipfs-api')
const Logger        = require('logplease')
const utils         = require('./src/utils')

const logger = Logger.create("Orbit.Index-Native")

const MODE = process.env.ENV ? process.env.ENV : 'debug'

const getUserHome = () => {
  return process.env[(process.platform !== 'win32') ? 'HOME' : 'USERPROFILE']
}

const getAppDataDirectory = () => {
  return process.platform !== 'win32'
    ? 'Library/Application Support/orbit-floodsub-ipfs-repo'
    : 'AppData\\Roaming\\orbit-floodsub-ipfs-repo'
}

const dataDirectory = path.join(getUserHome(), getAppDataDirectory())

const appDataPath = path.resolve(MODE === 'dev' ? process.cwd() : process.resourcesPath + "/app")
if (!fs.existsSync(appDataPath))
  fs.mkdirSync(appDataPath)

Logger.setLogfile(path.join(appDataPath, 'debug.log'))
logger.debug("Run index.js in '" + MODE + "' mode")

const connectWindowSize = { width: 500, height: 430, center: true, minWidth: 500, minHeight: 430, "web-preferences": {
      "web-security": false
    } }
const mainWindowSize    = { width: 1200, height: 800, center: true, minWidth: 256, minHeight: 256, "web-preferences": {
      "web-security": false
    } }
let mainWindow = null

const template = require('./menu-native')(app)
const menu = Menu.buildFromTemplate(template)
let events

const setWindowToNormal = () => {
  const pos  = mainWindow.getPosition() || [0, 0]
  const size = mainWindow.getSize() || [connectWindowSize.width, connectWindowSize.height]
  const x    = (pos[0] + size[0]/2) - mainWindowSize.width/2
  const y    = (pos[1] + size[1]/2) - mainWindowSize.height/2
  mainWindow.setSize(mainWindowSize.width, mainWindowSize.height)
  mainWindow.setPosition(x, y)
}

const setWindowToLogin = () => {
  const pos  = mainWindow.getPosition() || [0, 0]
  const size = mainWindow.getSize() || [mainWindowSize.width, mainWindowSize.height]
  const x    = (pos[0] + size[0]/2) - connectWindowSize.width/2
  const y    = (pos[1] + size[1]/2) - connectWindowSize.height/2
  mainWindow.setSize(connectWindowSize.width, connectWindowSize.height)
  mainWindow.setPosition(x, y)
}

const shutdown = () => {
  logger.info("Shutting down...")
  setTimeout(() => {
    logger.info("All done!")
    app.quit()
  }, 1000)
}

app.on('window-all-closed', shutdown)
process.on('SIGINT', () => shutdown)
process.on('SIGTERM', () => shutdown)

process.on('uncaughtException', (error) => {
  logger.warn(error)
})

app.on('ready', () => {
  try {

    mainWindow = new BrowserWindow(connectWindowSize)

    logger.info("Checking for running IPFS daemon...")
    const test = IpfsApi()
    test.version((err, v) => {
      if(v && (v.version.split('.')[1] !== '4' || v.version.split('.')[2] !== '4-dev')) {
        let errStr = ''
        errStr += "Detected a running IPFS daemon version '" + v.version + "'\n"
        errStr += "Please shut down other IPFS daemons before running Orbit\n"

        errStr.split('\n')
          .forEach((e) => logger.error(e))

        mainWindow.loadURL('file://' + __dirname + '/client/dist/error.html?message=' + encodeURIComponent(errStr))
      } else {
        logger.info("Starting the systems")

        Menu.setApplicationMenu(menu)

        mainWindow = new BrowserWindow(connectWindowSize)
        mainWindow.webContents.session.setDownloadPath(path.resolve(getUserHome() + '/Downloads'))

        global.DEV = MODE === 'dev'
        global.isElectron = true

        let opts = {}
        opts['Addresses.API'] = '/ip4/127.0.0.1/tcp/0'
        opts['Addresses.Swarm'] = ['/ip4/0.0.0.0/tcp/0']
        opts['Addresses.Gateway'] = ''

        const loadApp = () => {
          if(MODE === 'dev')
            mainWindow.loadURL('http://localhost:8000/')
          else
            mainWindow.loadURL('file://' + __dirname + '/client/dist/index.html')
        }

        if (!err) {
          global.ipfsInstance = IpfsApi()
          loadApp()
        } else {
          let ipfsDaemon
          ipfsd.local(dataDirectory, opts, (err, node) => {
            if(err) throw err
            ipfsDaemon = node

            logger.info("Initializing IPFS daemon")
            logger.debug(`Using IPFS repo at '${node.path}'`)

            ipfsDaemon.init({ directory: dataDirectory }, (err, node) => {
              // Ignore error (usually "repo already exists")
              if (err) {
                const repoExists = String(err).match('ipfs configuration file already exists')
                const migrationNeeded = String(err).match('ipfs repo needs migration')

                if (migrationNeeded) {
                  let errStr = `Error initializing IPFS daemon: '${migrationNeeded[0]}'\n`
                  errStr += `Tried to init IPFS repo at '${dataDirectory}', but failed.\n`
                  errStr += `Use $IPFS_PATH to specify another repo path, eg. 'export IPFS_PATH=/tmp/orbit-floodsub'.`

                  errStr.split('\n')
                    .forEach((e) => logger.error(e))

                  dialog.showMessageBox({
                    type: 'error',
                    buttons: ['Ok :('],
                    title: 'Error',
                    message: migrationNeeded[0],
                    detail: errStr
                  }, () => process.exit(1))
                }
              } else {
                logger.info("Starting IPFS daemon")
                ipfsDaemon.startDaemon((err, ipfs) => {
                  if (err) throw err
                  logger.info("IPFS daemon started at", ipfs.apiHost, ipfs.apiPort)
                  global.ipfsInstance = IpfsApi(ipfs.apiHost, ipfs.apiPort)
                  // global.ipfsInstance = ipfs
                  loadApp()
                })
              }
            })
          })
        }

        mainWindow.on('closed', () => {
          mainWindow = null
        })

        ipcMain.on('connected', (event) => {
          setWindowToNormal()
        })

        ipcMain.on('disconnected', (event) => {
          setWindowToLogin()
        })
      }
    })
  } catch(e) {
    logger.error("Error in index-native:", e)
  }
})
<|endoftext|>


<commit_before>/*
 * Christmas lights controller - Tim Poulsen
 * License MIT
 *
 *
 */

var _ = require("lodash"),
	colors = require("colors"),
	fields = require("fields"),
	rpio = require('rpio'),
	fs = require("fs"),
	path = require("path");

const OFF = rpio.HIGH;
const ON = rpio.LOW;

var pins = [3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24];
var shows = fs.readdirSync('shows');
var turnOffShowAt;

turnOffAllRelays();

if (process.argv[2]) {
	var showToRun = process.argv[2];
	if (showToRun === 'off') {
		turnOffAllRelays();
	} else if (showToRun === 'on') {
		turnOnAllRelays();
	} else {
		runShow(process.argv[2]);
	}
} else {
	fields.set([
		fields.select({
			promptLabel: 'Which show would you like to run?',
			options: shows,
			numbered: true
		})
	]).prompt(function (err, value) {
		if (err) {
			console.error('There was an error!\n' + err);
		} else {
			runShow(value[0]);
		}
	});

}

if (process.argv[3] && !isNaN(process.argv[3])) {
	// turn off the show after x hours
	var now = new Date();
	var futureMS = Math.round(parseFloat(process.argv[3]) * 60 * 60 * 1000);
	turnOffShowAt = now.getTime() + futureMS;
}

function runShow(showName) {
	var filePath = path.join('shows', showName);
	if (!fs.existsSync(filePath)) {
		console.error('No show file by the name ' + showName);
		process.exit(1);
	}
	var showFile = fs.readFileSync(filePath, 'utf8'),
		show = JSON.parse(showFile);
	var i = 0,
		interval = show.interval;

	var looper = setInterval(function () {
		if (turnOffShowAt) {
			if ((new Date()).getTime() > turnOffShowAt) {
				clearInterval(looper);
				looper = undefined;
				turnOffAllRelays(); // app will exit when that's done
			}
		}
		if (i < show.show.length) {
			drawRow(show.show[i]);
			i++;
		} else {
			if (!show.loop) {
				// show isn't set up to run continously
				clearInterval(looper);
				looper = undefined;
			} else {
				i = 0;
			}
		}
	}, interval);
}

function drawRow(arr) {
	arr.forEach(function (pinValue, index) {
		rpio.write(pins[index], pinValue ? ON : OFF);
	});
}

function turnOffAllRelays() {
	pins.forEach(function (pin) {
		rpio.open(pin, rpio.OUTPUT, OFF);
	});
}

function turnOnAllRelays() {
	pins.forEach(function (pin) {
		rpio.open(pin, rpio.OUTPUT, ON);
	});
}<commit_msg>update auto-shut-off<commit_after>/*
 * Christmas lights controller - Tim Poulsen
 * License MIT
 *
 *
 */

var _ = require("lodash"),
	colors = require("colors"),
	fields = require("fields"),
	rpio = require('rpio'),
	fs = require("fs"),
	path = require("path");

const OFF = rpio.HIGH;
const ON = rpio.LOW;

var pins = [3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24];
var shows = fs.readdirSync('shows');
var turnOffShowAt;

turnOffAllRelays();

if (process.argv[2]) {
	var showToRun = process.argv[2];
	if (showToRun === 'off') {
		turnOffAllRelays();
	} else if (showToRun === 'on') {
		turnOnAllRelays();
	} else {
		runShow(process.argv[2]);
	}
} else {
	fields.set([
		fields.select({
			promptLabel: 'Which show would you like to run?',
			options: shows,
			numbered: true
		})
	]).prompt(function (err, value) {
		if (err) {
			console.error('There was an error!\n' + err);
		} else {
			runShow(value[0]);
		}
	});

}

if (process.argv[3] && !isNaN(process.argv[3])) {
	// turn off the show after x hours
	var now = new Date();
	var futureMS = Math.round(parseFloat(process.argv[3]) * 60 * 60 * 1000);
	turnOffShowAt = now.getTime() + futureMS;
}

function runShow(showName) {
	var filePath = path.join('shows', showName);
	if (!fs.existsSync(filePath)) {
		console.error('No show file by the name ' + showName);
		process.exit(1);
	}
	var showFile = fs.readFileSync(filePath, 'utf8'),
		show = JSON.parse(showFile);
	var i = 0,
		interval = show.interval;

	var looper = setInterval(function () {
		if (i < show.show.length) {
			drawRow(show.show[i]);
			i++;
		} else {
			if (!show.loop) {
				// show isn't set up to run continously
				clearInterval(looper);
				looper = undefined;
			} else {
				i = 0;
			}
		}
		if (turnOffShowAt) {
			if ((new Date()).getTime() > turnOffShowAt) {
				clearInterval(looper);
				looper = undefined;
				turnOffAllRelays(); // app will exit when that's done
			}
		}
	}, interval);
}

function drawRow(arr) {
	arr.forEach(function (pinValue, index) {
		rpio.write(pins[index], pinValue ? ON : OFF);
	});
}

function turnOffAllRelays() {
	pins.forEach(function (pin) {
		rpio.open(pin, rpio.OUTPUT, OFF);
	});
}

function turnOnAllRelays() {
	pins.forEach(function (pin) {
		rpio.open(pin, rpio.OUTPUT, ON);
	});
}<|endoftext|>