<commit_before>require('dotenv').load();

var neo4j = require('neo4j');
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var SpotifyStrategy = require('passport-spotify').Strategy;
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var Redis = require('ioredis');
var app = express();

// yup, lets use "neo" as a password locally
var db = new neo4j.GraphDatabase(process.env.GRAPHENEDB_URL || 'http://neo4j:neo@localhost:7474');
var redis = new Redis(process.env.REDISTOGO_URL);

var opts = {
  resave:false,
  saveUninitialized:true,
  store: new RedisStore({
    client: redis
  }),
  secret: process.env.SESSION_SECRET || 'keyboard cat',
  cookie: {path: '/', secure: false}
};

if (app.get('env') === 'production') {
  app.set('trust proxy', 1);
  opts.cookie.secure = true;
}

// just persist the whole thing in the session for now (won't be on the client)
passport.serializeUser(function(user, done) { done(null, user); });
passport.deserializeUser(function(obj, done) { done(null, obj); });

app.use(session(opts));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new SpotifyStrategy({
    clientID: process.env.SPOTIFY_CLIENT_ID,
    clientSecret:  process.env.SPOTIFY_CLIENT_SECRET,
    callbackURL: process.env.SPOTIFY_CALLBACK_URL
  },
  function(accessToken, refreshToken, profile, done) {
    console.log(profile);
    db.cypher({
      query: 'MERGE (user:user { spotifyId: {spotifyId}, displayName: {displayName}, photos: {photos} }) RETURN user',
      params: {
        spotifyId: profile.id,
        displayName: profile.displayName,
        photos: profile.photos,
      },
    }, function(err, response){
      done(err, response[0].user);
    });
  }
));

app.get('/auth', passport.authenticate('spotify'));

