<commit_before>/*global require module process console*/
(function withModule(require, module, console) {
  'use strict';

  var redisDriver = require('redis')
    , redisPort = process.env.REDIS_PORT || 6379
    , redisIp = process.env.REDIS_IP || '127.0.0.1'
    , rtcPort = process.env.RTC_PORT || 9876
    , redis = redisDriver.createClient(redisPort, redisIp, {})
    , constructKeyForChannel = function constructKeyForChannel(channel, domain) {

        return 'channel-' + channel + ':' + domain;
      }
    , listenersField = (function calcListenersField() {

        return 'listeners';
      }())
    , initiatorField = (function calcInitiatorField() {

        return 'channelOwner';
      }())
    , waitersForInitiatorField = (function calcWaitersForInitiatorField() {

        return 'waitersForOwner';
      }())
    , approvedUsersField = (function calcApprovedUsersField() {

        return 'approvedUsers';
      }())
    , constructOffersField = function constructOffersField(who) {

        return who + '-offer';
      }
    , constructIceCadindatesFieldsForUser = function constructIceCadindatesFieldsForUser(who) {

        return who + '-iceCadidates';
      }
    , getInitiatorForChannel = function getInitiatorForChannel(channel) {
        var channelInitiatorKey = constructKeyForChannel(channel, initiatorField);
        return new Promise(function deferred(resolve, reject) {

          redis.get(channelInitiatorKey, function onResult(err, channelInitiator) {

            if (!err &&
              channelInitiator) {

              resolve(channelInitiator);
            } else {

              reject('Problems in retrieve initiator for channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , setInitiatorForChannel = function setInitiatorForChannel(channel, who) {
        var channelInitiatorKey = constructKeyForChannel(channel, initiatorField);
        getInitiatorForChannel(channel).catch(function onError() {

          redis.set(channelInitiatorKey, who);
        });
      }
    , removeInitiatorForChannel = function removeInitiatorForChannel(channel) {
        var channelInitiatorKey = constructKeyForChannel(channel, initiatorField);
        redis.del(channelInitiatorKey);
      }
    , addListenerForChannel = function addListenerForChannel(channel, who) {
        var listenersForChannel = constructKeyForChannel(channel, listenersField);
        getInitiatorForChannel(channel).then(function onSuccess(channelInitiator) {

          if (channelInitiator !== who) {

            redis.sadd(listenersForChannel, who);
          }
        }).catch(function onFailure() {

          redis.sadd(listenersForChannel, who);
        });
      }
    , removeListenerForChannel = function removeListenerForChannel(channel, who) {
        var listenersForChannel = constructKeyForChannel(channel, listenersField);
        redis.srem(listenersForChannel, who);
      }
    , getListenersForChannel = function getListenersForChannel(channel) {
        var listenersForChannel = constructKeyForChannel(channel, listenersField);
        return new RSVP.Promise(function deferred(resolve, reject) {

          redis.smembers(listenersForChannel, function onResult(err, channelMembers) {

            if (!err &&
              channelMembers) {

              resolve(channelMembers);
            } else {

              reject('Problems in retrieve listeners for channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , addInitiatorWaiterForChannel = function addInitiatorWaiterForChannel(channel, who) {
        var initiatorWaiterForChannel = constructKeyForChannel(channel, waitersForInitiatorField);
        redis.sadd(initiatorWaiterForChannel, who);
      }
    , removeInitiatorWaiterForChannel = function removeInitiatorWaiterForChannel(channel, who) {
        var initiatorWaiterForChannel = constructKeyForChannel(channel, waitersForInitiatorField);
        redis.srem(initiatorWaiterForChannel, who);
      }
    , getInitiatorWaitersForChannel = function getInitiatorWaitersForChannel(channel) {
        var initiatorWaiterForChannel = constructKeyForChannel(channel, waitersForInitiatorField);
        return new RSVP.Promise(function deferred(resolve, reject) {

          redis.smembers(initiatorWaiterForChannel, function onResult(err, inititatorWaiters) {

            if (!err &&
              inititatorWaiters) {

              resolve(inititatorWaiters);
            } else {

              reject('Problems in retrieve initiator waiters for channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , addApprovedUserForChannel = function addApprovedUserForChannel(channel, who) {
        var approvedUsersForChannel = constructKeyForChannel(channel, approvedUsersField);
        redis.sadd(approvedUsersForChannel, who);
      }
    , removeApprovedUserForChannel = function removeApprovedUserForChannel(channel, who) {
        var approvedUsersForChannel = constructKeyForChannel(channel, approvedUsersField);
        redis.srem(approvedUsersForChannel, who);
      }
    , getApprovedUsersForChannel = function getApprovedUsersForChannel(channel) {
        var approvedUsersForChannel = constructKeyForChannel(channel, approvedUsersField);
        return new RSVP.Promise(function deferred(resolve, reject) {

          redis.smembers(approvedUsersForChannel, function onResult(err, approvedUsers) {

            if (!err &&
              approvedUsers) {

              resolve(approvedUsers);
            } else {

              reject('Problems in retrieve approved users for channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , setOfferForUserInChannel = function setOfferForUserInChannel(channel, who, offer) {
        var userInChannelOfferKey = constructKeyForChannel(channel, constructOffersField(who));
        redis.set(userInChannelOfferKey, JSON.stringify(offer));
      }
    , getOfferForChannel = function getOfferForChannel(channel) {
        var userInChannelOfferKey = 'channel-' + channel + ':*-offer'
          , evalString = 'local key = redis.call(\'keys\', \'' + userInChannelOfferKey + '\')[1]; if key then local value = redis.call(\'get\', key); if value then redis.call(\'del\', key); return {key, value}; end end';
        return new RSVP.Promise(function deferred(resolve, reject) {

          redis.eval(evalString, 0, function onResult(err, anOfferKeyValue) {

            if (!err &&
              anOfferKeyValue) {

              var regExp = /\d+:(\d+)/;
              resolve({
                'key': regExp.exec(anOfferKeyValue[0])[1],
                'value': JSON.parse(anOfferKeyValue[1])
              });
            } else {

              reject('Problems in retrieve offer from channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , addIceCandidateForUserInChannel = function addIceCandidateForUserInChannel(channel, who, iceCandidate) {
        var iceCandidateForUserAndChannel = constructKeyForChannel(channel, constructIceCadindatesFieldsForUser(who));
        redis.lpush(iceCandidateForUserAndChannel, JSON.stringify(iceCandidate));
      }
    , getIceCandidatesForUserInChannel = function getIceCandidatesForUserInChannel(channel, who) {
        var iceCandidateForUserAndChannel = constructKeyForChannel(channel, constructIceCadindatesFieldsForUser(who))
          , evalString = 'local key = redis.call(\'llen\', \'' + iceCandidateForUserAndChannel + '\'); if key then local value = redis.call(\'lrange\', \'' + iceCandidateForUserAndChannel + '\', 0, key); if value then redis.call(\'del\', \'' + iceCandidateForUserAndChannel + '\'); return value; end end';

        return new RSVP.Promise(function deferred(resolve, reject) {

          redis.eval(evalString, 0, function onResult(err, iceCandidates) {

            if (!err &&
              iceCandidates) {

              var iceCandidatesLength = iceCandidates.length
                , aJSONIceCandidateIndex
                , aJSONIceCandidate
                , toReturn = [];
              for (aJSONIceCandidateIndex = 0; aJSONIceCandidateIndex < iceCandidatesLength; aJSONIceCandidateIndex += 1) {

                aJSONIceCandidate = iceCandidates[aJSONIceCandidateIndex];
                toReturn.push(JSON.parse(aJSONIceCandidate));
              }

              resolve(toReturn);
            } else {

              reject('Problems in retrieve iceCandidate for user ' + who + ' from channel ' + channel + ' - ' + err);
            }
          });
        });
      }
    , getInitiatorAndApprovedUsersForChannel = function getInitiatorAndApprovedUsersForChannel(channel) {
        var promises = {
          'initiator': getInitiatorForChannel(channel),
          'approved': getApprovedUsersForChannel(channel)
        };

        return new RSVP.Promise(function deferred(resolve, reject) {
          RSVP.hashSettled(promises).then(function deferred(results) {

            if (results.initiator.state === 'fulfilled' && results.approved.state === 'fulfilled') {

              var initiator = results.initiator.value
                , approvedUsers = results.approved.value;

              resolve({
                'initiator': initiator,
                'approvedUsers': approvedUsers
              });
            } else {

              reject('Something goes wrong :(...');
            }
          });
        });
      }
    , isEmpty = function isEmpty(map) {
        for (var key in map) {

          if (map.hasOwnProperty(key)) {

            return false;
          }
        }
        return true;
      }
    , sockets = {}
    , directIceCandidates = {};

  module.exports = function exporting() {

    var websocketClosed = function websocketClosed(aWebSocket) {

          var channels = Object.keys(sockets)
            , aChannelIndex = 0
            , aChannel
            , channelUsers
            , channelUsersNames
            , channelUsersIndex
            , aChannelUser
            , channelsLength = channels.length
            , usersInChannelLength
            , waitersForInitiatorForChannelLength
            , eliminateUserFromInitiatorWaitersInChannel
            , usersWaitingForInitiatorIndex
            , aUserWaitingForInitiatorForChannel
            , usersApprovedInChannelLength
            , usersApprovedInChannelIndex
            , aUserApprovedInChannel
            , eliminateUserFromApprovedInChannel
            , manageListener = function manageListener(theChannel, theChannelUser) {
                removeListenerForChannel(theChannel, theChannelUser);
              }
            , manageInitiator = function manageInitiator(theChannel, theChannelUser, initiator) {

                if (initiator &&
                  theChannelUser === initiator) {

                    // XXX is the owner of channel. I should kick all the other users.
                    removeInitiatorForChannel(theChannel);
                } else {

                  manageListener(theChannel, theChannelUser);
                }
              }
            , manageInitiatorWaiter = function manageInitiatorWaiter(theChannel, theChannelUser, inititatorWaiters) {

                if (inititatorWaiters) {

                  waitersForInitiatorForChannelLength = inititatorWaiters.length;
                  eliminateUserFromInitiatorWaitersInChannel = false;
                  for (usersWaitingForInitiatorIndex = 0; usersWaitingForInitiatorIndex < waitersForInitiatorForChannelLength; usersWaitingForInitiatorIndex += 1) {

                    aUserWaitingForInitiatorForChannel = inititatorWaiters[usersWaitingForInitiatorIndex];
                    if (aUserWaitingForInitiatorForChannel === theChannelUser) {

                      eliminateUserFromInitiatorWaitersInChannel = true;
                      break;
                    }
                  }

                  if (eliminateUserFromInitiatorWaitersInChannel) {

                    removeInitiatorWaiterForChannel(theChannel, theChannelUser);
                  }
                }
              }
            , manageApprovedUser = function manageApprovedUser(theChannel, theChannelUser, approvedUsers) {

                if (approvedUsers) {

                  usersApprovedInChannelLength = approvedUsers.length;
                  eliminateUserFromApprovedInChannel = false;
                  for (usersApprovedInChannelIndex = 0; usersApprovedInChannelIndex < usersApprovedInChannelLength; usersApprovedInChannelIndex += 1) {

                    aUserApprovedInChannel = approvedUsers[usersApprovedInChannelIndex];
                    if (aUserApprovedInChannel === theChannelUser) {

                      eliminateUserFromApprovedInChannel = true;
                      break;
                    }
                  }

                  if (eliminateUserFromApprovedInChannel) {

                    removeApprovedUserForChannel(theChannel, theChannelUser);
                  }
                }
              };

          for (aChannelIndex = 0; aChannelIndex < channelsLength; aChannelIndex += 1) {

            aChannel = channels[aChannelIndex];
            channelUsers = sockets[aChannel];
            channelUsersNames = Object.keys(channelUsers);
            usersInChannelLength = channelUsersNames.length;
            for (channelUsersIndex = 0; channelUsersIndex < usersInChannelLength; channelUsersIndex += 1) {

              aChannelUser = channelUsersNames[channelUsersIndex];
              if (aWebSocket === sockets[aChannel][aChannelUser]) {

                delete sockets[aChannel][aChannelUser];
                if (directIceCandidates[aChannel] &&
                  directIceCandidates[aChannel][aChannelUser]) {

                  delete directIceCandidates[aChannel][aChannelUser];
                  if (isEmpty(directIceCandidates[aChannel])) {

                    delete directIceCandidates[aChannel];
                  }
                }

                if (isEmpty(sockets[aChannel])) {

                  delete sockets[aChannel];
                }

                getInitiatorForChannel(aChannel)
                  .then(manageInitiator.bind(this, aChannel, aChannelUser))
                  .catch(manageListener.bind(this, aChannel, aChannelUser));
                getInitiatorWaitersForChannel(aChannel).then(manageInitiatorWaiter.bind(this, aChannel, aChannelUser));
                getApprovedUsersForChannel(aChannel).then(manageApprovedUser.bind(this, aChannel, aChannelUser));
              }
            }
          }
        }
      , addWebSocketForChannel = function addWebSocketForChannel(aWebSocket, whoami, channel) {
          if (!sockets[channel]) {

            sockets[channel] = {};
          }
          sockets[channel][whoami] = aWebSocket;
        }
      , addOfferForChannel = function addOfferForChannel(offer, whoami, channel) {
          getInitiatorWaitersForChannel(channel).then(function onSuccess(waiters) {

            var firstWaiter
              , waitersIndex
              , aWaiter;
            if (waiters &&
              waiters.length > 0) {

              firstWaiter = waiters[0];
              if (firstWaiter &&
                firstWaiter.length > 0) {

                sockets[channel][firstWaiter].send('offer', channel, firstWaiter, whoami, offer);
                removeInitiatorWaiterForChannel(channel, firstWaiter);
              }

              if (waiters.length > 1) {

                for (waitersIndex = 1; waitersIndex < waiters.length; waitersIndex += 1) {

                  aWaiter = waiters[waitersIndex];

                  sockets[channel][aWaiter].send('redoJoin', channel, aWaiter, whoami);
                  removeInitiatorWaiterForChannel(channel, aWaiter);
                }
              }
            } else {

              setOfferForUserInChannel(channel, whoami, offer);
            }
          });
        }
      , sendOffersTo = function sendOffersTo(aWebSocket, whoami, channel) {
          var promises = {
            'initiator': getInitiatorForChannel(channel),
            'offer': getOfferForChannel(channel)
          };

          RSVP.hashSettled(promises).then(function deferred(results) {

            if (results.offer.state === 'fulfilled') {

              var who = results.offer.value.key
                , offerToSend = results.offer.value.value;
              aWebSocket.send('offer', channel, whoami, who, offerToSend);
            } else if (results.initiator.state === 'fulfilled') {

              sockets[channel][results.initiator.value].send('p2pInst', channel, results.initiator.value, whoami);
            } else {

              addInitiatorWaiterForChannel(channel, whoami);
            }
          });
        }
      , addCandidateForChannel = function addCandidateForChannel(iceCandidate, whoami, channel) {

          addIceCandidateForUserInChannel(channel, whoami, iceCandidate);
        }
      , sendCandidatesTo = function sendCandidatesTo(who, whoami, channel) {
          getIceCandidatesForUserInChannel(channel, who).then(function onSuccess(iceCandidates) {

            if (iceCandidates &&
              iceCandidates.length > 0 &&
              sockets[channel] &&
              sockets[channel][whoami]) {

              sockets[channel][whoami].send('candidate', channel, whoami, who, iceCandidates);
            }
          });
        }
      , sendAnswerTo = function sendAnswerTo(channel, who, whoami, answer) {
          if (sockets[channel] &&
            sockets[channel][who]) {

            sockets[channel][who].send('answer', channel, who, whoami, answer);
          }
        }
      , sendP2PIsInst = function sendP2PIsInst(channel, who, whoami) {
          if (sockets[channel] &&
            sockets[channel][who]) {

            sockets[channel][who].send('p2pIsInst', channel, who, whoami);
          } else {

            console.error('Params not valid');
          }
        }
      , sendUsersToConnectWithToApproved = function sendUsersToConnectWithToApproved(channel, who, whoami) {
          getInitiatorForChannel(channel).then(function onSuccess(initiator) {

            if (who &&
              initiator === whoami) {

              var usersInChannel = Object.keys(sockets[channel])
                , ownerInChannel = usersInChannel.indexOf(whoami)
                , approvedUserInChannel;

              if (ownerInChannel >= 0) {

                usersInChannel.splice(ownerInChannel, 1);
                approvedUserInChannel = usersInChannel.indexOf(who);
                if (approvedUserInChannel >= 0) {

                  usersInChannel.splice(approvedUserInChannel, 1);
                  addApprovedUserForChannel(channel, who);
                  sockets[channel][who].send('approved', channel, who, whoami, usersInChannel);
                }
              }
            }
          });
        }
      , sendNotApproval = function sendNotApproval(channel, who, whoami) {
          getInitiatorForChannel(channel).then(function onSuccess(initiator) {

            if (who &&
              initiator === whoami) {

              removeApprovedUserForChannel(channel, who);
              sockets[channel][who].send('unApproved', channel, who, whoami);
            }
          });
        }
      , manageIncomingMessage = function manageIncomingMessage(message, aWebSocket) {

          var parsedMsg = JSON.parse(message);
          /*{
              'opcode': opcode,
              'whoami': whoami,
              'token': 'jwt-token',
              'who': who,
              'channel': channel,
              'payload': data
          }*/

          /*eslint-disable no-console*/
          console.log('-- incoming --', {
            'opcode': parsedMsg.opcode,
            'whoami': parsedMsg.whoami,
            'token': 'jwt-token',
            'who': parsedMsg.who,
            'channel': parsedMsg.channel
          });
          /*eslint-enable no-console*/

          if (/* Mandatory fields */
            parsedMsg.opcode &&
            parsedMsg.whoami &&
            parsedMsg.token &&
            parsedMsg.channel) {

            addWebSocketForChannel(aWebSocket, parsedMsg.whoami, parsedMsg.channel);
            //jwt.verify(parsedMsg.token, config.sessionSecretKey, function () {
            switch (parsedMsg.opcode) {
              case 'open':

                if (parsedMsg.payload) {

                  setInitiatorForChannel(parsedMsg.channel, parsedMsg.whoami);
                  addOfferForChannel(parsedMsg.payload, parsedMsg.whoami, parsedMsg.channel);
                  if (parsedMsg.who) {

                    sendP2PIsInst(parsedMsg.channel, parsedMsg.who, parsedMsg.whoami);
                  }
                }
              break;

              case 'join':

                addListenerForChannel(parsedMsg.channel, parsedMsg.whoami);
                sendOffersTo(aWebSocket, parsedMsg.whoami, parsedMsg.channel);
              break;

              case 'answer':

                sendAnswerTo(parsedMsg.channel, parsedMsg.who, parsedMsg.whoami, parsedMsg.payload);
              break;

              case 'iceCandidate':

                if (parsedMsg.payload &&
                  parsedMsg.whoami &&
                  parsedMsg.channel) {

                  if (directIceCandidates[parsedMsg.channel] &&
                    directIceCandidates[parsedMsg.channel][parsedMsg.who] &&
                    directIceCandidates[parsedMsg.channel][parsedMsg.who][parsedMsg.whoami]) {

                    sockets[parsedMsg.channel][parsedMsg.who].send('candidate', parsedMsg.channel, parsedMsg.who, parsedMsg.whoami, [parsedMsg.payload]);
                  } else {

                    addCandidateForChannel(parsedMsg.payload, parsedMsg.whoami, parsedMsg.channel);
                  }
                }
              break;

              case 'useIceCandidates':

                sendCandidatesTo(parsedMsg.who, parsedMsg.whoami, parsedMsg.channel);
                getInitiatorAndApprovedUsersForChannel(parsedMsg.channel).then(function onSuccess(response) {

                  if (response.initiator === parsedMsg.whoami) {

                    if (response.approvedUsers) {
                      var approvedUsersIndex = 0
                        , approvedUsersLength = response.approvedUsers.length
                        , anApprovedUser;
                      for (; approvedUsersIndex < approvedUsersLength; approvedUsersIndex += 1) {

                        anApprovedUser = response.approvedUsers[approvedUsersIndex];
                        if (anApprovedUser &&
                          anApprovedUser !== parsedMsg.who) {

                          sockets[parsedMsg.channel][anApprovedUser].send('approved', parsedMsg.channel, parsedMsg.who, parsedMsg.whoami, [parsedMsg.who]);
                        }
                      }
                    }
                  }
                });
                if (!directIceCandidates[parsedMsg.channel]) {

                  directIceCandidates[parsedMsg.channel] = {};
                }

                if (!directIceCandidates[parsedMsg.channel][parsedMsg.whoami]) {

                  directIceCandidates[parsedMsg.channel][parsedMsg.whoami] = {};
                }

                directIceCandidates[parsedMsg.channel][parsedMsg.whoami][parsedMsg.who] = true;
              break;

              case 'approve':

                sendUsersToConnectWithToApproved(parsedMsg.channel, parsedMsg.who, parsedMsg.whoami);
              break;

              case 'unApprove':

                sendNotApproval(parsedMsg.channel, parsedMsg.who, parsedMsg.whoami);
              break;

              case 'leave':

                websocketClosed(aWebSocket);
              break;

              default:

                /*eslint-disable no-console*/
                console.error(parsedMsg.opcode, 'un-manageable.');
                /*eslint-enable no-console*/
            }
            //});
          } else {

            /*eslint-disable no-console*/
            console.error(parsedMsg, 'is an unaccettable message.');
            /*eslint-enable no-console*/
          }
        }
      , onRequest = function onRequest(socket) {

          socket.push = socket.send;
          socket.send = function send(opcode, channel, who, whoami, data) {
            if (socket.readyState === socket.OPEN) {

              var toSend = {
                'opcode': opcode,
                'whoami': whoami,
                'who': who,
                'channel': channel,
                'payload': data
              };
              console.log('-- send --', {
                'opcode': opcode,
                'whoami': whoami,
                'who': who,
                'channel': channel
              });
              socket.push(JSON.stringify(toSend));
            } else {

              console.log('Socket is in readyState', socket.readyState);
            }
          };

          socket.on('message', function onMessage(message) {

            manageIncomingMessage(message, socket);
          });

          socket.on('close', function onClose() {

            websocketClosed(socket);
          });
        };

    wss.on('connection', onRequest);
    process.on('SIGTERM', function onSigTerm(exitCallback) {

      redis.quit();
      if (exitCallback) {

        exitCallback();
      }
    });

    return {
      'listenersForChannel': getListenersForChannel
    };
  };
}(require, module, console));
<commit_msg>no storage, atm<commit_after><|endoftext|>


<commit_before>var fs = require('fs-extra');
var path = require('path');
var pump = require('pump');
var OgrJsonStream = require('ogr-json-stream');
var winston = require('winston');
var options = require('commander');
var async = require('async');
var ogrChild = require('./ogrChild');
var loader = require('./lib/loader');

//If linked to an elasticsearch Docker container
var esVar = process.env.ELASTICSEARCH_PORT;
var esHost = 'localhost';
var esPort = 9200;

if(esVar){
  esVar = esVar.split('//')[1].split(':');
  esHost = esVar[0];
  esPort = +esVar[1];
}

var logger = new winston.Logger({
    transports: [
      new (winston.transports.Console)()
    ]
  });

options
  .version('0.0.1')
  .option('-d, --directory <directory>', 'Directory where TIGER files live')
  .option('-c, --concurrency <concurrency>', 'How many loading tasks will run at once. Defaults to 4.', 4)
  .option('-h, --host <host>', 'ElasticSearch host. Defaults to localhost', esHost)
  .option('-p, --port <port>', 'ElasticSearch port. Defaults to 9200', Number, esPort)
  .option('-a, --alias <alias>', 'Elasticsearch index alias. Defaults to census', 'census')
  .option('-t, --type <type>', 'Elasticsearch type within the provided or default index. Defaults to addrfeat', 'addrfeat')
  .option('--profile', 'The aws credentials profile in ~/.aws/credentials. Will also respect AWS keys as environment variables.', 'default')
  .option('-q, --quiet', 'Suppress logging.', false)
  .parse(process.argv);

options.logger = logger;

function worker(file, callback){
  var child = ogrChild(file);
  var stream = OgrJsonStream();

  pump(child, stream);

  loader(options, stream, {name: path.basename(file, path.extname(file))}, callback);
}

var queue = async.queue(worker, options.concurrency);

queue.drain = function(){
  logger.info('All files processed.');
};

fs.readdir(options.directory, function(err, files){
  if(err) return logger.error(err);
  files.forEach(function(file){
    queue.push(file, function(err){
      if(err)logger.error(err);
      logger.info(file + ' finished processing');
    })
  })
});

<commit_msg>Make tiger cli executable<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs-extra');
var path = require('path');
var pump = require('pump');
var OgrJsonStream = require('ogr-json-stream');
var winston = require('winston');
var options = require('commander');
var async = require('async');
var ogrChild = require('./ogrChild');
var loader = require('./lib/loader');

//If linked to an elasticsearch Docker container
var esVar = process.env.ELASTICSEARCH_PORT;
var esHost = 'localhost';
var esPort = 9200;

if(esVar){
  esVar = esVar.split('//')[1].split(':');
  esHost = esVar[0];
  esPort = +esVar[1];
}

var logger = new winston.Logger({
    transports: [
      new (winston.transports.Console)()
    ]
  });

options
  .version('0.0.1')
  .option('-d, --directory <directory>', 'Directory where TIGER files live')
  .option('-c, --concurrency <concurrency>', 'How many loading tasks will run at once. Defaults to 4.', 4)
  .option('-h, --host <host>', 'ElasticSearch host. Defaults to localhost', esHost)
  .option('-p, --port <port>', 'ElasticSearch port. Defaults to 9200', Number, esPort)
  .option('-a, --alias <alias>', 'Elasticsearch index alias. Defaults to census', 'census')
  .option('-t, --type <type>', 'Elasticsearch type within the provided or default index. Defaults to addrfeat', 'addrfeat')
  .option('--profile', 'The aws credentials profile in ~/.aws/credentials. Will also respect AWS keys as environment variables.', 'default')
  .option('-q, --quiet', 'Suppress logging.', false)
  .parse(process.argv);

options.logger = logger;

function worker(file, callback){
  var child = ogrChild(file);
  var stream = OgrJsonStream();

  pump(child, stream);

  loader(options, stream, {name: path.basename(file, path.extname(file))}, callback);
}

var queue = async.queue(worker, options.concurrency);

queue.drain = function(){
  logger.info('All files processed.');
};

fs.readdir(options.directory, function(err, files){
  if(err) return logger.error(err);
  files.forEach(function(file){
    queue.push(file, function(err){
      if(err)logger.error(err);
      logger.info(file + ' finished processing');
    })
  })
});

<|endoftext|>


<commit_before>/**
 * @namespace leaf.ai
 * @property {Object} PatternList The List of Patterns
 */
leaf.ai = {
    PatternList: new leaf.List(),
    /**
     * Executes a success callback if a match if found, and passes in the response and Model.
     * @memberOf leaf.ai
     * @param {string} The pattern.
     * @param {Function} success The callback callback
     * @param {Function} failure The failure callback
     * @returns {string} The response.
     */
    respond: function(pattern, success, failure) {
        var result;
        /**
        * Determines if a pattern exist.
        * @private
        * @param {Object} model The Model.
        * @returns {Boolean} True if the pattern exists in the Model.
        */
        function contains(model) {
            /**
             * Handle a string pattern
             */
            if(leaf.isString(model.get('pattern'))) {
                return pattern.indexOf(filter(model.get('pattern'))) != -1;
            }
            /**
             * Handle an Array pattern
             */
            if(leaf.isArray(model.get('pattern'))) {
                for (var index = 0; index < model.get('pattern').length; index++) {
                    if(pattern.indexOf(filter(model.get('pattern')[index])) != -1) {
                        return true;
                    }
                }
            }

            return false;
        }
        /**
        * Return the response if a pattern exists.
        * @private
        * @param {Object} model The Model.
        * @returns {string} The response.
        */
        function respond(model) {
        	var header = "", content = "", footer = "";

            /**
             * Handle a string header
             */
            if(leaf.isDefined(model.get('header')) && leaf.isString(model.get('header')) ) {
                header = model.get('header');
            }

            /**
             * Handle an Array header
             */
            if(leaf.isDefined(model.get('header')) && leaf.isArray(model.get('header')) ) {
                header = random(model.get('header'));
            }

            /**
             * Handle a string content
             */
            if(leaf.isDefined(model.get('content')) && leaf.isString(model.get('content'))) {
                content = model.get('content');
            }

            /**
             * Handle an Array content
             */
            if(leaf.isDefined(model.get('content')) && leaf.isArray(model.get('content'))) {
                content = random(model.get('content'));
            }

            /**
             * Handle a string footer
             */
            if(leaf.isDefined(model.get('footer')) && leaf.isString(model.get('footer')) ) {
                footer = model.get('footer');
            }

            /**
             * Handle an Array footer
             */
            if(leaf.isDefined(model.get('footer')) && leaf.isArray(model.get('footer')) ) {
                footer = random(model.get('footer'));
            }

            return header + content + footer;
        }
        /**
        * Returns a random response if multiple responses are given.
        * @private
        * @param {Object} data The Array.
        * @returns {string} The response.
        */
        function random(data) {
            return data[Math.floor(Math.random() * data.length)];
        }
        /**
         * Removes punctuation and lower cases a value for better string
         * comparisons.
         * @private
         * @param {string} value The value.
         * @returns {string} The filtered value.
         */
        function filter(value) {
            return value.toLowerCase().replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ");
        }
        /**
         * Filter the pattern.
         */
        pattern = filter(pattern);
        /**
         * Iterate through the List and look for a match. If a match was found,
         * assign result to it.
         */
        this.PatternList.each(function(model) {
            if(contains(model) === true) {
                result = model;
            }
        });
        /**
         * Execute the appropriate callback Function. If the result is a Model, pass
         * the response and the result to the success callback.
         */
        if (leaf.isDefined(result)) {
            success(respond(result), result);
        }
        else {
            failure();
        }
    }
};
<commit_msg>Updated<commit_after><|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router'
import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'
import Style from 'style-it'
import chroma from 'chroma-js'
import QueueAnim from 'rc-queue-anim'

import {formatDate, filterHtml, getNewListUri} from '../utils'
import Page from './Page'

import FlatButton from 'material-ui/FlatButton'
import Avatar from 'material-ui/Avatar'
import TouchRipple from 'material-ui/internal/TouchRipple'
import ExtensionDuoshuo from '../components/Duoshuo/Extensions'
import Waiting from '../components/Waiting'

import './List.css'

export default class List extends Page {
  componentDidMount () {
    document.title = '文章列表 - ' + window.config.title
  }

  componentDidUpdate (prevProps, prevState) {
    // super.componentDidUpdate(prevProps, prevState)
    window.doListLoaded()
    window.doGlobal()
  }

  handleAnimationEnd = (data) => {
    if (data.type === 'enter') {
      this.trianglify(document.querySelector(`.canvas-triangle-${data.key}`))
    }
  }

  pageTo = pageForward => {
    const currentPage = this.state.data.pagebar.current
    const maxPage = parseInt(this.state.data.pagebar.max / this.state.data.pagebar.pageCount, 10) + 1
    let nextPage = currentPage + pageForward
    if (nextPage <= 0 || nextPage > maxPage) nextPage = currentPage
    return getNewListUri(this.props.location.pathname, { page: nextPage })
  }

  render () {
    const data = this.state.data
    if (!data) return (<Waiting />)
    return (

      {!data.articles ? <Waiting /> :
<QueueAnim onEnd={this.handleAnimationEnd}>
        {data.articles.map((article) => {
          const introHtml = {__html: article.Intro}
          const linkTo = '/post/' + article.ID
          const color = this.colors[parseInt(Math.random() * this.colors.length, 10)]
          const brewer = chroma.brewer[color]
          return
        })
      }</QueueAnim>

          <Link to={this.pageTo(-1)}><FlatButton primary label='Prev' /></Link>
          <Link to={this.pageTo(1)}><FlatButton primary label='Next' style={{float: 'right'}} /></Link>

    }

)
  }

}
<commit_msg>Remove one of animation<commit_after>import React from 'react'
import { Link } from 'react-router'
import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'
import Style from 'style-it'
import chroma from 'chroma-js'
// import QueueAnim from 'rc-queue-anim'

import {formatDate, filterHtml, getNewListUri} from '../utils'
import Page from './Page'

import FlatButton from 'material-ui/FlatButton'
import Avatar from 'material-ui/Avatar'
import TouchRipple from 'material-ui/internal/TouchRipple'
import ExtensionDuoshuo from '../components/Duoshuo/Extensions'
import Waiting from '../components/Waiting'

import './List.css'

export default class List extends Page {
  componentDidMount () {
    document.title = '文章列表 - ' + window.config.title
  }

  componentDidUpdate (prevProps, prevState) {
    super.componentDidUpdate(prevProps, prevState)
    window.doListLoaded()
    window.doGlobal()
  }

  handleAnimationEnd = (data) => {
    if (data.type === 'enter') {
      this.trianglify(document.querySelector(`.canvas-triangle-${data.key}`))
    }
  }

  pageTo = pageForward => {
    const currentPage = this.state.data.pagebar.current
    const maxPage = parseInt(this.state.data.pagebar.max / this.state.data.pagebar.pageCount, 10) + 1
    let nextPage = currentPage + pageForward
    if (nextPage <= 0 || nextPage > maxPage) nextPage = currentPage
    return getNewListUri(this.props.location.pathname, { page: nextPage })
  }

  render () {
    const data = this.state.data
    if (!data) return (<Waiting />)
    return (

      {!data.articles ? <Waiting /> :
{/* <QueueAnim onEnd={this.handleAnimationEnd}> */}
        {data.articles.map((article) => {
          const introHtml = {__html: article.Intro}
          const linkTo = '/post/' + article.ID
          const color = this.colors[parseInt(Math.random() * this.colors.length, 10)]
          const brewer = chroma.brewer[color]
          return
        })
      }{/* </QueueAnim> */}

          <Link to={this.pageTo(-1)}><FlatButton primary label='Prev' /></Link>
          <Link to={this.pageTo(1)}><FlatButton primary label='Next' style={{float: 'right'}} /></Link>

    }

)
  }

}
<|endoftext|>


<commit_before>import React from 'react'
import classnames from 'classnames'
//
// import _ from './utils'

const defaultButton = (props) => (
  <button type='button' {...props} className='-btn'>{props.children}</button>
)

export default React.createClass({
  getInitialState () {
    return {
      page: this.props.page
    }
  },
  componentWillReceiveProps (nextProps) {
    this.setState({page: nextProps.page})
  },
  getSafePage (page) {
    return Math.min(Math.max(page, 0), this.props.pages - 1)
  },
  changePage (page) {
    page = this.getSafePage(page)
    this.setState({page})
    this.props.onPageChange(page)
  },
  applyPage (e) {
    e && e.preventDefault()
    const page = this.state.page
    this.changePage(page === '' ? this.props.page : page)
  },
  render () {
    const {
      // Computed
      pages,
      // Props
      page,
      showPageSizeOptions,
      pageSizeOptions,
      pageSize,
      showPageJump,
      canPrevious,
      canNext,
      onPageSizeChange,
      className,
      PreviousComponent = defaultButton,
      NextComponent = defaultButton
    } = this.props

    return (

          <PreviousComponent
            onClick={(e) => {
              if (!canPrevious) return
              this.changePage(page - 1)
            }}
            disabled={!canPrevious}
          >
            {this.props.previousText}
          </PreviousComponent>

            {this.props.pageText} {showPageJump ? (

                <input
                  type={this.state.page === '' ? 'text' : 'number'}
                  onChange={e => {
                    const val = e.target.value
                    const page = val - 1
                    if (val === '') {
                      return this.setState({page: val})
                    }
                    this.setState({page: this.getSafePage(page)})
                  }}
                  value={this.state.page === '' ? '' : this.state.page + 1}
                  onBlur={this.applyPage}
                  onKeyPress={e => {
                    if (e.which === 13 || e.keyCode === 13) {
                      this.applyPage()
                    }
                  }}
                />

            ) : (
              {page + 1}
            )} {this.props.ofText} {pages}

          {showPageSizeOptions && (

              <select
                onChange={(e) => onPageSizeChange(Number(e.target.value))}
                value={pageSize}
              >
                {pageSizeOptions.map((option, i) => {
                  return (
                    <option
                      key={i}
                      value={option}>
                      {option} {this.props.rowsText}
                    </option>
                  )
                })}
              </select>

          )}

          <NextComponent
            onClick={(e) => {
              if (!canNext) return
              this.changePage(page + 1)
            }}
            disabled={!canNext}
          >
            {this.props.nextText}
          </NextComponent>

    )
  }
})
<commit_msg>Avoid page refresh if same page, set NaN to current page (#178)<commit_after>import React from 'react'
import classnames from 'classnames'
//
// import _ from './utils'

const defaultButton = (props) => (
  <button type='button' {...props} className='-btn'>{props.children}</button>
)

export default React.createClass({
  getInitialState () {
    return {
      page: this.props.page
    }
  },
  componentWillReceiveProps (nextProps) {
    this.setState({page: nextProps.page})
  },
  getSafePage (page) {
    if (isNaN(page)) {
      page = this.props.page
    }
    return Math.min(Math.max(page, 0), this.props.pages - 1)
  },
  changePage (page) {
    page = this.getSafePage(page)
    this.setState({page})
    if (this.props.page !== page) {
      this.props.onPageChange(page)
    }
  },
  applyPage (e) {
    e && e.preventDefault()
    const page = this.state.page
    this.changePage(page === '' ? this.props.page : page)
  },
  render () {
    const {
      // Computed
      pages,
      // Props
      page,
      showPageSizeOptions,
      pageSizeOptions,
      pageSize,
      showPageJump,
      canPrevious,
      canNext,
      onPageSizeChange,
      className,
      PreviousComponent = defaultButton,
      NextComponent = defaultButton
    } = this.props

    return (

          <PreviousComponent
            onClick={(e) => {
              if (!canPrevious) return
              this.changePage(page - 1)
            }}
            disabled={!canPrevious}
          >
            {this.props.previousText}
          </PreviousComponent>

            {this.props.pageText} {showPageJump ? (

                <input
                  type={this.state.page === '' ? 'text' : 'number'}
                  onChange={e => {
                    const val = e.target.value
                    const page = val - 1
                    if (val === '') {
                      return this.setState({page: val})
                    }
                    this.setState({page: this.getSafePage(page)})
                  }}
                  value={this.state.page === '' ? '' : this.state.page + 1}
                  onBlur={this.applyPage}
                  onKeyPress={e => {
                    if (e.which === 13 || e.keyCode === 13) {
                      this.applyPage()
                    }
                  }}
                />

            ) : (
              {page + 1}
            )} {this.props.ofText} {pages}

          {showPageSizeOptions && (

              <select
                onChange={(e) => onPageSizeChange(Number(e.target.value))}
                value={pageSize}
              >
                {pageSizeOptions.map((option, i) => {
                  return (
                    <option
                      key={i}
                      value={option}>
                      {option} {this.props.rowsText}
                    </option>
                  )
                })}
              </select>

          )}

          <NextComponent
            onClick={(e) => {
              if (!canNext) return
              this.changePage(page + 1)
            }}
            disabled={!canNext}
          >
            {this.props.nextText}
          </NextComponent>

    )
  }
})
<|endoftext|>


<commit_before>'use strict'

/**
 * adonis-framework
 * Copyright(c) 2015-2016 Harminder Virk
 * MIT Licensed
*/

const helpers = require('./helpers')
const Group = require('./group')
const Resource = require('./resource')
const domains = require('./domains')
const util = require('../../lib/util')
const _ = require('lodash')

/**
 * holding reference to registered routes
 * @type {Array}
 * @private
 */
let routes = []

/**
 * holding reference to active Group
 * @type {String}
 * @private
 */
let activeGroup = null

/**
 * Create and register routes using regular expressions
 * @module Route
 */
let Route = exports = module.exports = {}

/**
 * return all registered routes
 *
 * @method routes
 * @return {Object}
 *
 * @public
 */
Route.routes = function () {
  return routes
}

/**
 * clear registered routes and other local variables
 *
 * @method new
 *
 * @public
 */
Route.new = function () {
  activeGroup = null
  routes = []
}

/**
 * a low level method to register route with path,verb
 * and handler
 *
 * @method route
 *
 * @param {string} route - route expression
 * @param {string} verb - http verb/method
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.route('/welcome', 'GET', function * () {
 *
 * })
 *
 * @public
 */
Route.route = function (route, verb, handler) {
  let constructedRoute = helpers.construct(route, verb, handler, activeGroup)
  routes.push(constructedRoute)
  return this
}

/**
 * register route with GET verb
 *
 * @method get
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.get('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.get = function (route, handler) {
  this.route(route, ['GET', 'HEAD'], handler)
  return this
}

/**
 * registers a get route with null handler
 * which later can be used with render
 * method to render a view.
 *
 * @method on
 *
 * @param  {String} route
 * @return {Object}
 *
 * @public
 */
Route.on = function (route) {
  Route.get(route, null)
  return this
}

/**
 * Replaces the route handler method with a custom
 * closure, to send a given view.
 *
 * @method render
 *
 * @param  {String} view
 *
 * @public
 */
Route.render = function (view) {
  const route = Route._lastRoute()
  route.handler = function * (request, response) {
    yield response.sendView(view, {request})
  }
}

/**
 * register route with POST verb
 *
 * @method post
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.post('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.post = function (route, handler) {
  this.route(route, 'POST', handler)
  return this
}

/**
 * register route with PUT verb
 *
 * @method put
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.put('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.put = function (route, handler) {
  this.route(route, 'PUT', handler)
  return this
}

/**
 * register route with PATCH verb
 *
 * @method patch
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.patch('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.patch = function (route, handler) {
  this.route(route, 'PATCH', handler)
  return this
}

/**
 * register route with DELETE verb
 *
 * @method delete
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.delete('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.delete = function (route, handler) {
  this.route(route, 'DELETE', handler)
  return this
}

/**
 * register route with OPTIONS verb
 *
 * @method options
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.put('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.options = function (route, handler) {
  this.route(route, 'OPTIONS', handler)
  return this
}

/**
 * registers a route with multiple HTTP verbs
 *
 * @method match
 *
 * @param  {Array} verbs - an array of verbs
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.match(['GET', 'POST'], '/user', function * () {
 *
 * })
 *
 * @public
 */
Route.match = function (verbs, route, handler) {
  verbs = _.map(verbs, function (verb) { return verb.toUpperCase() })
  this.route(route, verbs, handler)
  return this
}

/**
 * registers route for all http verbs
 *
 * @method any
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.any('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.any = function (route, handler) {
  const verbs = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
  this.route(route, verbs, handler)
  return this
}

/**
 * giving unique name to a registered route
 *
 * @method as
 *
 * @param  {String} name - name for recently registered route
 *
 * @example
 * Route.get('/user/:id', '...').as('getUser')
 *
 * @public
 */
Route.as = function (name) {
  let lastRoute = Route._lastRoute()
  lastRoute.name = name
  return this
}

/**
 * returns last route registered inside the route store
 *
 * @method lastRoute
 *
 * @return {Object}
 *
 * @private
 */
Route._lastRoute = function () {
  return _.last(routes)
}

/**
 * assign array of named middlewares to route
 *
 * @method middlewares
 * @synonym middleware
 *
 * @param  {Mixed} keys - an array of middleware or multiple parameters
 * @return {Object} - reference to this for chaining
 *
 * @example
 * Route.get('...').middleware('auth', 'csrf')
 * Route.get('...').middleware(['auth', 'csrf'])
 *
 * @public
 */
Route.middlewares = function () {
  helpers.appendMiddleware(
    Route._lastRoute(),
    util.spread.apply(this, arguments)
  )
  return this
}

/**
 * @see module:Route~middlewares
 * @method middleware
 */
Route.middleware = Route.middlewares

/**
 * create a new group of routes to apply rules on a group
 * instead of applying them on every route.
 *
 * @method group
 *
 * @param  {String}   name - unqiue name for group
 * @param  {Function} cb - Callback to isolate group
 * @returns {Route.Group} - Instance of route group
 *
 * @example
 * Route.group('v1', function () {
 *
 * }).prefix('/v1').middleware('auth')
 * @public
 */
Route.group = function (name, cb) {
  activeGroup = name
  cb()
  const groupRoutes = _.filter(routes, function (route) {
    return route.group === activeGroup
  })
  activeGroup = null
  return new Group(groupRoutes)
}

/**
 * resolves route for a given url and HTTP verb/method
 *
 * @method resolve
 *
 * @param  {String} urlPath - Path to url
 * @param  {String} verb - Http verb
 * @param  {String} host - Current host
 *
 * @return {Object}
 *
 * @example
 * Route.resolve('/user/1', 'GET', 'localhost')
 *
 * @public
 */
Route.resolve = function (urlPath, verb, host) {
  if (domains.match(host)) {
    urlPath = `${host}${urlPath}`
  }
  let resolvedRoute = helpers.returnMatchingRouteToUrl(routes, urlPath, verb)
  if (_.size(resolvedRoute) === 0) {
    return {}
  }
  return helpers.returnRouteArguments(resolvedRoute, urlPath, host)
}

/**
 * creates a resource of routes based out of conventions
 *
 * @method resource
 * @alias resources
 *
 * @param  {String} name - Resource name
 * @param  {String} controller - Controller to handle resource requests
 * @returns {Route.resources} - Instance of Resources class
 *
 * @example
 * Route.resource('user', 'UserController')
 * Route.resource('post.comments', 'CommentsController')
 *
 * @public
 */
Route.resource = function (name, controller) {
  return new Resource(Route, name, controller)
}
Route.resources = Route.resource

/**
 * creates a valid url based on route pattern and parameters and params
 *
 * @method url
 *
 * @param  {String} pattern
 * @param  {Object} params
 * @return {String}
 *
 * @example
 * Route.url('user/:id', {id: 1})
 *
 * @public
 */
Route.url = function (pattern, params) {
  const namedRoute = _.filter(routes, function (route) {
    return route.name === pattern
  })[0]

  /**
   * if found pattern as a named route, make it using
   * route properties
   */
  if (namedRoute) {
    const resolveRoute = namedRoute.domain ? `${namedRoute.domain}${namedRoute.route}` : namedRoute.route
    return helpers.compileRouteToUrl(resolveRoute, params)
  }
  return helpers.compileRouteToUrl(pattern, params)
}

/**
 * returns a route with it's property
 *
 * @method getRoute
 * @param  {Object} property
 *
 * @example
 * Route.getRoute({name: 'user.show'})
 * Route.getRoute({handler: 'UserController.show'})
 *
 * @return {Object}
 */
Route.getRoute = function (property) {
  const index = _.findIndex(routes, property)
  return routes[index]
}

/**
 * removes a route from routes mapping using it's name
 *
 * @method remove
 *
 * @param  {String} name
 *
 * @example
 * Route.remove('user.create')
 *
 * @public
 */
Route.remove = function (name) {
  const index = _.findIndex(routes, {name})
  routes.splice(index, 1)
}

/**
 * add formats paramters to route defination which makes
 * url to have optional extensions at the end of them.
 *
 * @method formats
 *
 * @param  {Array} formats - array of supported supports
 * @param  {Boolean} [strict=false] - Using strict mode will not register
 *                                    a plain route without any extension
 *
 * @example
 * Route.get('/user', '...').formats(['json', 'xml'])
 *
 * @public
 */
Route.formats = function (formats, strict) {
  const lastRoute = Route._lastRoute()
  helpers.addFormats(lastRoute, formats, strict)
}
<commit_msg>refactor(route): return this from route.render to chaining<commit_after>'use strict'

/**
 * adonis-framework
 * Copyright(c) 2015-2016 Harminder Virk
 * MIT Licensed
*/

const helpers = require('./helpers')
const Group = require('./group')
const Resource = require('./resource')
const domains = require('./domains')
const util = require('../../lib/util')
const _ = require('lodash')

/**
 * holding reference to registered routes
 * @type {Array}
 * @private
 */
let routes = []

/**
 * holding reference to active Group
 * @type {String}
 * @private
 */
let activeGroup = null

/**
 * Create and register routes using regular expressions
 * @module Route
 */
let Route = exports = module.exports = {}

/**
 * return all registered routes
 *
 * @method routes
 * @return {Object}
 *
 * @public
 */
Route.routes = function () {
  return routes
}

/**
 * clear registered routes and other local variables
 *
 * @method new
 *
 * @public
 */
Route.new = function () {
  activeGroup = null
  routes = []
}

/**
 * a low level method to register route with path,verb
 * and handler
 *
 * @method route
 *
 * @param {string} route - route expression
 * @param {string} verb - http verb/method
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.route('/welcome', 'GET', function * () {
 *
 * })
 *
 * @public
 */
Route.route = function (route, verb, handler) {
  let constructedRoute = helpers.construct(route, verb, handler, activeGroup)
  routes.push(constructedRoute)
  return this
}

/**
 * register route with GET verb
 *
 * @method get
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.get('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.get = function (route, handler) {
  this.route(route, ['GET', 'HEAD'], handler)
  return this
}

/**
 * registers a get route with null handler
 * which later can be used with render
 * method to render a view.
 *
 * @method on
 *
 * @param  {String} route
 * @return {Object}
 *
 * @public
 */
Route.on = function (route) {
  Route.get(route, null)
  return this
}

/**
 * Replaces the route handler method with a custom
 * closure, to send a given view.
 *
 * @method render
 *
 * @param  {String} view
 * @return {Object}
 *
 * @public
 */
Route.render = function (view) {
  const route = Route._lastRoute()
  route.handler = function * (request, response) {
    yield response.sendView(view, {request})
  }
  return this
}

/**
 * register route with POST verb
 *
 * @method post
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.post('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.post = function (route, handler) {
  this.route(route, 'POST', handler)
  return this
}

/**
 * register route with PUT verb
 *
 * @method put
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.put('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.put = function (route, handler) {
  this.route(route, 'PUT', handler)
  return this
}

/**
 * register route with PATCH verb
 *
 * @method patch
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.patch('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.patch = function (route, handler) {
  this.route(route, 'PATCH', handler)
  return this
}

/**
 * register route with DELETE verb
 *
 * @method delete
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.delete('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.delete = function (route, handler) {
  this.route(route, 'DELETE', handler)
  return this
}

/**
 * register route with OPTIONS verb
 *
 * @method options
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.put('/user/:id', function * () {
 *
 * })
 *
 * @public
 */
Route.options = function (route, handler) {
  this.route(route, 'OPTIONS', handler)
  return this
}

/**
 * registers a route with multiple HTTP verbs
 *
 * @method match
 *
 * @param  {Array} verbs - an array of verbs
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.match(['GET', 'POST'], '/user', function * () {
 *
 * })
 *
 * @public
 */
Route.match = function (verbs, route, handler) {
  verbs = _.map(verbs, function (verb) { return verb.toUpperCase() })
  this.route(route, verbs, handler)
  return this
}

/**
 * registers route for all http verbs
 *
 * @method any
 *
 * @param  {String} route - route expression
 * @param {any} handler - handler to respond to a given request
 *
 * @example
 * Route.any('/user', function * () {
 *
 * })
 *
 * @public
 */
Route.any = function (route, handler) {
  const verbs = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
  this.route(route, verbs, handler)
  return this
}

/**
 * giving unique name to a registered route
 *
 * @method as
 *
 * @param  {String} name - name for recently registered route
 *
 * @example
 * Route.get('/user/:id', '...').as('getUser')
 *
 * @public
 */
Route.as = function (name) {
  let lastRoute = Route._lastRoute()
  lastRoute.name = name
  return this
}

/**
 * returns last route registered inside the route store
 *
 * @method lastRoute
 *
 * @return {Object}
 *
 * @private
 */
Route._lastRoute = function () {
  return _.last(routes)
}

/**
 * assign array of named middlewares to route
 *
 * @method middlewares
 * @synonym middleware
 *
 * @param  {Mixed} keys - an array of middleware or multiple parameters
 * @return {Object} - reference to this for chaining
 *
 * @example
 * Route.get('...').middleware('auth', 'csrf')
 * Route.get('...').middleware(['auth', 'csrf'])
 *
 * @public
 */
Route.middlewares = function () {
  helpers.appendMiddleware(
    Route._lastRoute(),
    util.spread.apply(this, arguments)
  )
  return this
}

/**
 * @see module:Route~middlewares
 * @method middleware
 */
Route.middleware = Route.middlewares

/**
 * create a new group of routes to apply rules on a group
 * instead of applying them on every route.
 *
 * @method group
 *
 * @param  {String}   name - unqiue name for group
 * @param  {Function} cb - Callback to isolate group
 * @returns {Route.Group} - Instance of route group
 *
 * @example
 * Route.group('v1', function () {
 *
 * }).prefix('/v1').middleware('auth')
 * @public
 */
Route.group = function (name, cb) {
  activeGroup = name
  cb()
  const groupRoutes = _.filter(routes, function (route) {
    return route.group === activeGroup
  })
  activeGroup = null
  return new Group(groupRoutes)
}

/**
 * resolves route for a given url and HTTP verb/method
 *
 * @method resolve
 *
 * @param  {String} urlPath - Path to url
 * @param  {String} verb - Http verb
 * @param  {String} host - Current host
 *
 * @return {Object}
 *
 * @example
 * Route.resolve('/user/1', 'GET', 'localhost')
 *
 * @public
 */
Route.resolve = function (urlPath, verb, host) {
  if (domains.match(host)) {
    urlPath = `${host}${urlPath}`
  }
  let resolvedRoute = helpers.returnMatchingRouteToUrl(routes, urlPath, verb)
  if (_.size(resolvedRoute) === 0) {
    return {}
  }
  return helpers.returnRouteArguments(resolvedRoute, urlPath, host)
}

/**
 * creates a resource of routes based out of conventions
 *
 * @method resource
 * @alias resources
 *
 * @param  {String} name - Resource name
 * @param  {String} controller - Controller to handle resource requests
 * @returns {Route.resources} - Instance of Resources class
 *
 * @example
 * Route.resource('user', 'UserController')
 * Route.resource('post.comments', 'CommentsController')
 *
 * @public
 */
Route.resource = function (name, controller) {
  return new Resource(Route, name, controller)
}
Route.resources = Route.resource

/**
 * creates a valid url based on route pattern and parameters and params
 *
 * @method url
 *
 * @param  {String} pattern
 * @param  {Object} params
 * @return {String}
 *
 * @example
 * Route.url('user/:id', {id: 1})
 *
 * @public
 */
Route.url = function (pattern, params) {
  const namedRoute = _.filter(routes, function (route) {
    return route.name === pattern
  })[0]

  /**
   * if found pattern as a named route, make it using
   * route properties
   */
  if (namedRoute) {
    const resolveRoute = namedRoute.domain ? `${namedRoute.domain}${namedRoute.route}` : namedRoute.route
    return helpers.compileRouteToUrl(resolveRoute, params)
  }
  return helpers.compileRouteToUrl(pattern, params)
}

/**
 * returns a route with it's property
 *
 * @method getRoute
 * @param  {Object} property
 *
 * @example
 * Route.getRoute({name: 'user.show'})
 * Route.getRoute({handler: 'UserController.show'})
 *
 * @return {Object}
 */
Route.getRoute = function (property) {
  const index = _.findIndex(routes, property)
  return routes[index]
}

/**
 * removes a route from routes mapping using it's name
 *
 * @method remove
 *
 * @param  {String} name
 *
 * @example
 * Route.remove('user.create')
 *
 * @public
 */
Route.remove = function (name) {
  const index = _.findIndex(routes, {name})
  routes.splice(index, 1)
}

/**
 * add formats paramters to route defination which makes
 * url to have optional extensions at the end of them.
 *
 * @method formats
 *
 * @param  {Array} formats - array of supported supports
 * @param  {Boolean} [strict=false] - Using strict mode will not register
 *                                    a plain route without any extension
 *
 * @example
 * Route.get('/user', '...').formats(['json', 'xml'])
 *
 * @public
 */
Route.formats = function (formats, strict) {
  const lastRoute = Route._lastRoute()
  helpers.addFormats(lastRoute, formats, strict)
}
<|endoftext|>


<commit_before>var dl = require('datalib'),
    template = dl.template,
    expr = require('vega-expression'),
    args = ['datum', 'parent', 'event', 'signals'];

var compile = expr.compiler(args, {
  idWhiteList: args,
  fieldVar:    args[0],
  globalVar:   function(id) {
    return 'this.sig[' + dl.str(id) + ']._value';
  },
  functions:   function(codegen) {
    var fn = expr.functions(codegen);
    fn.eventItem  = 'event.vg.getItem';
    fn.eventGroup = 'event.vg.getGroup';
    fn.eventX     = 'event.vg.getX';
    fn.eventY     = 'event.vg.getY';
    fn.open       = openGen(codegen);
    fn.scale      = scaleGen(codegen, false);
    fn.iscale     = scaleGen(codegen, true);
    fn.inrange    = 'this.defs.inrange';
    fn.indata     = indataGen(codegen);
    fn.format     = 'this.defs.format';
    fn.timeFormat = 'this.defs.timeFormat';
    fn.utcFormat  = 'this.defs.utcFormat';
    return fn;
  },
  functionDefs: function(/*codegen*/) {
    return {
      'scale':      scale,
      'inrange':    inrange,
      'indata':     indata,
      'format':     numberFormat,
      'timeFormat': timeFormat,
      'utcFormat':  utcFormat,
      'open':       windowOpen
    };
  }
});

function openGen(codegen) {
  return function (args) {
    args = args.map(codegen);
    var n = args.length;
    if (n < 1 || n > 2) {
      throw Error("open takes exactly 1 or 2 arguments.");
    }
    return 'this.defs.open(this.model, ' +
      args[0] + (n > 1 ? ',' + args[1] : '') + ')';
  };
}

function windowOpen(model, url, name) {
  if (window && window.open) {
    var opt = dl.extend({type: 'open', url: url, name: name}, model.config().load),
        uri = dl.load.sanitizeUrl(opt);
    if (uri) {
      window.open(uri, name);
    } else {
      throw Error('Invalid URL: ' + opt.url);
    }
  } else {
    throw Error("open can only be invoked in a browser.")
  }
}

function scaleGen(codegen, invert) {
  return function(args) {
    args = args.map(codegen);
    var n = args.length;
    if (n < 2 || n > 3) {
      throw Error("scale takes exactly 2 or 3 arguments.");
    }
    return 'this.defs.scale(this.model, ' + invert + ', ' +
      args[0] + ',' + args[1] + (n > 2 ? ',' + args[2] : '') + ')';
  };
}

function scale(model, invert, name, value, scope) {
  if (!scope || !scope.scale) {
    scope = (scope && scope.mark) ? scope.mark.group : model.scene().items[0];
  }
  // Verify scope is valid
  if (model.group(scope._id) !== scope) {
    throw Error('Scope for scale "'+name+'" is not a valid group item.');
  }
  var s = scope.scale(name);
  return !s ? value : (invert ? s.invert(value) : s(value));
}

function inrange(val, a, b, exclusive) {
  var min = a, max = b;
  if (a > b) { min = b; max = a; }
  return exclusive ?
    (min < val && max > val) :
    (min <= val && max >= val);
}

function indataGen(codegen) {
  return function(args, globals, fields, dataSources) {
    var data;
    if (args.length !== 3) {
      throw Error("indata takes 3 arguments.");
    }
    if (args[0].type !== 'Literal') {
      throw Error("Data source name must be a literal for indata.");
    }

    data = args[0].value;
    dataSources[data] = 1;
    if (args[2].type === 'Literal') {
      indataGen.model.requestIndex(data, args[2].value);
    }

    args = args.map(codegen);
    return 'this.defs.indata(this.model,' +
      args[0] + ',' + args[1] + ',' + args[2] + ')';
  };
}

function indata(model, dataname, val, field) {
  var data = model.data(dataname),
      index = data.getIndex(field);
  return index[val] > 0;
}

function numberFormat(specifier, v) {
  return template.format(specifier, 'number')(v);
}

function timeFormat(specifier, d) {
  return template.format(specifier, 'time')(d);
}

function utcFormat(specifier, d) {
  return template.format(specifier, 'utc')(d);
}

function wrap(model) {
  return function(str) {
    indataGen.model = model;
    var x = compile(str);
    x.model = model;
    x.sig = model ? model._signals : {};
    return x;
  };
}

wrap.scale = scale;
wrap.codegen = compile.codegen;
module.exports = wrap;
<commit_msg>Refine window.open function handling.<commit_after>var dl = require('datalib'),
    template = dl.template,
    expr = require('vega-expression'),
    args = ['datum', 'parent', 'event', 'signals'];

var compile = expr.compiler(args, {
  idWhiteList: args,
  fieldVar:    args[0],
  globalVar:   function(id) {
    return 'this.sig[' + dl.str(id) + ']._value';
  },
  functions:   function(codegen) {
    var fn = expr.functions(codegen);
    fn.eventItem  = 'event.vg.getItem';
    fn.eventGroup = 'event.vg.getGroup';
    fn.eventX     = 'event.vg.getX';
    fn.eventY     = 'event.vg.getY';
    fn.open       = openGen(codegen);
    fn.scale      = scaleGen(codegen, false);
    fn.iscale     = scaleGen(codegen, true);
    fn.inrange    = 'this.defs.inrange';
    fn.indata     = indataGen(codegen);
    fn.format     = 'this.defs.format';
    fn.timeFormat = 'this.defs.timeFormat';
    fn.utcFormat  = 'this.defs.utcFormat';
    return fn;
  },
  functionDefs: function(/*codegen*/) {
    return {
      'scale':      scale,
      'inrange':    inrange,
      'indata':     indata,
      'format':     numberFormat,
      'timeFormat': timeFormat,
      'utcFormat':  utcFormat,
      'open':       windowOpen
    };
  }
});

function openGen(codegen) {
  return function (args) {
    args = args.map(codegen);
    var n = args.length;
    if (n < 1 || n > 2) {
      throw Error("open takes exactly 1 or 2 arguments.");
    }
    return 'this.defs.open(this.model, ' +
      args[0] + (n > 1 ? ',' + args[1] : '') + ')';
  };
}

function windowOpen(model, url, name) {
  if (typeof window !== 'undefined' && window && window.open) {
    var opt = dl.extend({type: 'open', url: url, name: name}, model.config().load),
        uri = dl.load.sanitizeUrl(opt);
    if (uri) {
      window.open(uri, name);
    } else {
      throw Error('Invalid URL: ' + opt.url);
    }
  } else {
    throw Error('Open function can only be invoked in a browser.');
  }
}

function scaleGen(codegen, invert) {
  return function(args) {
    args = args.map(codegen);
    var n = args.length;
    if (n < 2 || n > 3) {
      throw Error("scale takes exactly 2 or 3 arguments.");
    }
    return 'this.defs.scale(this.model, ' + invert + ', ' +
      args[0] + ',' + args[1] + (n > 2 ? ',' + args[2] : '') + ')';
  };
}

function scale(model, invert, name, value, scope) {
  if (!scope || !scope.scale) {
    scope = (scope && scope.mark) ? scope.mark.group : model.scene().items[0];
  }
  // Verify scope is valid
  if (model.group(scope._id) !== scope) {
    throw Error('Scope for scale "'+name+'" is not a valid group item.');
  }
  var s = scope.scale(name);
  return !s ? value : (invert ? s.invert(value) : s(value));
}

function inrange(val, a, b, exclusive) {
  var min = a, max = b;
  if (a > b) { min = b; max = a; }
  return exclusive ?
    (min < val && max > val) :
    (min <= val && max >= val);
}

function indataGen(codegen) {
  return function(args, globals, fields, dataSources) {
    var data;
    if (args.length !== 3) {
      throw Error("indata takes 3 arguments.");
    }
    if (args[0].type !== 'Literal') {
      throw Error("Data source name must be a literal for indata.");
    }

    data = args[0].value;
    dataSources[data] = 1;
    if (args[2].type === 'Literal') {
      indataGen.model.requestIndex(data, args[2].value);
    }

    args = args.map(codegen);
    return 'this.defs.indata(this.model,' +
      args[0] + ',' + args[1] + ',' + args[2] + ')';
  };
}

function indata(model, dataname, val, field) {
  var data = model.data(dataname),
      index = data.getIndex(field);
  return index[val] > 0;
}

function numberFormat(specifier, v) {
  return template.format(specifier, 'number')(v);
}

function timeFormat(specifier, d) {
  return template.format(specifier, 'time')(d);
}

function utcFormat(specifier, d) {
  return template.format(specifier, 'utc')(d);
}

function wrap(model) {
  return function(str) {
    indataGen.model = model;
    var x = compile(str);
    x.model = model;
    x.sig = model ? model._signals : {};
    return x;
  };
}

wrap.scale = scale;
wrap.codegen = compile.codegen;
module.exports = wrap;
<|endoftext|>


<commit_before>/*
 string bundle utility

 Usage:
   // use instead of HTMLDocument.getBoxObjectFor(HTMLElement)
   var bundle = window['piro.sakura.ne.jp']
                         .stringBundle
                         .get('chrome://example/locale/example.properties');
   bundle.getString('key1');
   bundle.getFormattedString('key2', [val1, val2]);

 lisence: The MIT License, Copyright (c) 2009 SHIMODA "Piro" Hiroshi
   http://www.cozmixng.org/repos/piro/fx3-compatibility-lib/trunk/license.txt
 original:
   http://www.cozmixng.org/repos/piro/fx3-compatibility-lib/trunk/stringBundle.js
*/
(function() {
	const currentRevision = 1;

	if (!('piro.sakura.ne.jp' in window)) window['piro.sakura.ne.jp'] = {};

	var loadedRevision = 'stringBundle' in window['piro.sakura.ne.jp'] ?
			window['piro.sakura.ne.jp'].stringBundle.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		return;
	}

	var Cc = Components.classes;
	var Ci = Components.interfaces;

	window['piro.sakura.ne.jp'].stringBundle = {
		revision : currentRevision,

		get : function(aURI)
		{
			if (!(aURI in this._cache)) {
				this._cache[aURI] = new StringBundle(aURI);
			}
			return this._cache[aURI];
		},
		_cache : {},

		get Service()
		{
			if (!this._Service) {
				this._Service = Cc['@mozilla.org/intl/stringbundle;1']
								.getService(Ci.nsIStringBundleService);
			}
			return this._Service;
		}
	};

	function StringBundle(aURI)
	{
		this._bundle = window['piro.sakura.ne.jp'].stringBundle.createBundle(aURI);
	}
	StringBundle.prototype = {
		getString : function(aKey) {
			try {
				return this._bundle.GetStringFromName(aKey);
			}
			catch(e) {
			}
			return '';
		},
		getFormattedString : function(aKey, aArray) {
			try {
				return this._bundle.formatStringFromName(aKey, aArray, aArray.length);
			}
			catch(e) {
			}
			return '';
		},
		get strings() {
			return this._bundle.getSimpleEnumeration();
		}
	};
})();
<commit_msg>生成に失敗していた<commit_after>/*
 string bundle utility

 Usage:
   // use instead of HTMLDocument.getBoxObjectFor(HTMLElement)
   var bundle = window['piro.sakura.ne.jp']
                         .stringBundle
                         .get('chrome://example/locale/example.properties');
   bundle.getString('key1');
   bundle.getFormattedString('key2', [val1, val2]);

 lisence: The MIT License, Copyright (c) 2009 SHIMODA "Piro" Hiroshi
   http://www.cozmixng.org/repos/piro/fx3-compatibility-lib/trunk/license.txt
 original:
   http://www.cozmixng.org/repos/piro/fx3-compatibility-lib/trunk/stringBundle.js
*/
(function() {
	const currentRevision = 1;

	if (!('piro.sakura.ne.jp' in window)) window['piro.sakura.ne.jp'] = {};

	var loadedRevision = 'stringBundle' in window['piro.sakura.ne.jp'] ?
			window['piro.sakura.ne.jp'].stringBundle.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		return;
	}

	var Cc = Components.classes;
	var Ci = Components.interfaces;

	window['piro.sakura.ne.jp'].stringBundle = {
		revision : currentRevision,

		get : function(aURI)
		{
			if (!(aURI in this._cache)) {
				this._cache[aURI] = new StringBundle(aURI);
			}
			return this._cache[aURI];
		},
		_cache : {}
	};

	const Service = Cc['@mozilla.org/intl/stringbundle;1']
						.getService(Ci.nsIStringBundleService);

	function StringBundle(aURI)
	{
		this._bundle = Service.createBundle(aURI);
	}
	StringBundle.prototype = {
		getString : function(aKey) {
			try {
				return this._bundle.GetStringFromName(aKey);
			}
			catch(e) {
			}
			return '';
		},
		getFormattedString : function(aKey, aArray) {
			try {
				return this._bundle.formatStringFromName(aKey, aArray, aArray.length);
			}
			catch(e) {
			}
			return '';
		},
		get strings() {
			return this._bundle.getSimpleEnumeration();
		}
	};
})();
<|endoftext|>