app.get('/callback',
  passport.authenticate('spotify', { failureRedirect: '/?failed' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set('views', './views');
app.set('view engine', 'jade');

app.get('/', function(req, res) {
  res.render('tree', {action: '', user: req.user});
});

app.post('/', function(req, res) {

  // todo-check
  console.log(req.body);

  db.cypher({
    query: 'CREATE (n:track { uri: {uri}, why: {why} }) RETURN n',
    params: {
      uri: req.body.track,
      why: req.body.why
    },
  }, function(err, results) {
    if (err) throw err;
    res.redirect(results[0].n._id);
  });
});

app.get('/:id', function(req, res, next){
    if(!parseInt(req.params.id)) return next();
    db.cypher({
      // TODO limit to tracks not users
      query: 'MATCH (track-[*0..25]->n) WHERE id(n)={id} RETURN track',
      params: {
        id: parseInt(req.params.id)
      },
    }, function(err, tracks) {
      if (err) throw err;
      if(!tracks.length) return res.send(404);

      tracks.reverse();
      res.render('tree', { tracks: tracks, action: req.params.id, user: req.user });
    });
});

app.post('/:id', function(req, res){
    if(!parseInt(req.params.id)) return next();
    db.cypher({
      query: 'MATCH (p) WHERE id(p)={id} CREATE (n:track { uri: {uri}, why: {why} }), (p)-[:PARENT]->(n) RETURN n',
      params: {
        id: parseInt(req.params.id),
        uri: req.body.track,
        why: req.body.why
      },
    }, function(err, results) {
      if (err) throw err;
      res.redirect(results[0].n._id);
    });
});

app.listen(process.env.PORT || 3000);
<commit_msg>attach users to first track, breaks stuff<commit_after>require('dotenv').load();

var neo4j = require('neo4j');
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var SpotifyStrategy = require('passport-spotify').Strategy;
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var Redis = require('ioredis');
var app = express();

// yup, lets use "neo" as a password locally
var db = new neo4j.GraphDatabase(process.env.GRAPHENEDB_URL || 'http://neo4j:neo@localhost:7474');
var redis = new Redis(process.env.REDISTOGO_URL);

var opts = {
  resave:false,
  saveUninitialized:true,
  store: new RedisStore({
    client: redis
  }),
  secret: process.env.SESSION_SECRET || 'keyboard cat',
  cookie: {path: '/', secure: false}
};

if (app.get('env') === 'production') {
  app.set('trust proxy', 1);
  opts.cookie.secure = true;
}

// just persist the whole thing in the session for now (won't be on the client)
passport.serializeUser(function(user, done) { done(null, user); });
passport.deserializeUser(function(obj, done) { done(null, obj); });

app.use(session(opts));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new SpotifyStrategy({
    clientID: process.env.SPOTIFY_CLIENT_ID,
    clientSecret:  process.env.SPOTIFY_CLIENT_SECRET,
    callbackURL: process.env.SPOTIFY_CALLBACK_URL
  },
  function(accessToken, refreshToken, profile, done) {
    console.log(profile);
    db.cypher({
      query: 'MERGE (user:user { spotifyId: {spotifyId}, displayName: {displayName}, photos: {photos} }) RETURN user',
      params: {
        spotifyId: profile.id,
        displayName: profile.displayName,
        photos: profile.photos,
      },
    }, function(err, response){
      done(err, response[0].user);
    });
  }
));

app.get('/auth', passport.authenticate('spotify'));

app.get('/callback',
  passport.authenticate('spotify', { failureRedirect: '/?failed' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set('views', './views');
app.set('view engine', 'jade');

app.get('/', function(req, res) {
  res.render('tree', {action: '', user: req.user});
});

app.post('/', function(req, res) {

  // todo-check
  console.log(req.body);

  db.cypher({
    query: 'MATCH (u) WHERE id(u)={userId} CREATE (n:track { uri: {uri}, why: {why}}), (u)-[:AUTHOR]->(n) RETURN n',
    params: {
      userId: req.user._id,
      uri: req.body.track,
      why: req.body.why
    },
  }, function(err, results) {
    if (err) throw err;
    res.redirect(results[0].n._id);
  });
});

app.get('/:id', function(req, res, next){
    if(!parseInt(req.params.id)) return next();
    db.cypher({
      query: 'MATCH (track-[:PARENT*0..25]->n) WHERE id(n)={id} RETURN track',
      params: {
        id: parseInt(req.params.id)
      },
    }, function(err, tracks) {
      if (err) throw err;
      if(!tracks.length) return res.send(404);

      tracks.reverse();
      res.render('tree', { tracks: tracks, action: req.params.id, user: req.user });
    });
});

app.post('/:id', function(req, res){
    if(!parseInt(req.params.id)) return next();
    db.cypher({
      query: 'MATCH (p) WHERE id(p)={id} CREATE (n:track { uri: {uri}, why: {why} }), (p)-[:PARENT]->(n) RETURN n',
      params: {
        id: parseInt(req.params.id),
        uri: req.body.track,
        why: req.body.why
      },
    }, function(err, results) {
      if (err) throw err;
      res.redirect(results[0].n._id);
    });
});

app.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>var request = require('request');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var fs = require('fs');
var _ = require('lodash');
var async = require('async');
var color = gutil.colors;

const PLUGIN_NAME = 'gulp-phrase';

function phrase(params, cb) {

    function pull(params , cb) {
        listLocales(params, cb);
    }

    function listLocales(params, cb) {
        makeApiRequest('locales', params, function(body) {
            var locales = JSON.parse(body);

            var syncArray = [];

            _.each(locales, function(locale, index) {
                syncArray[index] = function(cb) {

                    setTimeout(function() {
                        downloadTranslations(locale, params, function(res) {
                            cb(null, res);
                        });
                    }, 500);

                };
            });

            setTimeout(function() {
                async.series(syncArray, function(err, results) {
                    cb(results);
                });
            }, 500);
        });
    }

    function downloadTranslations(locale, params, cb) {
        var path = 'translations/download';
        var filename = params.dir + 'phrase.' + locale.name + '.json';
        var file = fs.createWriteStream(filename);

        //file handlers
        file
            .on('open', function() {
                process.stdout.write('Fetch locale -> ' + locale.name + '\r\n');
            })
            .on('error', function() {
                process.stdout.write(color.red('Error when fetch locale -> ' + locale.name + '\r\n'));
                cb(false);
            })
            .on('finish', function() {
                cb(filename);
                process.stdout.write(color.green('Downloaded ->' + filename + '\r\n'));
            });

        params.locale = locale.name;

        makeApiRequest(path, params, function(body) {
            file.write(body);
            file.end();
        });
    }

    function makeApiRequest(path, params, cb) {
        var uri = 'https://phraseapp.com/api/v1/' + path;

        request.get(prepareApiRequest(params, uri), function(err, response, body) {

            if (err) {
                cb(new PluginError(PLUGIN_NAME, err));
            }

            cb(body);
        });
    }

    function prepareApiRequest(params, path) {

        if (!params.apiToken || !params.dir) {
            throw new PluginError(PLUGIN_NAME, 'Invalid params');
        }

        var apiToken = params.apiToken;
        var tag = params.tag ? params.tag : false;
        var dir = params.dir ? params.dir : false;
        var format = 'simple_json';
        var locale = params.locale ? params.locale : false;

        var options = {
            url: path
        };

        if (apiToken) {
            options.qs = {
                'auth_token' : apiToken,
                'format': format
            };
        }

        if (tag) {
            options.qs.tag = tag;
        }

        if (dir) {
            options.dir = dir;
        }

        if (locale) {
            options.qs.locale = locale;
        }

        return options;
    }

    return pull(params, cb);
}

module.exports = phrase;
<commit_msg>Fix CS<commit_after>var request = require('request');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var fs = require('fs');
var _ = require('lodash');
var async = require('async');
var color = gutil.colors;

const PLUGIN_NAME = 'gulp-phrase';

function phrase(params, cb) {

  function pull(params , cb) {
    listLocales(params, cb);
  }

  function listLocales(params, cb) {
    makeApiRequest('locales', params, function(body) {
      var locales = JSON.parse(body);

      var syncArray = [];

      _.each(locales, function(locale, index) {
        syncArray[index] = function(cb) {

          setTimeout(function() {
            downloadTranslations(locale, params, function(res) {
              cb(null, res);
            });
          }, 500);

        };
      });

      setTimeout(function() {
        async.series(syncArray, function(err, results) {
          cb(results);
        });
      }, 500);
    });
  }

  function downloadTranslations(locale, params, cb) {
    var path = 'translations/download';
    var filename = params.dir + 'phrase.' + locale.name + '.json';
    var file = fs.createWriteStream(filename);

        //file handlers
        file
        .on('open', function() {
          process.stdout.write('Fetch locale -> ' + locale.name + '\r\n');
        })
        .on('error', function() {
          process.stdout.write(color.red('Error when fetch locale -> ' + locale.name + '\r\n'));
          cb(false);
        })
        .on('finish', function() {
          cb(filename);
          process.stdout.write(color.green('Downloaded ->' + filename + '\r\n'));
        });

        params.locale = locale.name;

        makeApiRequest(path, params, function(body) {
          file.write(body);
          file.end();
        });
      }

      function makeApiRequest(path, params, cb) {
        var uri = 'https://phraseapp.com/api/v1/' + path;

        request.get(prepareApiRequest(params, uri), function(err, response, body) {

          if (err) {
            cb(new PluginError(PLUGIN_NAME, err));
          }

          cb(body);
        });
      }

      function prepareApiRequest(params, path) {

        if (!params.apiToken || !params.dir) {
          throw new PluginError(PLUGIN_NAME, 'Invalid params');
        }

        var apiToken = params.apiToken;
        var tag = params.tag ? params.tag : false;
        var dir = params.dir ? params.dir : false;
        var format = 'simple_json';
        var locale = params.locale ? params.locale : false;

        var options = {
          url: path
        };

        if (apiToken) {
          options.qs = {
            'auth_token' : apiToken,
            'format': format
          };
        }

        if (tag) {
          options.qs.tag = tag;
        }

        if (dir) {
          options.dir = dir;
        }

        if (locale) {
          options.qs.locale = locale;
        }

        return options;
      }

      return pull(params, cb);
    }

    module.exports = phrase;
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

var mkdirp = require('mkdirp');
var async = require('async');

var AsyncDependenciesBlock = require('webpack/lib/AsyncDependenciesBlock');
var ConstDependency = require('webpack/lib/dependencies/ConstDependency');
var ContextDependency = require('webpack/lib/dependencies/ContextDependency');
var DependenciesBlockVariable = require('webpack/lib/DependenciesBlockVariable');
var ModuleDependency = require('webpack/lib/dependencies/ModuleDependency');
var NullDependency = require('webpack/lib/dependencies/NullDependency');
var NullDependencyTemplate = require('webpack/lib/dependencies/NullDependencyTemplate');
var NullFactory = require('webpack/lib/NullFactory');
var RawModule = require('webpack/lib/RawModule');

var RawSource = require('webpack-sources').RawSource;
var Source = require('webpack-sources').Source;

var SourceNode = require('source-map').SourceNode;
var SourceMapConsumer = require('source-map').SourceMapConsumer;

var fromStringWithSourceMap = require('source-list-map').fromStringWithSourceMap;

function RawModuleDependency(request) {
  ModuleDependency.call(this, request);
}
RawModuleDependency.prototype = Object.create(ModuleDependency.prototype);
RawModuleDependency.prototype.constructor = RawModuleDependency;
function RawModuleDependencyTemplate() {
}
RawModuleDependencyTemplate.prototype.apply = function() {};
RawModuleDependencyTemplate.prototype.applyAsTemplateArgument = function() {};

function CacheModule(cacheItem) {
  RawModule.call(this, cacheItem.source, cacheItem.identifier, cacheItem.identifier);

  this.context = cacheItem.context;
  this.request = cacheItem.request;
  // this.map = function() {return cacheItem.map;};
  var source = new RawSource(cacheItem.source);
  source.map = function() {
    return cacheItem.map;
  };
  source.node = function() {
    n = SourceNode.fromStringWithSourceMap(
      cacheItem.source,
      new SourceMapConsumer(cacheItem.map)
    );
    // Rehydrate source keys
    var sources = Object.keys(n.sourceContents);
    for (var i = 0; i < sources.length; i++) {
      var key = sources[i];
      n.sourceContents['$' + key] = n.sourceContents[key];
      delete n.sourceContents[key];
    }
    return n;
  };
  source.listMap = function() {
    return fromStringWithSourceMap(cacheItem.source, cacheItem.map);
  };
  this.source = function() {
    return source;
  };
  this.updateHash = function(hash) {
    hash.update(cacheItem.hashContent);
  };
  this.assets = Object.keys(cacheItem.assets).reduce(function(carry, key) {
    var source = cacheItem.assets[key];
    if (source.type === 'Buffer') {
      source = new Buffer(source);
    }
    carry[key] = new RawSource(source);
    return carry;
  }, {});
  this.buildTimestamp = cacheItem.buildTimestamp;
  this.fileDependencies = cacheItem.fileDependencies;
  this.contextDependencies = cacheItem.contextDependencies;
  function deserializeDependencies(deps) {
    return deps.map(function(req) {
      if (req.contextDependency) {
        return new ContextDependency(req.request, req.recursive, req.regExp ? new RegExp(req.regExp) : null);
      }
      if (req.constDependency) {
        return new NullDependency();
      }
      return new RawModuleDependency(req.request);
    });
  }
  function deserializeVariables(vars) {
    return vars.map(function(req) {
      return new DependenciesBlockVariable(req.name, req.expression, deserializeDependencies(req.dependencies));
    });
  }
  function deserializeBlocks(blocks, parent) {
    blocks.map(function(req) {
      if (req.async) {
        var block = new AsyncDependenciesBlock(req.name, parent);
        block.dependencies = deserializeDependencies(req.dependencies);
        block.variables = deserializeVariables(req.variables);
        deserializeBlocks(req.blocks, block);
        return block;
      }
    })
    .filter(Boolean)
    .forEach(function(block) {
      parent.addBlock(block);
    });
  }
  this.dependencies = deserializeDependencies(cacheItem.dependencies);
  this.variables = deserializeVariables(cacheItem.variables);
  deserializeBlocks(cacheItem.blocks, this);
}
CacheModule.prototype = Object.create(RawModule.prototype);
CacheModule.prototype.constructor = CacheModule;
function needRebuild(buildTimestamp, fileDependencies, contextDependencies, fileTimestamps, contextTimestamps) {
  var timestamp = 0;
  fileDependencies.forEach(function(file) {
    var ts = fileTimestamps[file];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  contextDependencies.forEach(function(context) {
    var ts = contextTimestamps[context];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  return timestamp >= buildTimestamp;
}
CacheModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
  return needRebuild(this.buildTimestamp, this.fileDependencies, this.contextDependencies, fileTimestamps, contextTimestamps);
};

function HardSourceWebpackPlugin(options) {
  this.options = options;
}

module.exports = HardSourceWebpackPlugin;
HardSourceWebpackPlugin.prototype.apply = function(compiler) {
  var options = this.options;
  var active = true;
  var cacheDirName = options.cacheDirectory;
  if (!cacheDirName) {
    console.error('HardSourceWebpackPlugin requires a cacheDirectory setting.');
    active = false;
    return;
  }
  var cacheDirPath = path.join(compiler.options.context, cacheDirName);
  var resolveCachePath = path.join(cacheDirPath, 'resolve.json');

  var resolveCache = {};
  var moduleCache = {};
  var moduleCacheLoading = [];

  var fileTimestamps = {};

  compiler.plugin('after-plugins', function() {
    if (
      !compiler.recordsInputPath ||
      compiler.recordsInputPath !== compiler.recordsOutputPath
    ) {
      console.error('HardSourceWebpackPlugin requires recordsPath to be set.');
      active = false;
    }
  });

  compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
    if (!active) {return cb();}
    mkdirp.sync(cacheDirPath);
    try {
      resolveCache = JSON.parse(fs.readFileSync(resolveCachePath, 'utf8'));
    }
    catch (e) {}
    var start = Date.now();

    moduleCacheLoading = [];

    async.each(fs.readdirSync(cacheDirPath), function(name, cb) {
      if (name === 'records.json') {return cb();}
      if (name === 'resolve.json') {return cb();}
      fs.readFile(path.join(cacheDirPath, name), 'utf8', function(err, json) {
        if (err) {return cb();}
        var subcache = JSON.parse(json);
        var key = Object.keys(subcache)[0];
        moduleCache[key] = subcache[key];
        cb();
      });
    }, function() {
      var loading = moduleCacheLoading;
      moduleCacheLoading = null;
      for (var i = 0; i < loading.length; i++) {
        loading[i]();
      }
      cb();
    });
  });

  compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
    if (!active) {return cb();}

    if (!compiler.inputFileSystem) {
      // try {
      //   compiler.compiler.records = JSON.parse(fs.readFileSync(recordsPath, 'utf8'));
      // }
      // catch (e) {}
    }
    else {
      // compiler.recordsInputPath = compiler.recordsOutputPath = recordsPath;
    }

    if(!moduleCache.fileDependencies) return cb();
    // var fs = compiler.inputFileSystem;
    var fileTs = compiler.fileTimestamps = fileTimestamps = {};
    async.forEach(moduleCache.fileDependencies, function(file, callback) {
      fs.stat(file, function(err, stat) {
        if(err) {
          if(err.code === "ENOENT") return callback();
          return callback(err);
        }

        fileTs[file] = stat.mtime || Infinity;
        callback();
      });
    }, cb);
  });

  compiler.plugin('compilation', function(compilation, params) {
    if (!active) {return;}

    compilation.fileTimestamps = fileTimestamps;

    compilation.dependencyFactories.set(RawModuleDependency, params.normalModuleFactory);
    compilation.dependencyTemplates.set(RawModuleDependency, new RawModuleDependencyTemplate);

    compilation.dependencyFactories.set(ContextDependency, params.contextModuleFactory);
    compilation.dependencyTemplates.set(ContextDependency, new RawModuleDependencyTemplate);

    compilation.dependencyFactories.set(NullDependency, new NullFactory());
    compilation.dependencyTemplates.set(NullDependency, new NullDependencyTemplate);

    params.normalModuleFactory.plugin('resolver', function(fn) {
      return function(request, cb) {
        // if (request.request.indexOf('index.html') !== -1) {
        //   console.log('resolve cache', request.request);
        // }
        var cacheId = JSON.stringify([request.context, request.request]);
        if (resolveCache[cacheId]) {
          var result = Object.assign({}, resolveCache[cacheId]);
          result.dependencies = request.dependencies;
          result.parser = compilation.compiler.parser;
          return cb(null, result);
        }

        var originalRequest = request;
        return fn.call(null, request, function(err, request) {
          if (err) {
            return cb(err);
          }
          if (!request.source) {
            resolveCache[cacheId] = Object.assign({}, request, {
              parser: null,
              dependencies: null,
            });
          }
          cb.apply(null, arguments);
        });
      };
    });

    params.normalModuleFactory.plugin('resolver', function(fn) {
      return function(request, cb) {
        fn.call(null, request, function(err, result) {
          if (err) {return cb(err);}
          // else if (moduleCacheLoading) {
          //   return moduleCacheLoading.push(function() {
          //     var cacheItem = moduleCache[result.request];
          //     if (!needRebuild(
          //       cacheItem.buildTimestamp,
          //       cacheItem.fileDependencies,
          //       // cacheItem.contextDependencies,
          //       [],
          //       fileTimestamps,
          //       compiler.contextTimestamps
          //     )) {
          //       var module = new CacheModule(cacheItem);
          //       return cb(null, module);
          //     }
          //     else {
          //       result.parser = compilation.compiler.parser;
          //       return cb(null, result);
          //     }
          //   });
          // }
          else if (moduleCache[result.request]) {
            var cacheItem = moduleCache[result.request];
            if (!needRebuild(
              cacheItem.buildTimestamp,
              cacheItem.fileDependencies,
              cacheItem.contextDependencies,
              // [],
              fileTimestamps,
              compiler.contextTimestamps
            )) {
              var module = new CacheModule(cacheItem);
              return cb(null, module);
            }
          }
          return cb(null, result);
        });
      };
    });
  });

  compiler.plugin('after-compile', function(compilation, cb) {
    if (!active) {return cb();}

    var startCacheTime = Date.now();
    fs.writeFileSync(resolveCachePath, JSON.stringify(resolveCache), 'utf8');

    function serializeDependencies(deps) {
      return deps
      .map(function(dep) {
        return {
          contextDependency: dep instanceof ContextDependency,
          constDependency: dep instanceof ConstDependency,
          request: dep.request,
          recursive: dep.recursive,
          regExp: dep.regExp ? dep.regExp.source : null,
        };
      })
      .filter(function(req) {
        return req.request || req.constDependency;
      });
    }
    function serializeVariables(vars) {
      return vars.map(function(variable) {
        return {
          name: variable.name,
          expression: variable.expression,
          dependencies: serializeDependencies(variable.dependencies),
        }
      });
    }
    function serializeBlocks(blocks) {
      return blocks.map(function(block) {
        return {
          async: block instanceof AsyncDependenciesBlock,
          name: block.chunkName,
          dependencies: serializeDependencies(block.dependencies),
          variables: serializeVariables(block.variables),
          blocks: serializeBlocks(block.blocks),
        };
      });
    }
    function serializeHashContent(module) {
      var content = [];
      module.updateHash({
        update: function(str) {
          content.push(str);
        },
      });
      return content.join('');
    }

    var devtoolOptions;
  	if(compiler.options.devtool && (compiler.options.devtool.indexOf("sourcemap") >= 0 || compiler.options.devtool.indexOf("source-map") >= 0)) {
  		var hidden = compiler.options.devtool.indexOf("hidden") >= 0;
  		var inline = compiler.options.devtool.indexOf("inline") >= 0;
  		var evalWrapped = compiler.options.devtool.indexOf("eval") >= 0;
  		var cheap = compiler.options.devtool.indexOf("cheap") >= 0;
  		var moduleMaps = compiler.options.devtool.indexOf("module") >= 0;
  		var noSources = compiler.options.devtool.indexOf("nosources") >= 0;
  		var legacy = compiler.options.devtool.indexOf("@") >= 0;
  		var modern = compiler.options.devtool.indexOf("#") >= 0;
  		var comment = legacy && modern ? "\n/*\n//@ sourceMappingURL=[url]\n//# sourceMappingURL=[url]\n*/" :
  			legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" :
  			modern ? "\n//# sourceMappingURL=[url]" :
  			null;
      devtoolOptions = {
  			filename: inline ? null : compiler.options.output.sourceMapFilename,
  			moduleFilenameTemplate: compiler.options.output.devtoolModuleFilenameTemplate,
  			fallbackModuleFilenameTemplate: compiler.options.output.devtoolFallbackModuleFilenameTemplate,
  			append: hidden ? false : comment,
  			module: moduleMaps ? true : cheap ? false : true,
  			columns: cheap ? false : true,
  			lineToLine: compiler.options.output.devtoolLineToLine,
  			noSources: noSources,
  		};
  	}

    moduleCache.fileDependencies = compilation.fileDependencies;
    fs.writeFileSync(
      path.join(cacheDirPath, 'file-dependencies.json'),
      JSON.stringify({fileDependencies: compilation.fileDependencies}),
      'utf8'
    );

    async.forEach(compilation.modules, function(module, cb) {
      if (module.request && module.cacheable && !(module instanceof CacheModule)) {
        var source = module.source(
          compilation.dependencyTemplates,
          compilation.moduleTemplate.outputOptions,
          compilation.moduleTemplate.requestShortener
        );
        moduleCache[module.request] = {
          moduleId: module.id,
          context: module.context,
          request: module.request,
          identifier: module.identifier(),
          assets: Object.keys(module.assets || {}).reduce(function(carry, key) {
            carry[key] = module.assets[key].source();
            return carry;
          }, {}),
          buildTimestamp: module.buildTimestamp,

          source: source.source(),
          map: devtoolOptions && source.map(devtoolOptions),
          hashContent: serializeHashContent(module),

          dependencies: serializeDependencies(module.dependencies),
          variables: serializeVariables(module.variables),
          blocks: serializeBlocks(module.blocks),

          fileDependencies: module.fileDependencies,
          contextDependencies: module.contextDependencies,
        };

        mkdirp.sync(cacheDirPath);
        var hashName = crypto.createHash('sha1')
        .update(module.request).digest().hexSlice();
        return fs.writeFile(
          path.join(cacheDirPath, hashName + '.json'),
          JSON.stringify({[module.request]: moduleCache[module.request]}),
          'utf8',
          cb
        );
      }
      cb();
    }, cb);
    //
    // console.log('cache out', Date.now() - startCacheTime);
    // cb();
  });
  // Ensure records are stored inbetween runs of memory-fs using
  // webpack-dev-middleware.
  compiler.plugin('done', function() {
    if (!active) {return;}

    fs.writeFileSync(
      path.resolve(compiler.options.context, compiler.recordsOutputPath),
      JSON.stringify(compiler.records, null, 2),
      'utf8'
    );
  });
};
<commit_msg>Improve source content key hydration<commit_after>var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

var mkdirp = require('mkdirp');
var async = require('async');

var AsyncDependenciesBlock = require('webpack/lib/AsyncDependenciesBlock');
var ConstDependency = require('webpack/lib/dependencies/ConstDependency');
var ContextDependency = require('webpack/lib/dependencies/ContextDependency');
var DependenciesBlockVariable = require('webpack/lib/DependenciesBlockVariable');
var ModuleDependency = require('webpack/lib/dependencies/ModuleDependency');
var NullDependency = require('webpack/lib/dependencies/NullDependency');
var NullDependencyTemplate = require('webpack/lib/dependencies/NullDependencyTemplate');
var NullFactory = require('webpack/lib/NullFactory');
var RawModule = require('webpack/lib/RawModule');

var RawSource = require('webpack-sources').RawSource;
var Source = require('webpack-sources').Source;

var SourceNode = require('source-map').SourceNode;
var SourceMapConsumer = require('source-map').SourceMapConsumer;

var fromStringWithSourceMap = require('source-list-map').fromStringWithSourceMap;

function RawModuleDependency(request) {
  ModuleDependency.call(this, request);
}
RawModuleDependency.prototype = Object.create(ModuleDependency.prototype);
RawModuleDependency.prototype.constructor = RawModuleDependency;
function RawModuleDependencyTemplate() {
}
RawModuleDependencyTemplate.prototype.apply = function() {};
RawModuleDependencyTemplate.prototype.applyAsTemplateArgument = function() {};

function CacheModule(cacheItem) {
  RawModule.call(this, cacheItem.source, cacheItem.identifier, cacheItem.identifier);

  this.context = cacheItem.context;
  this.request = cacheItem.request;
  // this.map = function() {return cacheItem.map;};
  var source = new RawSource(cacheItem.source);
  source.map = function() {
    return cacheItem.map;
  };
  source.node = function() {
    var node = SourceNode.fromStringWithSourceMap(
      cacheItem.source,
      new SourceMapConsumer(cacheItem.map)
    );
    // Rehydrate source keys, webpack 1 uses source-map 0.4 which needs an
    // appended $. webpack 2 uses source-map 0.5 which may append $. Either way
    // setSourceContent will provide the needed behaviour. This is pretty round
    // about and ugly but this is less prone to failure than trying to determine
    // whether we're in webpack 1 or 2 and if they are using webpack-core or
    // webpack-sources and the version of source-map in that.
    var setSourceContent = new RawModule('').source().node().setSourceContent;
    var sources = Object.keys(node.sourceContents);
    for (var i = 0; i < sources.length; i++) {
      var key = sources[i];
      var content = node.sourceContents[key];
      delete node.sourceContents[key];
      setSourceContent.call(node, key, content);
    }
    return node;
  };
  source.listMap = function() {
    return fromStringWithSourceMap(cacheItem.source, cacheItem.map);
  };
  this.source = function() {
    return source;
  };
  this.updateHash = function(hash) {
    hash.update(cacheItem.hashContent);
  };
  this.assets = Object.keys(cacheItem.assets).reduce(function(carry, key) {
    var source = cacheItem.assets[key];
    if (source.type === 'Buffer') {
      source = new Buffer(source);
    }
    carry[key] = new RawSource(source);
    return carry;
  }, {});
  this.buildTimestamp = cacheItem.buildTimestamp;
  this.fileDependencies = cacheItem.fileDependencies;
  this.contextDependencies = cacheItem.contextDependencies;
  function deserializeDependencies(deps) {
    return deps.map(function(req) {
      if (req.contextDependency) {
        return new ContextDependency(req.request, req.recursive, req.regExp ? new RegExp(req.regExp) : null);
      }
      if (req.constDependency) {
        return new NullDependency();
      }
      return new RawModuleDependency(req.request);
    });
  }
  function deserializeVariables(vars) {
    return vars.map(function(req) {
      return new DependenciesBlockVariable(req.name, req.expression, deserializeDependencies(req.dependencies));
    });
  }
  function deserializeBlocks(blocks, parent) {
    blocks.map(function(req) {
      if (req.async) {
        var block = new AsyncDependenciesBlock(req.name, parent);
        block.dependencies = deserializeDependencies(req.dependencies);
        block.variables = deserializeVariables(req.variables);
        deserializeBlocks(req.blocks, block);
        return block;
      }
    })
    .filter(Boolean)
    .forEach(function(block) {
      parent.addBlock(block);
    });
  }
  this.dependencies = deserializeDependencies(cacheItem.dependencies);
  this.variables = deserializeVariables(cacheItem.variables);
  deserializeBlocks(cacheItem.blocks, this);
}
CacheModule.prototype = Object.create(RawModule.prototype);
CacheModule.prototype.constructor = CacheModule;
function needRebuild(buildTimestamp, fileDependencies, contextDependencies, fileTimestamps, contextTimestamps) {
  var timestamp = 0;
  fileDependencies.forEach(function(file) {
    var ts = fileTimestamps[file];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  contextDependencies.forEach(function(context) {
    var ts = contextTimestamps[context];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  return timestamp >= buildTimestamp;
}
CacheModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
  return needRebuild(this.buildTimestamp, this.fileDependencies, this.contextDependencies, fileTimestamps, contextTimestamps);
};

function HardSourceWebpackPlugin(options) {
  this.options = options;
}

module.exports = HardSourceWebpackPlugin;
HardSourceWebpackPlugin.prototype.apply = function(compiler) {
  var options = this.options;
  var active = true;
  var cacheDirName = options.cacheDirectory;
  if (!cacheDirName) {
    console.error('HardSourceWebpackPlugin requires a cacheDirectory setting.');
    active = false;
    return;
  }
  var cacheDirPath = path.join(compiler.options.context, cacheDirName);
  var resolveCachePath = path.join(cacheDirPath, 'resolve.json');

  var resolveCache = {};
  var moduleCache = {};
  var moduleCacheLoading = [];

  var fileTimestamps = {};

  compiler.plugin('after-plugins', function() {
    if (
      !compiler.recordsInputPath ||
      compiler.recordsInputPath !== compiler.recordsOutputPath
    ) {
      console.error('HardSourceWebpackPlugin requires recordsPath to be set.');
      active = false;
    }
  });

  compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
    if (!active) {return cb();}
    mkdirp.sync(cacheDirPath);
    try {
      resolveCache = JSON.parse(fs.readFileSync(resolveCachePath, 'utf8'));
    }
    catch (e) {}
    var start = Date.now();

    moduleCacheLoading = [];

    async.each(fs.readdirSync(cacheDirPath), function(name, cb) {
      if (name === 'records.json') {return cb();}
      if (name === 'resolve.json') {return cb();}
      fs.readFile(path.join(cacheDirPath, name), 'utf8', function(err, json) {
        if (err) {return cb();}
        var subcache = JSON.parse(json);
        var key = Object.keys(subcache)[0];
        moduleCache[key] = subcache[key];
        cb();
      });
    }, function() {
      var loading = moduleCacheLoading;
      moduleCacheLoading = null;
      for (var i = 0; i < loading.length; i++) {
        loading[i]();
      }
      cb();
    });
  });

  compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
    if (!active) {return cb();}

    if (!compiler.inputFileSystem) {
      // try {
      //   compiler.compiler.records = JSON.parse(fs.readFileSync(recordsPath, 'utf8'));
      // }
      // catch (e) {}
    }
    else {
      // compiler.recordsInputPath = compiler.recordsOutputPath = recordsPath;
    }

    if(!moduleCache.fileDependencies) return cb();
    // var fs = compiler.inputFileSystem;
    var fileTs = compiler.fileTimestamps = fileTimestamps = {};
    async.forEach(moduleCache.fileDependencies, function(file, callback) {
      fs.stat(file, function(err, stat) {
        if(err) {
          if(err.code === "ENOENT") return callback();
          return callback(err);
        }

        fileTs[file] = stat.mtime || Infinity;
        callback();
      });
    }, cb);
  });

  compiler.plugin('compilation', function(compilation, params) {
    if (!active) {return;}

    compilation.fileTimestamps = fileTimestamps;

    compilation.dependencyFactories.set(RawModuleDependency, params.normalModuleFactory);
    compilation.dependencyTemplates.set(RawModuleDependency, new RawModuleDependencyTemplate);

    compilation.dependencyFactories.set(ContextDependency, params.contextModuleFactory);
    compilation.dependencyTemplates.set(ContextDependency, new RawModuleDependencyTemplate);

    compilation.dependencyFactories.set(NullDependency, new NullFactory());
    compilation.dependencyTemplates.set(NullDependency, new NullDependencyTemplate);

    params.normalModuleFactory.plugin('resolver', function(fn) {
      return function(request, cb) {
        // if (request.request.indexOf('index.html') !== -1) {
        //   console.log('resolve cache', request.request);
        // }
        var cacheId = JSON.stringify([request.context, request.request]);
        if (resolveCache[cacheId]) {
          var result = Object.assign({}, resolveCache[cacheId]);
          result.dependencies = request.dependencies;
          result.parser = compilation.compiler.parser;
          return cb(null, result);
        }

        var originalRequest = request;
        return fn.call(null, request, function(err, request) {
          if (err) {
            return cb(err);
          }
          if (!request.source) {
            resolveCache[cacheId] = Object.assign({}, request, {
              parser: null,
              dependencies: null,
            });
          }
          cb.apply(null, arguments);
        });
      };
    });

    params.normalModuleFactory.plugin('resolver', function(fn) {
      return function(request, cb) {
        fn.call(null, request, function(err, result) {
          if (err) {return cb(err);}
          // else if (moduleCacheLoading) {
          //   return moduleCacheLoading.push(function() {
          //     var cacheItem = moduleCache[result.request];
          //     if (!needRebuild(
          //       cacheItem.buildTimestamp,
          //       cacheItem.fileDependencies,
          //       // cacheItem.contextDependencies,
          //       [],
          //       fileTimestamps,
          //       compiler.contextTimestamps
          //     )) {
          //       var module = new CacheModule(cacheItem);
          //       return cb(null, module);
          //     }
          //     else {
          //       result.parser = compilation.compiler.parser;
          //       return cb(null, result);
          //     }
          //   });
          // }
          else if (moduleCache[result.request]) {
            var cacheItem = moduleCache[result.request];
            if (!needRebuild(
              cacheItem.buildTimestamp,
              cacheItem.fileDependencies,
              cacheItem.contextDependencies,
              // [],
              fileTimestamps,
              compiler.contextTimestamps
            )) {
              var module = new CacheModule(cacheItem);
              return cb(null, module);
            }
          }
          return cb(null, result);
        });
      };
    });
  });

  compiler.plugin('after-compile', function(compilation, cb) {
    if (!active) {return cb();}

    var startCacheTime = Date.now();
    fs.writeFileSync(resolveCachePath, JSON.stringify(resolveCache), 'utf8');

    function serializeDependencies(deps) {
      return deps
      .map(function(dep) {
        return {
          contextDependency: dep instanceof ContextDependency,
          constDependency: dep instanceof ConstDependency,
          request: dep.request,
          recursive: dep.recursive,
          regExp: dep.regExp ? dep.regExp.source : null,
        };
      })
      .filter(function(req) {
        return req.request || req.constDependency;
      });
    }
    function serializeVariables(vars) {
      return vars.map(function(variable) {
        return {
          name: variable.name,
          expression: variable.expression,
          dependencies: serializeDependencies(variable.dependencies),
        }
      });
    }
    function serializeBlocks(blocks) {
      return blocks.map(function(block) {
        return {
          async: block instanceof AsyncDependenciesBlock,
          name: block.chunkName,
          dependencies: serializeDependencies(block.dependencies),
          variables: serializeVariables(block.variables),
          blocks: serializeBlocks(block.blocks),
        };
      });
    }
    function serializeHashContent(module) {
      var content = [];
      module.updateHash({
        update: function(str) {
          content.push(str);
        },
      });
      return content.join('');
    }

    var devtoolOptions;
  	if(compiler.options.devtool && (compiler.options.devtool.indexOf("sourcemap") >= 0 || compiler.options.devtool.indexOf("source-map") >= 0)) {
  		var hidden = compiler.options.devtool.indexOf("hidden") >= 0;
  		var inline = compiler.options.devtool.indexOf("inline") >= 0;
  		var evalWrapped = compiler.options.devtool.indexOf("eval") >= 0;
  		var cheap = compiler.options.devtool.indexOf("cheap") >= 0;
  		var moduleMaps = compiler.options.devtool.indexOf("module") >= 0;
  		var noSources = compiler.options.devtool.indexOf("nosources") >= 0;
  		var legacy = compiler.options.devtool.indexOf("@") >= 0;
  		var modern = compiler.options.devtool.indexOf("#") >= 0;
  		var comment = legacy && modern ? "\n/*\n//@ sourceMappingURL=[url]\n//# sourceMappingURL=[url]\n*/" :
  			legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" :
  			modern ? "\n//# sourceMappingURL=[url]" :
  			null;
      devtoolOptions = {
  			filename: inline ? null : compiler.options.output.sourceMapFilename,
  			moduleFilenameTemplate: compiler.options.output.devtoolModuleFilenameTemplate,
  			fallbackModuleFilenameTemplate: compiler.options.output.devtoolFallbackModuleFilenameTemplate,
  			append: hidden ? false : comment,
  			module: moduleMaps ? true : cheap ? false : true,
  			columns: cheap ? false : true,
  			lineToLine: compiler.options.output.devtoolLineToLine,
  			noSources: noSources,
  		};
  	}

    moduleCache.fileDependencies = compilation.fileDependencies;
    fs.writeFileSync(
      path.join(cacheDirPath, 'file-dependencies.json'),
      JSON.stringify({fileDependencies: compilation.fileDependencies}),
      'utf8'
    );

    async.forEach(compilation.modules, function(module, cb) {
      if (module.request && module.cacheable && !(module instanceof CacheModule)) {
        var source = module.source(
          compilation.dependencyTemplates,
          compilation.moduleTemplate.outputOptions,
          compilation.moduleTemplate.requestShortener
        );
        moduleCache[module.request] = {
          moduleId: module.id,
          context: module.context,
          request: module.request,
          identifier: module.identifier(),
          assets: Object.keys(module.assets || {}).reduce(function(carry, key) {
            carry[key] = module.assets[key].source();
            return carry;
          }, {}),
          buildTimestamp: module.buildTimestamp,

          source: source.source(),
          map: devtoolOptions && source.map(devtoolOptions),
          hashContent: serializeHashContent(module),

          dependencies: serializeDependencies(module.dependencies),
          variables: serializeVariables(module.variables),
          blocks: serializeBlocks(module.blocks),

          fileDependencies: module.fileDependencies,
          contextDependencies: module.contextDependencies,
        };

        mkdirp.sync(cacheDirPath);
        var hashName = crypto.createHash('sha1')
        .update(module.request).digest().hexSlice();
        return fs.writeFile(
          path.join(cacheDirPath, hashName + '.json'),
          JSON.stringify({[module.request]: moduleCache[module.request]}),
          'utf8',
          cb
        );
      }
      cb();
    }, cb);
    //
    // console.log('cache out', Date.now() - startCacheTime);
    // cb();
  });
  // Ensure records are stored inbetween runs of memory-fs using
  // webpack-dev-middleware.
  compiler.plugin('done', function() {
    if (!active) {return;}

    fs.writeFileSync(
      path.resolve(compiler.options.context, compiler.recordsOutputPath),
      JSON.stringify(compiler.records, null, 2),
      'utf8'
    );
  });
};
<|endoftext|>


<commit_before>module.exports = {
  '-1' : 'system busy, retry later',
  0    : 'success',
  1    : 'internal error, contact us',

  10001: 'require appKey',
  10002: 'require appSecret',
  10003: 'require deviceId',
  10004: 'invalid appKey',
  10005: 'invalid appSecret',
  10006: 'failed to create/update device, contact us',
  10007: 'invalid token',
  10008: 'token is expired',
  10009: 'failed to generate token, contact us',
  10010: 'require token',
  10011: 'require uploaded data file',
  11001: 'require username',
  11002: 'require password',
  11003: 'user not exist',
  11004: 'password not match',
  11005: 'failed to generate token, contact us',
  11006: 'failed to create user',
  11007: 'failed to hash password',
  11008: 'failed to save user, please check if required field is correct',
  11009: 'failed to save file',
  11010: 'failed to delete file',
  11011: 'file not exist',
  11012: 'error when read file',
  11013: 'failed to create poi import task',
  11014: 'require clientKey',
  11015: 'require clientSecret',
  11016: 'client not exist',
  11017: 'invalid clientKey',
  11018: 'invalid clientSecret',
  40001: 'failed to create device, contact us',
  40002: 'failed to get created device, contact us',
  40003: 'failed to update device, contact us',
  40004: 'failed to get updated device, contact us',
  40005: 'failed to queue poi import job'
};<commit_msg>add more error codes<commit_after>module.exports = {
  '-1' : 'system busy, retry later',
  0    : 'success',
  1    : 'internal error, contact us',

  10001: 'require appKey',
  10002: 'require appSecret',
  10003: 'require deviceId',
  10004: 'invalid appKey',
  10005: 'invalid appSecret',
  10006: 'failed to create/update device, contact us',
  10007: 'invalid token',
  10008: 'token is expired',
  10009: 'failed to generate token, contact us',
  10010: 'require token',
  10011: 'require uploaded data file',
  11001: 'require username',
  11002: 'require password',
  11003: 'user not exist',
  11004: 'password not match',
  11005: 'failed to generate token, contact us',
  11006: 'failed to create user',
  11007: 'failed to hash password',
  11008: 'failed to save user, please check if required field is correct',
  11009: 'failed to save file',
  11010: 'failed to delete file',
  11011: 'file not exist',
  11012: 'error when read file',
  11013: 'failed to create poi import task',
  11014: 'require clientKey',
  11015: 'require clientSecret',
  11016: 'client not exist',
  11017: 'invalid clientKey',
  11018: 'invalid clientSecret',
  40001: 'failed to create device, contact us',
  40002: 'failed to get created device, contact us',
  40003: 'failed to update device, contact us',
  40004: 'failed to get updated device, contact us',
  40005: 'failed to queue poi import job',
  40006: 'failed to find pois'
};<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;
var EventEmitter = require('events').EventEmitter;
module.exports = function(cmd, args) {
   var self = new EventEmitter();
   var child = spawn(cmd, args);
   var pauserefcount = 0;
   child.stdin.resume();
   child.stdout.resume();
   self.pause = function() {
       pauserefcount++;
       if (pauserefcount > 1)
          return;
       child.kill('SIGTSTP');
       self.paused = true;
   };
   self.resume = function() {
    console.log(cmd + '.resume');
       pauserefcount--;
       if (pauserefcount>0)
         return;
       if (pauserefcount<0)
         throw new Error('resume() is called without calling pause()');
       child.kill('SIGCONT');
       self.paused = false;
   };
   child.stdout.on('data', function(data) {
       console.log(cmd + '.data', data);
       self.emit('data', data); // self.emit.bind(self, 'data') ???
   });
   child.on('exit', function(code, signal) {
       if (code === 0)
           self.emit('end');
       //else
       //    console.log(code, signal);
   });
   self.write = function(data) {
       console.log(cmd + '.write', data);
       return child.stdin.write(data);
   };
   child.stdin.on('drain', function() {
       self.emit('drain');
   });
   self.end = function() {
       child.kill('SIGINT');
   };
   self.pipe = function(dest, opts) {
       dest.on('drain', function() {
           if (self.paused)
               self.resume();
       });
       self.on('data', function(data) {
           var buffered = !dest.write(data);
           if (buffered & !self.paused)
               self.pause();
       });

       if (!opts || (opts && opts.end === true) || (opts && typeof opts.end === 'undefined'))
           self.on('end', function() {
               dest.end();
           });

       self.emit('pipe');
       return dest;
   };
   return self;
};
<commit_msg>Added connect and error events<commit_after>var spawn = require('child_process').spawn;
var EventEmitter = require('events').EventEmitter;
module.exports = function(cmd, args) {
   var self = new EventEmitter();
   var child = spawn(cmd, args);
   var pauserefcount = 0;
   var error = false;
   child.stdin.resume();
   child.stdout.resume();

   setImmediate(function() {
       if(! error)
           self.emit("connect");
   });
   self.pause = function() {
       pauserefcount++;
       if (pauserefcount > 1)
          return;
       child.kill('SIGTSTP');
       self.paused = true;
   };
   self.resume = function() {
    console.log(cmd + '.resume');
       pauserefcount--;
       if (pauserefcount>0)
         return;
       if (pauserefcount<0)
         throw new Error('resume() is called without calling pause()');
       child.kill('SIGCONT');
       self.paused = false;
   };
   child.stdout.on('data', function(data) {
       console.log(cmd + '.data', data);
       self.emit('data', data); // self.emit.bind(self, 'data') ???
   });
   child.on('exit', function(code, signal) {
       if (code === 0)
           self.emit('end');
       //else
       //    console.log(code, signal);
   });
   child.on("error", function(err) {
       error = true;
       self.emit("error", err);
   });
   self.write = function(data) {
       console.log(cmd + '.write', data);
       return child.stdin.write(data);
   };
   child.stdin.on('drain', function() {
       self.emit('drain');
   });
   self.end = function() {
       child.kill('SIGINT');
   };
   self.pipe = function(dest, opts) {
       dest.on('drain', function() {
           if (self.paused)
               self.resume();
       });
       self.on('data', function(data) {
           var buffered = !dest.write(data);
           if (buffered & !self.paused)
               self.pause();
       });

       if (!opts || (opts && opts.end === true) || (opts && typeof opts.end === 'undefined'))
           self.on('end', function() {
               dest.end();
           });

       self.emit('pipe');
       return dest;
   };
   return self;
};
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var redis = require("redis"),
    client = redis.createClient();

app.use(bodyParser.json());

app.get('/', function (req, res) {
  res.send('Welcome to PAW!');
});

app.get('/dogs', function (req, res) {
   client.keys('*', function (err, keys) {
     res.json({dogs: keys});
   });
});

app.post('/event', function (req, res) {
  dogName = req.body.event.dog;
  status = req.body.event.inOffice;
  console.log('Request: ', req.body.event);

  // Set key in redis store
  client.set(dogName, status);

  // Set the key to expire after 5 minutes
  client.expire(dogName, 60 * 5);

  res.json({status: 'success'});
});

// Redis-specific code and configuration
client.on("error", function (err) {
    console.log("Error " + err);
});

// Starting the express server
var server = app.listen(3000, '0.0.0.0', function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('paw-api listening at http://%s:%s', host, port);
});
<commit_msg>environment variable for redis url<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var redisURL = process.env.REDIS_URL;
var redis = require("redis"),
    client = redis.createClient(redisURL);

app.use(bodyParser.json());

app.get('/', function (req, res) {
  res.send('Welcome to PAW!');
});

app.get('/dogs', function (req, res) {
   client.keys('*', function (err, keys) {
     res.json({dogs: keys});
   });
});

app.post('/event', function (req, res) {
  dogName = req.body.event.dog;
  status = req.body.event.inOffice;
  console.log('Request: ', req.body.event);

  // Set key in redis store
  client.set(dogName, status);

  // Set the key to expire after 5 minutes
  client.expire(dogName, 60 * 5);

  res.json({status: 'success'});
});

// Redis-specific code and configuration
client.on("error", function (err) {
    console.log("Error " + err);
});

// Starting the express server
var server = app.listen(3000, '0.0.0.0', function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('paw-api listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>var _param = require('./param.json');
var _os = require('os');
var _fs = require('fs');
var _sysconf = require('sysconf');

function silent(fnc)
{
	try
	{
		return fnc();
	}
	catch(ex)
	{
		return null;
	}
}

// Returns process id or 0 if not found, -1 if ambiguous, sets reason
var reason;
function findProcId()
{
	// Get all proc id's
	var procs = _fs.readdirSync('/proc').filter(function(e) { return !isNaN(parseInt(e)); });
	var pidResult = 0;

	var hit;

	procs.every(function(pid)
	{
		var stat = _fs.readFileSync('/proc/' + pid + '/stat', 'utf8').split(' ');
		var cwd = silent(function() { return _fs.readlinkSync('/proc/' + pid + '/cwd'); });
		var path = silent(function() { return _fs.readlinkSync('/proc/' + pid + '/exe'); });

		var re;

		var prc = {
			name : stat[1].substr(1, stat[1].length - 2),
			path : path || '',
			cwd : cwd || ''
		};

		if (_param.processName)
		{
			re = new RegExp(_param.processName);
			if (!re.test(prc.name))
				return true;
		}
		if (_param.processPath)
		{
			re = new RegExp(_param.processPath);
			if (!re.test(prc.path))
				return true;
		}
		if (_param.processCwd)
		{
			re = new RegExp(_param.processCwd);
			if (!re.test(prc.cwd))
				return true;
		}

		// Got a hit, make sure not ambiguous
		if (pidResult)
		{
			reason = 'process ambiguity: ' + JSON.stringify(prc) + ' is too similar to ' + JSON.stringify(hit);
			pidResult = -1;
			return false;
		}
		else
		{
			hit = prc;
			pidResult = pid;
			return true;
		}
	});

	if (!pidResult)
		reason = 'the process was not found';

	return pidResult;
}

var _pollInterval = _param.pollInterval || 1000;
var _source = _param.source || _os.hostname();
var _pagesize = _sysconf.get(_sysconf._SC_PAGESIZE);

var _pid;
var _notified;

function poll()
{
	if (!_pid)
	{
		_pid = findProcId();

		if (_pid <= 0)
		{
			// Couldn't locate, spit out an error once and keep trying
			if (!_notified)
			{
				_notified = true;
				console.error('Unable to locate process, ' + reason);
			}
		}
		else
			_notified = false;
	}

	if (_pid)
	{
		try
		{
			var memuse = _fs.readFileSync('/proc/' + _pid + '/stat', 'utf8').split(' ')[23] * _pagesize;

			console.log('%s %d', _source, memuse);

		}
		catch(ex)
		{
			if (ex.message.indexOf('No such process') != -1)
				_pid = 0;
			else
				console.error('Unexpected error: ' + ex.message);

			console.log('%s 0', _source);
		}
	}
	else
		console.log('%s 0', _source);

	setTimeout(poll, _pollInterval);
}

poll();

<commit_msg>proper output<commit_after>var _param = require('./param.json');
var _os = require('os');
var _fs = require('fs');
var _sysconf = require('sysconf');

function silent(fnc)
{
	try
	{
		return fnc();
	}
	catch(ex)
	{
		return null;
	}
}

// Returns process id or 0 if not found, -1 if ambiguous, sets reason
var reason;
function findProcId()
{
	// Get all proc id's
	var procs = _fs.readdirSync('/proc').filter(function(e) { return !isNaN(parseInt(e)); });
	var pidResult = 0;

	var hit;

	procs.every(function(pid)
	{
		var stat = _fs.readFileSync('/proc/' + pid + '/stat', 'utf8').split(' ');
		var cwd = silent(function() { return _fs.readlinkSync('/proc/' + pid + '/cwd'); });
		var path = silent(function() { return _fs.readlinkSync('/proc/' + pid + '/exe'); });

		var re;

		var prc = {
			name : stat[1].substr(1, stat[1].length - 2),
			path : path || '',
			cwd : cwd || ''
		};

		if (_param.processName)
		{
			re = new RegExp(_param.processName);
			if (!re.test(prc.name))
				return true;
		}
		if (_param.processPath)
		{
			re = new RegExp(_param.processPath);
			if (!re.test(prc.path))
				return true;
		}
		if (_param.processCwd)
		{
			re = new RegExp(_param.processCwd);
			if (!re.test(prc.cwd))
				return true;
		}

		// Got a hit, make sure not ambiguous
		if (pidResult)
		{
			reason = 'process ambiguity: ' + JSON.stringify(prc) + ' is too similar to ' + JSON.stringify(hit);
			pidResult = -1;
			return false;
		}
		else
		{
			hit = prc;
			pidResult = pid;
			return true;
		}
	});

	if (!pidResult)
		reason = 'the process was not found';

	return pidResult;
}

var _pollInterval = _param.pollInterval || 1000;
var _source = _param.source || _os.hostname();
var _pagesize = _sysconf.get(_sysconf._SC_PAGESIZE);

var _pid;
var _notified;

function poll()
{
	if (!_pid)
	{
		_pid = findProcId();

		if (_pid <= 0)
		{
			// Couldn't locate, spit out an error once and keep trying
			if (!_notified)
			{
				_notified = true;
				console.error('Unable to locate process, ' + reason);
			}
		}
		else
			_notified = false;
	}

	if (_pid)
	{
		try
		{
			var memuse = _fs.readFileSync('/proc/' + _pid + '/stat', 'utf8').split(' ')[23] * _pagesize;

			console.log('MEM_PROCESS %d %s', memuse, _source);

		}
		catch(ex)
		{
			if (ex.message.indexOf('No such process') != -1)
				_pid = 0;
			else
				console.error('Unexpected error: ' + ex.message);

			console.log('%s 0', _source);
		}
	}
	else
		console.log('%s 0', _source);

	setTimeout(poll, _pollInterval);
}

poll();

<|endoftext|>


<commit_before>var path = require('path');

module.exports = {
    // Options that can't be extend
    'configFile': 'book',
    'generator': 'website',
    'extension': null,

    // Book metadats (somes are extracted from the README by default)
    'title': null,
    'description': null,
    'isbn': null,
    'language': 'en',
    'direction': null,
    'author': null,

    // version of gitbook to use
    'gitbook': '*',

    // Structure
    'structure': {
        'langs': 'LANGS.md',
        'readme': 'README.md',
        'glossary': 'GLOSSARY.md',
        'summary': 'SUMMARY.md'
    },

    // CSS Styles
    'styles': {
        'website': 'styles/website.css',
        'print': 'styles/print.css',
        'ebook': 'styles/ebook.css',
        'pdf': 'styles/pdf.css',
        'mobi': 'styles/mobi.css',
        'epub': 'styles/epub.css'
    },

    // Plugins list, can contain '-name' for removing default plugins
    'plugins': [],

    // Global configuration for plugins
    'pluginsConfig': {},

    // Variables for templating
    'variables': {},

    // Set another theme with your own layout
    // It's recommended to use plugins or add more options for default theme, though
    // See https://github.com/GitbookIO/gitbook/issues/209
    'theme': path.resolve(__dirname, '../theme'),

    // Links in template (null: default, false: remove, string: new value)
    'links': {
        // Custom links at top of sidebar
        'sidebar': {
            // 'Custom link name': 'https://customlink.com'
        },

        // Sharing links
        'sharing': {
            'google': null,
            'facebook': null,
            'twitter': null,
            'weibo': null,
            'all': null
        }
    },

    // Options for PDF generation
    'pdf': {
        // Add toc at the end of the file
        'toc': true,

        // Add page numbers to the bottom of every page
        'pageNumbers': false,

        // Font for the file content
        'fontSize': 12,
        'fontFamily': 'Helvetica',

        // Paper size for the pdf
        // Choices are [u’a0’, u’a1’, u’a2’, u’a3’, u’a4’, u’a5’, u’a6’, u’b0’, u’b1’, u’b2’, u’b3’, u’b4’, u’b5’, u’b6’, u’legal’, u’letter’]
        'paperSize': 'a4',

        // How to mark detected chapters.
        // Choices are “pagebreak”, “rule”, 'both' or “none”.
        'chapterMark' : 'pagebreak',

        // An XPath expression. Page breaks are inserted before the specified elements.
        // To disable use the expression: '/'
        'pageBreaksBefore': '/',

        // Margin (in pts)
        // Note: 72 pts equals 1 inch
        'margin': {
            'right': 62,
            'left': 62,
            'top': 56,
            'bottom': 56
        },

        // Header HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
        'headerTemplate': null,

        // Footer HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
        'footerTemplate': null
    }
};
<commit_msg>Use Arial as default font<commit_after>var path = require('path');

module.exports = {
    // Options that can't be extend
    'configFile': 'book',
    'generator': 'website',
    'extension': null,

    // Book metadats (somes are extracted from the README by default)
    'title': null,
    'description': null,
    'isbn': null,
    'language': 'en',
    'direction': null,
    'author': null,

    // version of gitbook to use
    'gitbook': '*',

    // Structure
    'structure': {
        'langs': 'LANGS.md',
        'readme': 'README.md',
        'glossary': 'GLOSSARY.md',
        'summary': 'SUMMARY.md'
    },

    // CSS Styles
    'styles': {
        'website': 'styles/website.css',
        'print': 'styles/print.css',
        'ebook': 'styles/ebook.css',
        'pdf': 'styles/pdf.css',
        'mobi': 'styles/mobi.css',
        'epub': 'styles/epub.css'
    },

    // Plugins list, can contain '-name' for removing default plugins
    'plugins': [],

    // Global configuration for plugins
    'pluginsConfig': {},

    // Variables for templating
    'variables': {},

    // Set another theme with your own layout
    // It's recommended to use plugins or add more options for default theme, though
    // See https://github.com/GitbookIO/gitbook/issues/209
    'theme': path.resolve(__dirname, '../theme'),

    // Links in template (null: default, false: remove, string: new value)
    'links': {
        // Custom links at top of sidebar
        'sidebar': {
            // 'Custom link name': 'https://customlink.com'
        },

        // Sharing links
        'sharing': {
            'google': null,
            'facebook': null,
            'twitter': null,
            'weibo': null,
            'all': null
        }
    },

    // Options for PDF generation
    'pdf': {
        // Add toc at the end of the file
        'toc': true,

        // Add page numbers to the bottom of every page
        'pageNumbers': false,

        // Font for the file content
        'fontSize': 12,
        'fontFamily': 'Arial',

        // Paper size for the pdf
        // Choices are [u’a0’, u’a1’, u’a2’, u’a3’, u’a4’, u’a5’, u’a6’, u’b0’, u’b1’, u’b2’, u’b3’, u’b4’, u’b5’, u’b6’, u’legal’, u’letter’]
        'paperSize': 'a4',

        // How to mark detected chapters.
        // Choices are “pagebreak”, “rule”, 'both' or “none”.
        'chapterMark' : 'pagebreak',

        // An XPath expression. Page breaks are inserted before the specified elements.
        // To disable use the expression: '/'
        'pageBreaksBefore': '/',

        // Margin (in pts)
        // Note: 72 pts equals 1 inch
        'margin': {
            'right': 62,
            'left': 62,
            'top': 56,
            'bottom': 56
        },

        // Header HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
        'headerTemplate': null,

        // Footer HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
        'footerTemplate': null
    }
};
<|endoftext|>


<commit_before>'use strict'

function ReInterval (callback, interval, args) {
  var self = this;

  this._callback = callback;
  this._args = args;

  this._interval = setInterval(callback, interval, this._args);

  this.reschedule = function (interval) {

    var now = Date.now();
    if (self._interval)
      clearInterval(self._interval);
    self._interval = setInterval(self._callback, interval, self._args);
  };

  this.clear = function () {
    if (self._interval) {
      clearInterval(self._interval);
      self._interval = undefined;
      self._callback = undefined;
      self._args = undefined;
    }
  };
}

function reInterval () {
  if (typeof arguments[0] !== 'function')
    throw new Error('callback needed');
  if (typeof arguments[1] !== 'number')
    throw new Error('interval needed');

  var args;

  if (arguments.length > 0) {
    args = new Array(arguments.length - 2);

    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i + 2];
    }
  }

  return new ReInterval(arguments[0], arguments[1], args);
}

module.exports = reInterval;
<commit_msg>Update Reschedule and Clear functions, create Destroy function.<commit_after>'use strict'

function ReInterval (callback, interval, args) {
  var self = this;

  this._callback = callback;
  this._args = args;

  this._interval = setInterval(callback, interval, this._args);

  this.reschedule = function (interval) {
    // if no interval entered, use the interval passed in on creation
    if (!interval)
      interval = self._interval;

    if (self._interval)
      clearInterval(self._interval);
    self._interval = setInterval(self._callback, interval, self._args);
  };

  this.clear = function () {
    if (self._interval) {
      clearInterval(self._interval);
      self._interval = undefined;
    }
  };

  this.destroy = function () {
    if (self._interval) {
      clearInterval(self._interval);
    }
    self._callback = undefined;
    self._interval = undefined;
    self._args = undefined;
  };
}

function reInterval () {
  if (typeof arguments[0] !== 'function')
    throw new Error('callback needed');
  if (typeof arguments[1] !== 'number')
    throw new Error('interval needed');

  var args;

  if (arguments.length > 0) {
    args = new Array(arguments.length - 2);

    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i + 2];
    }
  }

  return new ReInterval(arguments[0], arguments[1], args);
}

module.exports = reInterval;
<|endoftext|>


<commit_before>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet, injectGlobal, css } from 'styled-components';
import { normalize } from 'polished';

// See https://www.styled-components.com/docs/advanced#nextjs

// Add global styles
// eslint-disable-next-line no-unused-expressions
const globalStyles = css`
  ${normalize(true)} *, *:before, *:after {
    box-sizing: inherit;
  }

  html {
    box-sizing: border-box;
    font-size: 16px;
  }

  body {
    margin: 0;
    padding: 0;
    font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI',
      'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
      'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
    background: #eff0f2;
    color: #444444;

    a {
      color: #20588f;
    }

    small {
      color: #8a6666;
    }
  }
`;

// eslint-disable-next-line no-unused-expressions
injectGlobal`
  ${globalStyles}
`;

class GDLDocument extends Document {
  static async getInitialProps(context) {
    // Wait for the language on the request (see server.js) so we can set the lang attribute on the html tag
    const props = await super.getInitialProps(context);
    const { req: { language } } = context;
    return {
      ...props,
      language,
    };
  }
  render() {
    const sheet = new ServerStyleSheet();
    const main = sheet.collectStyles();
    const styleTags = sheet.getStyleElement();
    return (

          <title>Global Digital Library</title>
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {styleTags}

{main}

          <NextScript />

    );
  }
}

export { GDLDocument as default, globalStyles };
<commit_msg>Fix SSR for styled-components<commit_after>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet, injectGlobal, css } from 'styled-components';
import { normalize } from 'polished';

// See https://www.styled-components.com/docs/advanced#nextjs

// Add global styles
// eslint-disable-next-line no-unused-expressions
const globalStyles = css`
  ${normalize(true)} *, *:before, *:after {
    box-sizing: inherit;
  }

  html {
    box-sizing: border-box;
    font-size: 16px;
  }

  body {
    margin: 0;
    padding: 0;
    font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI',
      'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
      'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
    background: #eff0f2;
    color: #444444;

    a {
      color: #20588f;
    }

    small {
      color: #8a6666;
    }
  }
`;

// eslint-disable-next-line no-unused-expressions
injectGlobal`
  ${globalStyles}
`;

class GDLDocument extends Document {
  static getInitialProps({ renderPage, req }) {
    const sheet = new ServerStyleSheet();

    const page = renderPage(App => props =>
      sheet.collectStyles(<App {...props} />),
    );

    const styleTags = sheet.getStyleElement();

    return {
      ...page,
      language: req.language,
      styleTags,
    };
  }

  render() {
    return (

          <title>Global Digital Library</title>
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {this.props.styleTags}

          <NextScript />

    );
  }
}

export { GDLDocument as default, globalStyles };
<|endoftext|>


<commit_before>"use strict";

var request = require('request');
var cheerio = require('cheerio');
var async   = require('async');
var moment  = require('moment');
var twitter = require('simple-twitter');
var twitkeys = require('./twitterkeys');

/* Process:

 * Fetch event data
 * Get events for tomorrow
 * Assign a fucked-uppery to it
 * Tweet or Email it
*/

main();

function main () {
    fetch_event_data();
}

function fetch_event_data () {
    async.parallel([
        fetch_amphitheatre,
        fetch_skydome,
        fetch_acc,
        fetch_bmo_field,
        // fetch_fort_york,
        // fetch_road_closures,
    ],
    process_results
    )
}

function fetch_amphitheatre (cb) {
    var url = 'http://www.livenation.com/venues/14878/molson-canadian-amphitheatre';

    var tomorrow_format = moment().add('days', 1).format('YYYY-MM-DD');

    request.get(url, function (err, r, body) {
        if (err) {
            return cb("Error fetching amphitheatre: " + err);
        }
        var $ = cheerio.load(body, {lowerCaseTags: true});

        var entries = $('ul.showlist.upcoming li');
        var show = null;
        entries.each(function (i, el) {
            if (show) return;
            var $el = $(el);
            var attr = $el.attr('data-local-start-time');
            if (attr.indexOf(tomorrow_format) != -1) {
                show = $el.find('div.show').text().trim();
            }
        });
        if (show) {
            console.log("Found show: " + show);
            return cb(null, show);
        }
        console.log("Found no shows matching " + tomorrow_format);
        return cb();
    })
}

function fetch_ticketmaster (venue_id, cb) {
    var url = 'http://www.ticketmaster.ca/json/search/event?vid=' + venue_id;

    var tomorrow_format = moment().add('days', 1).format('YYYY-MM-DD');

    request.get(url, {json: true}, function (err, r, data) {
        if (err) {
            return cb("Error fetching ticketmaster venue: " + venue_id + ": " + err);
        }
        // console.log(data.response.docs);
        var events = data.response.docs;
        var show = null;
        for (var i=0; i<events.length; i++) {
            if (events[i].EventDate.indexOf(tomorrow_format) != -1) {
                show = events[i].EventName;
                break;
            }
        }
        return cb(null, show);
    });
}

function fetch_skydome (cb) {
    fetch_ticketmaster(131114, cb);
}

function fetch_acc (cb) {
    fetch_ticketmaster(131157, cb);
}

function fetch_bmo_field (cb) {
    fetch_ticketmaster(131713, cb);
}

function fetch_fort_york (cb) {
    var url = 'http://www.fortyork.ca/news-a-events/events.html';

    return cb();
}

function fetch_road_closures (cb) {
    return cb();
}

var fuckage = [
    'probably fine',
    'a bit shitty',
    'shitty',
    'fucking awful',
    'a fucking parking lot',
];

var reasons = [
    'Amp', 'Sky', 'ACC', 'BMO', 'FTY', 'CLO',
];

function process_results (err, results) {
    console.log("Results: ", results);
    var found = 0;
    var reason = '';
    for (var i=0; i<results.length; i++) {
        if (results[i]) found++;
        if (results[i]) reason += reasons[i] + ' '
    }

    if (found > 4) found = 4;

    var tomorrow_format = moment().add('days', 1).format('ddd, MMM Do');

    var status = "On " + tomorrow_format +
                 " in the evening the Gardiner will probably be " +
                 fuckage[found];

    if (reason.length) {
        status += ' (' + reason.trim() + ')';
    }

    if (process.env.NOTWEET) {
        console.log(status);
        return;
    }

    var twit = new twitter(
        twitkeys.consumer_key,
        twitkeys.consumer_secret,
        twitkeys.access_token,
        twitkeys.access_token_secret,
        false
    );

    twit.post('statuses/update', {status: status}, function (err, data) {
        if (err) {
            return console.log("Error posting to twitter: ", err);
        }
        console.log(data);
    });
}
<commit_msg>Add the ex<commit_after>"use strict";

var request = require('request');
var cheerio = require('cheerio');
var async   = require('async');
var moment  = require('moment');
var twitter = require('simple-twitter');
var twitkeys = require('./twitterkeys');

/* Process:

 * Fetch event data
 * Get events for tomorrow
 * Assign a fucked-uppery to it
 * Tweet or Email it
*/

/* TODO
 * Fetch road closures from http://www.toronto.ca/transportation/road_info/index.htm - hard to parse as some are partial closures
 * Use weather as a heuristic
*/

var process_day = moment().add('days', 1);

main();

function main () {
    fetch_event_data();
}

function fetch_event_data () {
    async.parallel([
        fetch_amphitheatre,
        fetch_skydome,
        fetch_acc,
        fetch_bmo_field,
        fetch_fort_york,
        fetch_the_ex,
        // fetch_road_closures,
    ],
    process_results
    )
}

function fetch_the_ex (cb) {
    var start = moment("Aug 16, 2013");
    var end   = moment("Sep 2, 2013");

    if (process_day > start && process_day <= end) {
        return cb(null, "The Ex");
    }
    return cb();
}

function fetch_amphitheatre (cb) {
    var url = 'http://www.livenation.com/venues/14878/molson-canadian-amphitheatre';

    var tomorrow_format = moment().add('days', 1).format('YYYY-MM-DD');

    request.get(url, function (err, r, body) {
        if (err) {
            return cb("Error fetching amphitheatre: " + err);
        }
        var $ = cheerio.load(body, {lowerCaseTags: true});

        var entries = $('ul.showlist.upcoming li');
        var show = null;
        entries.each(function (i, el) {
            if (show) return;
            var $el = $(el);
            var attr = $el.attr('data-local-start-time');
            if (attr.indexOf(tomorrow_format) != -1) {
                show = $el.find('div.show').text().trim();
            }
        });
        if (show) {
            console.log("Found show: " + show);
            return cb(null, show);
        }
        console.log("Found no shows matching " + tomorrow_format);
        return cb();
    })
}

function fetch_ticketmaster (venue_id, cb) {
    var url = 'http://www.ticketmaster.ca/json/search/event?vid=' + venue_id;

    var tomorrow_format = moment().add('days', 1).format('YYYY-MM-DD');

    request.get(url, {json: true}, function (err, r, data) {
        if (err) {
            return cb("Error fetching ticketmaster venue: " + venue_id + ": " + err);
        }
        // console.log(data.response.docs);
        var events = data.response.docs;
        var show = null;
        for (var i=0; i<events.length; i++) {
            if (events[i].EventDate.indexOf(tomorrow_format) != -1) {
                show = events[i].EventName;
                break;
            }
        }
        return cb(null, show);
    });
}

function fetch_skydome (cb) {
    fetch_ticketmaster(131114, cb);
}

function fetch_acc (cb) {
    fetch_ticketmaster(131157, cb);
}

function fetch_bmo_field (cb) {
    fetch_ticketmaster(131713, cb);
}

function fetch_fort_york (cb) {
    var url = 'http://www.fortyork.ca/news-a-events/events.html';

    return cb();
}

function fetch_road_closures (cb) {
    return cb();
}

var fuckage = [
    'probably fine',
    'a bit shitty',
    'shitty',
    'fucking awful',
    'a fucking parking lot',
];

var reasons = [
    'Amp', 'Sky', 'ACC', 'BMO', 'FTY', 'Ex', 'CLO',
];

function process_results (err, results) {
    console.log("Results: ", results);
    var found = 0;
    var reason = '';
    for (var i=0; i<results.length; i++) {
        if (results[i]) found++;
        if (results[i]) reason += reasons[i] + ' '
    }

    if (found > 4) found = 4;

    var tomorrow_format = moment().add('days', 1).format('ddd, MMM Do');

    var status = "On " + tomorrow_format +
                 " in the evening the Gardiner will probably be " +
                 fuckage[found];

    if (reason.length) {
        status += ' (' + reason.trim() + ')';
    }

    if (process.env.NOTWEET) {
        console.log(status);
        return;
    }

    var twit = new twitter(
        twitkeys.consumer_key,
        twitkeys.consumer_secret,
        twitkeys.access_token,
        twitkeys.access_token_secret,
        false
    );

    twit.post('statuses/update', {status: status}, function (err, data) {
        if (err) {
            return console.log("Error posting to twitter: ", err);
        }
        console.log(data);
    });
}
<|endoftext|>


<commit_before>import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet()
    const page = renderPage((App) => (props) =>
      sheet.collectStyles(<App {...props} />)
    )
    const styleTags = sheet.getStyleElement()
    return { ...page, styleTags }
  }

  render() {
    return (
      <html lang="en">
        <Head>
          <title>Styled MDL</title>
          {this.props.styleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}
<commit_msg>Include roboto font in app head - DW<commit_after>import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet()
    const page = renderPage((App) => (props) =>
      sheet.collectStyles(<App {...props} />)
    )
    const styleTags = sheet.getStyleElement()
    return { ...page, styleTags }
  }

  render() {
    return (
      <html lang="en">
        <Head>
          <title>Styled MDL</title>
          <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700" rel="stylesheet" />
          {this.props.styleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}
<|endoftext|>