<commit_before>#!/usr/bin/env node

var pollsProvider = require('./lib/pollsProvider');
var router = require('./lib/router').getInstance();
var sessionManager = require('./lib/sessionManager');
var auth = require('./lib/auth');

var http = require('http');
var fs = require('fs');
var path = require('path');

var FEEDBACKER_MASTER='fdbckr-master';

var currentPollId = 0;
var currentUser;
var currentPoll;
var currentQuestion = 0;
var clientResponses = [];
var users = 0;

function getCurrentQuestion() {
    return currentPoll.questions[currentQuestion];
}

function updateClients(responses, object) {
    responses.forEach(function (response) {
        response.write('data: '+JSON.stringify(object)+'\n\n');
    })
}

function getIndex(req, res) {
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    var page = fs.readFileSync(path.join(__dirname, 'page.html'), {encoding: 'utf8'});
    if (auth.isAuthorized(req)) {
        currentUser = req.parsedUrl.query.user;
        currentPoll = pollsProvider.initPoll(currentUser, currentPollId);
        var sessionId = sessionManager.newPresenterSession(currentUser);
        page = page.replace('', auth.getPresenterId());
        //TODO: render an html piece in a page.
        var presenterButtonsHtml = 'Your session is: '+sessionId+'
<input type="button" id="page-prev" class="response-btn" name="prev" value="< prev" onclick="submitPagingRequest(\'prev\')">' +
            '<input type="button" id="page-next" class="response-btn" name="next" value="next >" onclick="submitPagingRequest(\'next\')">';
        page = page.replace('', presenterButtonsHtml);

        res.writeHead(200, {'Content-Type': 'text/html', 'Set-Cookie': FEEDBACKER_MASTER+'='+sessionId});
        return res.end(page);
    } else {
        res.writeHead(401, {'Content-Type': 'text/html'});
        return res.end('Unauthorized');
    }
}

function getUserPage(req, res) {
    console.log('========>>> generating user page.');
    users += 1;
    var page = fs.readFileSync(path.join(__dirname, 'page.html'), {encoding: 'utf8'});
    page = page.replace('', 'happy-user-'+users);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(page);
}

function getPoll(req, res) {
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    clientResponses.push(res);
    console.log('>>>>', req.url, req.headers);
    res.writeHead(200, {'Content-Type': 'text/event-stream'});
    var currQuestion = getCurrentQuestion();
    console.log('#############################################################currQuestion', currQuestion);
    updateClients(clientResponses, currQuestion);
    return;
}

function postResponse (req, res) {
    var question = getCurrentQuestion();
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    var pollResponse = req.json;
    console.log('***** response: question:', pollResponse.question, 'response:', pollResponse.response);
    console.log('***** req.cookies:', req.headers.cookie);
    if(typeof pollResponse.question === 'number' && typeof pollResponse.response === 'number' ) {
        console.log('***** correct response: question:', pollResponse.question, 'response:', pollResponse.response);

        if(question.id === pollResponse.question && pollResponse.response <= question.responses.length - 1) {
            console.log('*** question and response found. counting.');
            question.responses[pollResponse.response].count += 1;
            updateClients(clientResponses, question);
            res.writeHead(200, "OK", {'Content-Type': 'text/html'});
        } else {
            var msg = "Not found: curr question: "+question.id+" max response: "+ question.responses.length -1;
            console.log('*** '+ msg);
            res.writeHead(404, msg, {'Content-Type': 'text/html'});
        }

    } else {
        var msg = ">>> could not parse question correctly :-(";
        console.log('====' + msg);
        res.writeHead(400, msg, {'Content-Type': 'text/html'});
    }
    res.end();

    return;

}

function postPagination(req, res){
    //curl -X POST --data '{"userId": "lksdjflsdkjf"}' http://localhost:8125/prev -v
    //curl -X POST --data '{"userId": "lksdjflsdkjf"}' http://localhost:8125/next -v
    var urlPath = req.parsedUrl.pathname;
    var isPageNextReq = urlPath.indexOf('next') !== -1;

    var pagingRequest = req.json;
    if (pagingRequest.userId !== auth.getPresenterId()) {//TODO: proper auth system.
        var msg = '%%%==> pagingRequest NOT authorized: userId: '+pagingRequest.userId+' presenterId: ' + auth.getPresenterId();
        console.log(msg, pagingRequest);

        res.writeHead(401, msg, {'Content-Type': 'text/html'});
        return res.end();
    }
    console.log('%%%==> pagingRequest authorized', pagingRequest, urlPath);
    res.writeHead(204, "Done.", {'Content-Type': 'text/html'});
    res.end();
    if(isPageNextReq) {
        console.log('=========>>>>> NEXT');
        var numberOfPolls = currentPoll.questions.length;
        if(currentQuestion < numberOfPolls -1) {
            currentQuestion += 1;
        }
    } else {
        console.log('=========>>>>> PREV');
        if(currentQuestion > 0) {
            currentQuestion -= 1;
        }
    }
    updateClients(clientResponses, getCurrentQuestion());

    return;
}

router.get('/', getIndex);
router.get('/index.html', getIndex);
router.get('/poll', getPoll);
router.get('/join', getUserPage);
router.post('/response', postResponse);
router.post('/next', postPagination);
router.post('/prev', postPagination);

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8126;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || "0.0.0.0";

http.createServer(router.route()).listen(server_port, server_ip_address);
console.log('Server running at http://'+server_ip_address+':'+server_port+'/');
<commit_msg>fix user joins before presenter<commit_after>#!/usr/bin/env node

var pollsProvider = require('./lib/pollsProvider');
var router = require('./lib/router').getInstance();
var sessionManager = require('./lib/sessionManager');
var auth = require('./lib/auth');

var http = require('http');
var fs = require('fs');
var path = require('path');

var FEEDBACKER_MASTER='fdbckr-master';

var currentPollId = 0;
var currentUser;
var currentPoll;
var currentQuestion = 0;
var clientResponses = [];
var users = 0;

function getCurrentQuestion() {
    if (!currentPoll || !currentPoll.questions) {
        return null;
    }

    return currentPoll.questions[currentQuestion];
}

function updateClients(responses, object) {
    responses.forEach(function (response) {
        response.write('data: '+JSON.stringify(object)+'\n\n');
    })
}

function getIndex(req, res) {
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    var page = fs.readFileSync(path.join(__dirname, 'page.html'), {encoding: 'utf8'});
    if (auth.isAuthorized(req)) {
        currentUser = req.parsedUrl.query.user;
        currentPoll = pollsProvider.initPoll(currentUser, currentPollId);
        var sessionId = sessionManager.newPresenterSession(currentUser);
        page = page.replace('', auth.getPresenterId());
        //TODO: render an html piece in a page.
        var presenterButtonsHtml = 'Your session is: '+sessionId+'
<input type="button" id="page-prev" class="response-btn" name="prev" value="< prev" onclick="submitPagingRequest(\'prev\')">' +
            '<input type="button" id="page-next" class="response-btn" name="next" value="next >" onclick="submitPagingRequest(\'next\')">';
        page = page.replace('', presenterButtonsHtml);

        res.writeHead(200, {'Content-Type': 'text/html', 'Set-Cookie': FEEDBACKER_MASTER+'='+sessionId});
        return res.end(page);
    } else {
        res.writeHead(401, {'Content-Type': 'text/html'});
        return res.end('Unauthorized');
    }
}

function getUserPage(req, res) {
    if (!getCurrentQuestion()) {
        res.writeHead(404, {'Content-Type': 'text/html'});
        res.end('No poll initialized yet.');
        return;
    }

    console.log('========>>> generating user page.');
    users += 1;
    var page = fs.readFileSync(path.join(__dirname, 'page.html'), {encoding: 'utf8'});
    page = page.replace('', 'happy-user-'+users);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(page);
    return;
}

function getPoll(req, res) {
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    clientResponses.push(res);
    console.log('>>>>', req.url, req.headers);
    res.writeHead(200, {'Content-Type': 'text/event-stream'});
    var currQuestion = getCurrentQuestion();
    console.log('#############################################################currQuestion', currQuestion);
    updateClients(clientResponses, currQuestion);
    return;
}

function postResponse (req, res) {
    var question = getCurrentQuestion();
    console.log('%%%%%%%%%%%%%%%% cookies:', req.cookies);
    var pollResponse = req.json;
    console.log('***** response: question:', pollResponse.question, 'response:', pollResponse.response);
    console.log('***** req.cookies:', req.headers.cookie);
    if(typeof pollResponse.question === 'number' && typeof pollResponse.response === 'number' ) {
        console.log('***** correct response: question:', pollResponse.question, 'response:', pollResponse.response);

        if(question.id === pollResponse.question && pollResponse.response <= question.responses.length - 1) {
            console.log('*** question and response found. counting.');
            question.responses[pollResponse.response].count += 1;
            updateClients(clientResponses, question);
            res.writeHead(200, "OK", {'Content-Type': 'text/html'});
        } else {
            var msg = "Not found: curr question: "+question.id+" max response: "+ question.responses.length -1;
            console.log('*** '+ msg);
            res.writeHead(404, msg, {'Content-Type': 'text/html'});
        }

    } else {
        var msg = ">>> could not parse question correctly :-(";
        console.log('====' + msg);
        res.writeHead(400, msg, {'Content-Type': 'text/html'});
    }
    res.end();

    return;

}

function postPagination(req, res){
    //curl -X POST --data '{"userId": "lksdjflsdkjf"}' http://localhost:8125/prev -v
    //curl -X POST --data '{"userId": "lksdjflsdkjf"}' http://localhost:8125/next -v
    var urlPath = req.parsedUrl.pathname;
    var isPageNextReq = urlPath.indexOf('next') !== -1;

    var pagingRequest = req.json;
    if (pagingRequest.userId !== auth.getPresenterId()) {//TODO: proper auth system.
        var msg = '%%%==> pagingRequest NOT authorized: userId: '+pagingRequest.userId+' presenterId: ' + auth.getPresenterId();
        console.log(msg, pagingRequest);

        res.writeHead(401, msg, {'Content-Type': 'text/html'});
        return res.end();
    }
    console.log('%%%==> pagingRequest authorized', pagingRequest, urlPath);
    res.writeHead(204, "Done.", {'Content-Type': 'text/html'});
    res.end();
    if(isPageNextReq) {
        console.log('=========>>>>> NEXT');
        var numberOfPolls = currentPoll.questions.length;
        if(currentQuestion < numberOfPolls -1) {
            currentQuestion += 1;
        }
    } else {
        console.log('=========>>>>> PREV');
        if(currentQuestion > 0) {
            currentQuestion -= 1;
        }
    }
    updateClients(clientResponses, getCurrentQuestion());

    return;
}

router.get('/', getIndex);
router.get('/index.html', getIndex);
router.get('/poll', getPoll);
router.get('/join', getUserPage);
router.post('/response', postResponse);
router.post('/next', postPagination);
router.post('/prev', postPagination);

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8126;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || "0.0.0.0";

http.createServer(router.route()).listen(server_port, server_ip_address);
console.log('Server running at http://'+server_ip_address+':'+server_port+'/');
<|endoftext|>


<commit_before>
import { join, resolve, relative, isAbsolute, dirname } from 'path';
import { StringLiteral } from 'babel-types';
import findUp from 'find-up';

function getConfig(configPath, findConfig) {
    var conf;
    if(!findConfig) {
        // Get webpack config
        conf = require(resolve(process.cwd(), configPath));
    } else {
        conf = require(findUp.sync(configPath));
    }

    return conf;
}

export default function({ types: t }) {
    return {
        visitor: {
            CallExpression(path, { file: { opts: { filename: filename } }, opts: { config: configPath = 'webpack.config.js', findConfig: findConfig = false } = {} }) {

                // Get webpack config
                const conf = getConfig(configPath, findConfig);

                // If the config comes back as null, we didn't find it, so throw an exception.
                if(conf === null) {
                    throw new Error('Cannot find configuration file: ' + configPath);
                }

                // exit if there's no alias config
                if(!conf.resolve || !conf.resolve.alias) {
                    return;
                }

                // Get the webpack alias config
                const aliasConf = conf.resolve.alias;

                const { callee: { name: calleeName }, arguments: args } = path.node;

                // Exit if it's not a require statement
                if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
                    return;
                }

                // Get the path of the StringLiteral
                const [{ value: filePath }] = args;

                for(let aliasFrom in aliasConf) {
                    if(aliasConf.hasOwnProperty(aliasFrom)) {

                        let aliasTo = aliasConf[aliasFrom];

                        // If the filepath is not absolute, make it absolute
                        if(!isAbsolute(aliasTo)) {
                            aliasTo = join(process.cwd(), aliasTo);
                        }

                        let regex = new RegExp(`^${aliasFrom}(\/|$)`);

                        // If the regex matches, replace by the right config
                        if(regex.test(filePath)) {
                            let relativeFilePath = relative(dirname(filename), aliasTo);

                            // In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
                            if(relativeFilePath.length === 0) {
                                relativeFilePath = '.';
                            }

                            let requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);

                            // In the unfortunate case of a file requiring the current directory which is the alias, we need to add
                            // an extra slash
                            if(requiredFilePath === '.') {
                                requiredFilePath = './';
                            }

                            path.node.arguments = [StringLiteral(requiredFilePath)];
                            return;
                        }
                    }
                }
            }
        }
    };
}
<commit_msg>transform sep of win32 to posix<commit_after>
import { join, resolve, relative, isAbsolute, dirname } from 'path';
import { StringLiteral } from 'babel-types';
import findUp from 'find-up';

function getConfig(configPath, findConfig) {
    var conf;
    if(!findConfig) {
        // Get webpack config
        conf = require(resolve(process.cwd(), configPath));
    } else {
        conf = require(findUp.sync(configPath));
    }

    return conf;
}

export default function({ types: t }) {
    return {
        visitor: {
            CallExpression(path, { file: { opts: { filename: filename } }, opts: { config: configPath = 'webpack.config.js', findConfig: findConfig = false } = {} }) {

                // Get webpack config
                const conf = getConfig(configPath, findConfig);

                // If the config comes back as null, we didn't find it, so throw an exception.
                if(conf === null) {
                    throw new Error('Cannot find configuration file: ' + configPath);
                }

                // exit if there's no alias config
                if(!conf.resolve || !conf.resolve.alias) {
                    return;
                }

                // Get the webpack alias config
                const aliasConf = conf.resolve.alias;

                const { callee: { name: calleeName }, arguments: args } = path.node;

                // Exit if it's not a require statement
                if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
                    return;
                }

                // Get the path of the StringLiteral
                const [{ value: filePath }] = args;

                for(let aliasFrom in aliasConf) {
                    if(aliasConf.hasOwnProperty(aliasFrom)) {

                        let aliasTo = aliasConf[aliasFrom];

                        // If the filepath is not absolute, make it absolute
                        if(!isAbsolute(aliasTo)) {
                            aliasTo = join(process.cwd(), aliasTo);
                        }

                        let regex = new RegExp(`^${aliasFrom}(\/|$)`);

                        // If the regex matches, replace by the right config
                        if(regex.test(filePath)) {
                            let relativeFilePath = relative(dirname(filename), aliasTo).replace(/\\/g, '/');

                            // In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
                            if(relativeFilePath.length === 0) {
                                relativeFilePath = '.';
                            }

                            let requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);

                            // In the unfortunate case of a file requiring the current directory which is the alias, we need to add
                            // an extra slash
                            if(requiredFilePath === '.') {
                                requiredFilePath = './';
                            }

                            path.node.arguments = [StringLiteral(requiredFilePath)];
                            return;
                        }
                    }
                }
            }
        }
    };
}
<|endoftext|>


<commit_before>/*global module:false, require:false */
'use strict';

// start build pattern: <!-- build:[target] output -->
// $1 is the type, $2 is the alternate search path, $3 is the destination file name
var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)?\s*-->/;

// end build pattern -- <!-- endbuild -->
var regend = /<!--\s*endbuild\s*-->/;

module.exports = function (content) {
  var blocks = getBlocks(content);

  content = updateReferences(blocks, content);

  var replaced = compactContent(blocks);

  return [ content, replaced ];
};

// Returns a hash object of all the directives for the given html. Results is
// of the following form:
//
//     {
//        'css/site.css ':[
//          '  <!-- build:css css/site.css -->',
//          '  <link rel="stylesheet" href="css/style.css">',
//          '  <!-- endbuild -->'
//        ],
//        'js/head.js ': [
//          '  <!-- build:js js/head.js -->',
//          '  <script src="js/libs/modernizr-2.5.3.min.js"></script>',
//          '  <!-- endbuild -->'
//        ],
//        'js/site.js ': [
//          '  <!-- build:js js/site.js -->',
//          '  <script src="js/plugins.js"></script>',
//          '  <script src="js/script.js"></script>',
//          '  <!-- endbuild -->'
//        ]
//     }
//
function getBlocks(body) {
  var lines = body.replace(/\r\n/g, '\n').split(/\n/),
    block = false,
    sections = {},
    last,
    removeBlockIndex = 0;

  lines.forEach(function (l) {
    var build = l.match(regbuild),
      endbuild = regend.test(l);

    if (build) {
      block = true;

      if(build[1] === 'remove') { build[3] = String(removeBlockIndex++); }
      sections[[build[1], build[3].trim()].join(':')] = last = [];
    }

    // switch back block flag when endbuild
    if (block && endbuild) {
      last.push(l);
      block = false;
    }

    if (block && last) {
      last.push(l);
    }
  });

  // sections is an array of lines starting with the build block comment opener,
  // including all the references and including the build block comment closer.
  return sections;
}

// Helpers
// -------
var helpers = {
  // useref and useref:* are used with the blocks parsed from directives
  useref: function (content, block, target, type) {
    var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n',
        lines = block.split(linefeed),
        refs = lines.slice(1, -1),
        ref = '',
        indent = (lines[0].match(/^\s*/) || [])[0];

    target = target || 'replace';

    if (refs.length) {
      if (type === 'css') {
        ref = '<link rel="stylesheet" href="' + target + '"\/>';
      } else if (type === 'js') {
        ref = '<script src="' + target + '"></script>';
      }
      else if (type == 'remove') {
        ref = '';
      }
      else if (type == 'jsasync') {
        ref = '<script src="' + target + '" async ></script>'
      }
    }
    return content.replace(block, indent + ref);
  }
};

function updateReferences(blocks, content) {

  // Determine the linefeed from the content
  var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n';

  // handle blocks
  Object.keys(blocks).forEach(function (key) {
    var block = blocks[key].join(linefeed),
      parts = key.split(':'),
      type = parts[0],
      target = parts[1];

    content = helpers.useref(content, block, target, type);
  });

  return content;
}

function compactContent(blocks) {

  var result = {};

  Object.keys(blocks).forEach(function (dest) {
    // Lines are the included scripts w/o the use blocks
    var lines = blocks[dest].slice(1, -1),
      parts = dest.split(':'),
      type = parts[0],
      // output is the useref block file
      output = parts[1],
      build = String.prototype.match.apply( blocks[dest][0], [regbuild] );

    // parse out the list of assets to handle, and update the grunt config accordingly
    var assets = lines.map(function (tag) {

      // The asset is the string of the referenced source file
      var asset = (tag.match(/(href|src)=["']([^'"]+)["']/) || [])[2];

      // Allow white space and comment in build blocks by checking if this line has an asset or not
      if (asset) {
        return asset;
      }

    }).reduce(function (a, b) {
      b = (b ? b.split(',') : '');
      return b ? a.concat(b) : a;
    }, []);

    result[type] = result[type] || {};
    result[type][output] = { 'assets': assets };
    if (build[2]) {
      // Alternate search path
      result[type][output].searchPaths = build[2];
    }
  });

  return result;
}

<commit_msg>Update index.js<commit_after>/*global module:false, require:false */
'use strict';

// start build pattern: <!-- build:[target] output -->
// $1 is the type, $2 is the alternate search path, $3 is the destination file name
// var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)?\s*-->/;
var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)?\s*([^\s]+)?\s*-->/;

// end build pattern -- <!-- endbuild -->
var regend = /<!--\s*endbuild\s*-->/;

module.exports = function (content) {
  var blocks = getBlocks(content);

  content = updateReferences(blocks, content);

  var replaced = compactContent(blocks);

  return [ content, replaced ];
};

// Returns a hash object of all the directives for the given html. Results is
// of the following form:
//
//     {
//        'css/site.css ':[
//          '  <!-- build:css css/site.css -->',
//          '  <link rel="stylesheet" href="css/style.css">',
//          '  <!-- endbuild -->'
//        ],
//        'js/head.js ': [
//          '  <!-- build:js js/head.js -->',
//          '  <script src="js/libs/modernizr-2.5.3.min.js"></script>',
//          '  <!-- endbuild -->'
//        ],
//        'js/site.js ': [
//          '  <!-- build:js js/site.js -->',
//          '  <script src="js/plugins.js"></script>',
//          '  <script src="js/script.js"></script>',
//          '  <!-- endbuild -->'
//        ]
//     }
//
function getBlocks(body) {
  var lines = body.replace(/\r\n/g, '\n').split(/\n/),
    block = false,
    sections = {},
    last,
    removeBlockIndex = 0;

  lines.forEach(function (l) {
    var build = l.match(regbuild),
      endbuild = regend.test(l);

    if (build) {
      block = true;

      if(build[1] === 'remove') { build[3] = String(removeBlockIndex++); }
      if(build[4]) {
        sections[[build[1], build[3].trim(), build[4].trim()].join(':')] = last = [];
      } else {
        sections[[build[1], build[3].trim()].join(':')] = last = [];
      }
    }

    // switch back block flag when endbuild
    if (block && endbuild) {
      last.push(l);
      block = false;
    }

    if (block && last) {
      last.push(l);
    }
  });

  // sections is an array of lines starting with the build block comment opener,
  // including all the references and including the build block comment closer.
  return sections;
}

// Helpers
// -------
var helpers = {
  // useref and useref:* are used with the blocks parsed from directives
  useref: function (content, block, target, type, attbs) {
    var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n',
        lines = block.split(linefeed),
        refs = lines.slice(1, -1),
        ref = '',
        indent = (lines[0].match(/^\s*/) || [])[0];

    target = target || 'replace';

    if (refs.length) {
      if (type === 'css') {
        ref = '<link rel="stylesheet" href="' + target + '"\/>';
      } else if (type === 'js') {
        ref = '<script src="' + target + '"></script>';
      }
      else if (type == 'remove') {
        ref = '';
      }
      else if (type == 'jsasync') {
        ref = '<script src="' + target + '" async ></script>'
      }
      else if (type == 'requirejs') {
        if(attbs) {
          ref = '<script src="' + target + '" ' + attbs + ' ></script>'
        } else {
          ref = '<script src="' + target + '"></script>';
        }
      }
    }
    return content.replace(block, indent + ref);
  }
};

function updateReferences(blocks, content) {

  // Determine the linefeed from the content
  var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n';

  // handle blocks
  Object.keys(blocks).forEach(function (key) {
    var block = blocks[key].join(linefeed),
      parts = key.split(':'),
      type = parts[0],
      target = parts[1],
      attbs =  parts[2];

    content = helpers.useref(content, block, target, type, attbs);
  });

  return content;
}

function compactContent(blocks) {

  var result = {};

  Object.keys(blocks).forEach(function (dest) {
    // Lines are the included scripts w/o the use blocks
    var lines = blocks[dest].slice(1, -1),
      parts = dest.split(':'),
      type = parts[0],
      // output is the useref block file
      output = parts[1],
      build = String.prototype.match.apply( blocks[dest][0], [regbuild] );

    // parse out the list of assets to handle, and update the grunt config accordingly
    var assets = lines.map(function (tag) {

      // The asset is the string of the referenced source file
      var asset = (tag.match(/(href|src)=["']([^'"]+)["']/) || [])[2];

      // Allow white space and comment in build blocks by checking if this line has an asset or not
      if (asset) {
        return asset;
      }

    }).reduce(function (a, b) {
      b = (b ? b.split(',') : '');
      return b ? a.concat(b) : a;
    }, []);

    result[type] = result[type] || {};
    result[type][output] = { 'assets': assets };
    if (build[2]) {
      // Alternate search path
      result[type][output].searchPaths = build[2];
    }
  });

  return result;
}
<|endoftext|>


<commit_before>/**
 * The options that can be specified as part of a history navigation request.
 */
interface NavigationOptions {
  /**
   * Replace the existing route.
   */
  replace?: boolean;

  /**
   * Trigger the router.
   */
  trigger?: boolean;
}

/**
 * An abstract base class for implementors of the basic history api.
 */
export class History {
  /**
   * Activates the history object.
   * @param options The set of options to activate history with.
   */
  activate(options: Object) : boolean {
    throw new Error('History must implement activate().');
  }

  /**
   * Deactivates the history object.
   */
  deactivate(): void {
    throw new Error('History must implement deactivate().');
  }

  /**
   * Causes a history navigation to occur.
   * @param fragment The history fragment to navigate to.
   * @param options The set of options that specify how the navigation should occur.
   * @return True if navigation occurred/false otherwise.
   */
  navigate(fragment: string, options?: NavigationOptions): boolean {
    throw new Error('History must implement navigate().');
  }

  /**
   * Causes the history state to navigate back.
   */
  navigateBack(): void {
    throw new Error('History must implement navigateBack().');
  }
}
<commit_msg>feat(history): add method for setting the title<commit_after>/**
 * The options that can be specified as part of a history navigation request.
 */
interface NavigationOptions {
  /**
   * Replace the existing route.
   */
  replace?: boolean;

  /**
   * Trigger the router.
   */
  trigger?: boolean;
}

/**
 * An abstract base class for implementors of the basic history api.
 */
export class History {
  /**
   * Activates the history object.
   *
   * @param options The set of options to activate history with.
   */
  activate(options: Object): boolean {
    throw new Error('History must implement activate().');
  }

  /**
   * Deactivates the history object.
   */
  deactivate(): void {
    throw new Error('History must implement deactivate().');
  }

  /**
   * Causes a history navigation to occur.
   *
   * @param fragment The history fragment to navigate to.
   * @param options The set of options that specify how the navigation should occur.
   * @return True if navigation occurred/false otherwise.
   */
  navigate(fragment: string, options?: NavigationOptions): boolean {
    throw new Error('History must implement navigate().');
  }

  /**
   * Causes the history state to navigate back.
   */
  navigateBack(): void {
    throw new Error('History must implement navigateBack().');
  }

  /**
   * Updates the title associated with the current location.
   */
  setTitle(title: string): void {
    throw new Error('History must implement setTitle().');
  }
}
<|endoftext|>


<commit_before>const caseless = require('caseless');
const qs = require('qs');
const fetch = require('cross-fetch');
const urlJoin = require('url-join');
const AbortController = require('abort-controller');

const Interceptor = require('./interceptor');

const methods = ['get', 'head', 'post', 'put', 'del', 'options', 'patch'];

const respProperties = {
  readOnly: [
    'headers',
    'ok',
    'redirected',
    'status',
    'statusText',
    'type',
    'url',
    'bodyUsed'
  ],
  writable: ['useFinalURL'],
  callable: [
    'clone',
    'error',
    'redirect',
    'arrayBuffer',
    'blob',
    'formData',
    'json',
    'text'
  ]
};

function overwriteOnAbortWith(signal, callback) {
  const _onAbort = signal.onabort;
  signal.onabort = () => {
    _onAbort && _onAbort();
    callback();
  };
}

function createFrisbeeResponse(origResp) {
  const resp = {
    originalResponse: origResp
  };

  respProperties.readOnly.forEach(prop =>
    Object.defineProperty(resp, prop, {
      value: origResp[prop]
    })
  );

  respProperties.writable.forEach(prop =>
    Object.defineProperty(resp, prop, {
      get() {
        return origResp[prop];
      },
      set(value) {
        origResp[prop] = value;
      }
    })
  );

  let callable = null;
  respProperties.callable.forEach(prop => {
    Object.defineProperty(resp, prop, {
      value: ((callable = origResp[prop]),
      typeof callable === 'function' && callable.bind(origResp))
    });
  });

  const headersObj = {};
  origResp.headers.forEach(pair => {
    headersObj[pair[0]] = pair[1];
  });
  Object.defineProperty(resp, 'headersObj', {
    value: headersObj
  });

  return resp;
}

class Frisbee {
  constructor(opts = {}) {
    this.opts = opts;

    let localAbortController;
    Object.defineProperty(this, 'abortController', {
      enumerable: false,
      get() {
        if (!localAbortController) {
          localAbortController = new AbortController();
          localAbortController.signal.onabort = () => {
            // when this is aborted, null out the localAbortController
            // so we'll create a new one next time we need it
            localAbortController = null;
          };
        }
        return localAbortController;
      }
    });

    let localAbortTokenMap = new Map();
    Object.defineProperty(this, 'abortTokenMap', {
      enumerable: false,
      value: localAbortTokenMap
    });

    Object.defineProperty(this, 'parseErr', {
      enumerable: false,
      value:
        opts.parseErr ||
        new Error(
          `Invalid JSON received${opts.baseURI ? ` from ${opts.baseURI}` : ''}`
        )
    });

    this.headers = {
      ...opts.headers
    };

    this.arrayFormat = opts.arrayFormat || 'indices';

    this.raw = opts.raw === true;

    if (opts.auth) this.auth(opts.auth);

    methods.forEach(method => {
      this[method] = this._setup(method);
    });

    // interceptor should be initialized after methods setup
    this.interceptor = new Interceptor(this, methods);
  }

  abort(token) {
    const mapValue = this.abortTokenMap.get(token);
    if (mapValue && mapValue.abortController) {
      mapValue.abortController.abort();
    }
  }

  abortAll() {
    this.abortController.abort();
  }

  _setup(method) {
    return (originalPath = '/', originalOptions = {}) => {
      if (originalOptions && typeof originalOptions === 'object') {
        let abortController;
        if (originalOptions.abortToken) {
          // allow to use a single token to cancel multiple requests
          let mapValue = this.abortTokenMap.get(originalOptions.abortToken);
          if (!mapValue) {
            mapValue = {
              abortController: new AbortController(),
              count: 0
            };
          }
          mapValue.count++;

          this.abortTokenMap.set(originalOptions.abortToken, mapValue);
          abortController = mapValue.abortController;
        } else {
          abortController = new AbortController();
        }

        // the user has defined their own signal we won't use it directly, but we'll listen to it
        if (originalOptions.signal) {
          overwriteOnAbortWith(originalOptions.signal, () =>
            abortController.abort()
          );
        }

        overwriteOnAbortWith(this.abortController.signal, () =>
          abortController.abort()
        );
        originalOptions.signal = abortController.signal;
      }

      // these can't change with interceptors, otherwise we're in weird behaviour land
      const { signal, abortToken } = originalOptions;

      return async (path = originalPath, options = originalOptions) => {
        // path must be string
        if (typeof path !== 'string')
          throw new TypeError('`path` must be a string');

        // otherwise check if its an object
        if (typeof options !== 'object' || Array.isArray(options))
          throw new TypeError('`options` must be an object');

        if (options.abortToken !== abortToken) {
          throw new Error('abortToken cannot be modified via an interceptor');
        }

        if (options.signal !== signal) {
          throw new Error('signal cannot be modified via an interceptor');
        }

        const { raw, ...noRaw } = options;

        const opts = {
          ...noRaw,
          headers: {
            ...this.headers,
            ...options.headers
          },
          method: method === 'del' ? 'DELETE' : method.toUpperCase()
        };

        // remove any nil or blank headers
        // (e.g. to automatically set Content-Type with `FormData` boundary)
        Object.keys(opts.headers).forEach(key => {
          if (
            typeof opts.headers[key] === 'undefined' ||
            opts.headers[key] === null ||
            opts.headers[key] === ''
          )
            delete opts.headers[key];
        });

        const c = caseless(opts.headers);

        // in order to support Android POST requests
        // we must allow an empty body to be sent
        // https://github.com/facebook/react-native/issues/4890
        if (typeof opts.body === 'undefined' && opts.method === 'POST') {
          opts.body = '';
        } else if (typeof opts.body === 'object' || Array.isArray(opts.body)) {
          if (opts.method === 'GET' || opts.method === 'DELETE') {
            const { arrayFormat } = this;
            path += `?${qs.stringify(opts.body, { arrayFormat })}`;
            delete opts.body;
          } else if (
            c.get('Content-Type') &&
            c.get('Content-Type').split(';')[0] === 'application/json'
          ) {
            try {
              opts.body = JSON.stringify(opts.body);
            } catch (error) {
              throw error;
            }
          }
        }

        // eslint-disable-next-line no-async-promise-executor
        const response = new Promise(async (resolve, reject) => {
          try {
            const fullUri = this.opts.baseURI
              ? urlJoin(this.opts.baseURI, path)
              : path;
            const originalRes = await fetch(fullUri, opts);
            const res = createFrisbeeResponse(originalRes);
            const contentType = res.headers.get('Content-Type');

            if (!res.ok) {
              res.err = new Error(res.statusText);

              // check if the response was JSON, and if so, better the error
              if (contentType && contentType.includes('application/json')) {
                try {
                  // attempt to parse json body to use as error message
                  if (typeof res.json === 'function') {
                    res.body = await res.json();
                  } else {
                    res.body = await res.text();
                    res.body = JSON.parse(res.body);
                  }

                  // attempt to use better and human-friendly error messages
                  if (
                    typeof res.body === 'object' &&
                    typeof res.body.message === 'string'
                  ) {
                    res.err = new Error(res.body.message);
                  } else if (
                    !Array.isArray(res.body) &&
                    // attempt to utilize Stripe-inspired error messages
                    typeof res.body.error === 'object'
                  ) {
                    if (res.body.error.message)
                      res.err = new Error(res.body.error.message);
                    if (res.body.error.stack)
                      res.err.stack = res.body.error.stack;
                    if (res.body.error.code) res.err.code = res.body.error.code;
                    if (res.body.error.param)
                      res.err.param = res.body.error.param;
                  }
                } catch (error) {
                  res.err = this.parseErr;
                }
              }

              resolve(res);
              return;
            }

            // if we just want a raw response then return early
            if (raw === true || (this.raw && raw !== false))
              return resolve(res.originalResponse);

            // determine whether we're returning text or json for body
            if (contentType && contentType.includes('application/json')) {
              try {
                if (typeof res.json === 'function') {
                  res.body = await res.json();
                } else {
                  res.body = await res.text();
                  res.body = JSON.parse(res.body);
                }
              } catch (error) {
                if (contentType === 'application/json') {
                  res.err = this.parseErr;
                  resolve(res);
                  return;
                }
              }
            } else {
              res.body = await res.text();
            }

            resolve(res);
          } catch (error) {
            reject(error);
          }
        });

        try {
          await response;
        } catch (e) {}

        // update the abortTokenMap
        let mapValue = this.abortTokenMap.get(options.abortToken);
        if (mapValue && !--mapValue.count) {
          this.abortTokenMap.delete(options.abortToken);
        }

        return response;
      };
    };
  }

  auth(creds) {
    if (typeof creds === 'string') {
      const index = creds.indexOf(':');
      if (index !== -1)
        creds = [creds.substr(0, index), creds.substr(index + 1)];
    }

    if (!Array.isArray(creds)) {
      // eslint-disable-next-line prefer-rest-params
      creds = [].slice.call(arguments);
    }

    switch (creds.length) {
      case 0:
        creds = ['', ''];
        break;
      case 1:
        creds.push('');
        break;
      case 2:
        break;
      default:
        throw new Error('auth option can only have two keys `[user, pass]`');
    }

    if (typeof creds[0] !== 'string')
      throw new TypeError('auth option `user` must be a string');

    if (typeof creds[1] !== 'string')
      throw new TypeError('auth option `pass` must be a string');

    if (!creds[0] && !creds[1]) {
      delete this.headers.Authorization;
    } else {
      this.headers.Authorization = `Basic ${Buffer.from(
        creds.join(':')
      ).toString('base64')}`;
    }

    return this;
  }

  jwt(token) {
    if (token === null || token === undefined)
      delete this.headers.Authorization;
    else if (typeof token === 'string')
      this.headers.Authorization = `Bearer ${token}`;
    else throw new TypeError('jwt token must be a string');

    return this;
  }
}

module.exports = Frisbee;
<commit_msg>Clarifying comment<commit_after>const caseless = require('caseless');
const qs = require('qs');
const fetch = require('cross-fetch');
const urlJoin = require('url-join');
const AbortController = require('abort-controller');

const Interceptor = require('./interceptor');

const methods = ['get', 'head', 'post', 'put', 'del', 'options', 'patch'];

const respProperties = {
  readOnly: [
    'headers',
    'ok',
    'redirected',
    'status',
    'statusText',
    'type',
    'url',
    'bodyUsed'
  ],
  writable: ['useFinalURL'],
  callable: [
    'clone',
    'error',
    'redirect',
    'arrayBuffer',
    'blob',
    'formData',
    'json',
    'text'
  ]
};

function overwriteOnAbortWith(signal, callback) {
  const _onAbort = signal.onabort;
  signal.onabort = () => {
    _onAbort && _onAbort();
    callback();
  };
}

function createFrisbeeResponse(origResp) {
  const resp = {
    originalResponse: origResp
  };

  respProperties.readOnly.forEach(prop =>
    Object.defineProperty(resp, prop, {
      value: origResp[prop]
    })
  );

  respProperties.writable.forEach(prop =>
    Object.defineProperty(resp, prop, {
      get() {
        return origResp[prop];
      },
      set(value) {
        origResp[prop] = value;
      }
    })
  );

  let callable = null;
  respProperties.callable.forEach(prop => {
    Object.defineProperty(resp, prop, {
      value: ((callable = origResp[prop]),
      typeof callable === 'function' && callable.bind(origResp))
    });
  });

  const headersObj = {};
  origResp.headers.forEach(pair => {
    headersObj[pair[0]] = pair[1];
  });
  Object.defineProperty(resp, 'headersObj', {
    value: headersObj
  });

  return resp;
}

class Frisbee {
  constructor(opts = {}) {
    this.opts = opts;

    let localAbortController;
    Object.defineProperty(this, 'abortController', {
      enumerable: false,
      get() {
        if (!localAbortController) {
          localAbortController = new AbortController();
          localAbortController.signal.onabort = () => {
            // when this is aborted, null out the localAbortController
            // so we'll create a new one next time we need it
            localAbortController = null;
          };
        }
        return localAbortController;
      }
    });

    let localAbortTokenMap = new Map();
    Object.defineProperty(this, 'abortTokenMap', {
      enumerable: false,
      value: localAbortTokenMap
    });

    Object.defineProperty(this, 'parseErr', {
      enumerable: false,
      value:
        opts.parseErr ||
        new Error(
          `Invalid JSON received${opts.baseURI ? ` from ${opts.baseURI}` : ''}`
        )
    });

    this.headers = {
      ...opts.headers
    };

    this.arrayFormat = opts.arrayFormat || 'indices';

    this.raw = opts.raw === true;

    if (opts.auth) this.auth(opts.auth);

    methods.forEach(method => {
      this[method] = this._setup(method);
    });

    // interceptor should be initialized after methods setup
    this.interceptor = new Interceptor(this, methods);
  }

  abort(token) {
    const mapValue = this.abortTokenMap.get(token);
    if (mapValue && mapValue.abortController) {
      mapValue.abortController.abort();
    }
  }

  abortAll() {
    this.abortController.abort();
  }

  _setup(method) {
    return (originalPath = '/', originalOptions = {}) => {
      if (originalOptions && typeof originalOptions === 'object') {
        let abortController;
        if (originalOptions.abortToken) {
          // allow to use a single token to cancel multiple requests
          let mapValue = this.abortTokenMap.get(originalOptions.abortToken);
          if (!mapValue) {
            mapValue = {
              abortController: new AbortController(),
              count: 0
            };
          }
          mapValue.count++;

          this.abortTokenMap.set(originalOptions.abortToken, mapValue);
          abortController = mapValue.abortController;
        } else {
          abortController = new AbortController();
        }

        // the user has defined their own signal we won't use it directly, but we'll listen to it
        if (originalOptions.signal) {
          overwriteOnAbortWith(originalOptions.signal, () =>
            abortController.abort()
          );
        }

        // abort this request whenever this.abortController.abort() gets called - a.k.a. - abortAll()
        overwriteOnAbortWith(this.abortController.signal, () =>
          abortController.abort()
        );
        originalOptions.signal = abortController.signal;
      }

      // these can't change with interceptors, otherwise we're in weird behaviour land
      const { signal, abortToken } = originalOptions;

      return async (path = originalPath, options = originalOptions) => {
        // path must be string
        if (typeof path !== 'string')
          throw new TypeError('`path` must be a string');

        // otherwise check if its an object
        if (typeof options !== 'object' || Array.isArray(options))
          throw new TypeError('`options` must be an object');

        if (options.abortToken !== abortToken) {
          throw new Error('abortToken cannot be modified via an interceptor');
        }

        if (options.signal !== signal) {
          throw new Error('signal cannot be modified via an interceptor');
        }

        const { raw, ...noRaw } = options;

        const opts = {
          ...noRaw,
          headers: {
            ...this.headers,
            ...options.headers
          },
          method: method === 'del' ? 'DELETE' : method.toUpperCase()
        };

        // remove any nil or blank headers
        // (e.g. to automatically set Content-Type with `FormData` boundary)
        Object.keys(opts.headers).forEach(key => {
          if (
            typeof opts.headers[key] === 'undefined' ||
            opts.headers[key] === null ||
            opts.headers[key] === ''
          )
            delete opts.headers[key];
        });

        const c = caseless(opts.headers);

        // in order to support Android POST requests
        // we must allow an empty body to be sent
        // https://github.com/facebook/react-native/issues/4890
        if (typeof opts.body === 'undefined' && opts.method === 'POST') {
          opts.body = '';
        } else if (typeof opts.body === 'object' || Array.isArray(opts.body)) {
          if (opts.method === 'GET' || opts.method === 'DELETE') {
            const { arrayFormat } = this;
            path += `?${qs.stringify(opts.body, { arrayFormat })}`;
            delete opts.body;
          } else if (
            c.get('Content-Type') &&
            c.get('Content-Type').split(';')[0] === 'application/json'
          ) {
            try {
              opts.body = JSON.stringify(opts.body);
            } catch (error) {
              throw error;
            }
          }
        }

        // eslint-disable-next-line no-async-promise-executor
        const response = new Promise(async (resolve, reject) => {
          try {
            const fullUri = this.opts.baseURI
              ? urlJoin(this.opts.baseURI, path)
              : path;
            const originalRes = await fetch(fullUri, opts);
            const res = createFrisbeeResponse(originalRes);
            const contentType = res.headers.get('Content-Type');

            if (!res.ok) {
              res.err = new Error(res.statusText);

              // check if the response was JSON, and if so, better the error
              if (contentType && contentType.includes('application/json')) {
                try {
                  // attempt to parse json body to use as error message
                  if (typeof res.json === 'function') {
                    res.body = await res.json();
                  } else {
                    res.body = await res.text();
                    res.body = JSON.parse(res.body);
                  }

                  // attempt to use better and human-friendly error messages
                  if (
                    typeof res.body === 'object' &&
                    typeof res.body.message === 'string'
                  ) {
                    res.err = new Error(res.body.message);
                  } else if (
                    !Array.isArray(res.body) &&
                    // attempt to utilize Stripe-inspired error messages
                    typeof res.body.error === 'object'
                  ) {
                    if (res.body.error.message)
                      res.err = new Error(res.body.error.message);
                    if (res.body.error.stack)
                      res.err.stack = res.body.error.stack;
                    if (res.body.error.code) res.err.code = res.body.error.code;
                    if (res.body.error.param)
                      res.err.param = res.body.error.param;
                  }
                } catch (error) {
                  res.err = this.parseErr;
                }
              }

              resolve(res);
              return;
            }

            // if we just want a raw response then return early
            if (raw === true || (this.raw && raw !== false))
              return resolve(res.originalResponse);

            // determine whether we're returning text or json for body
            if (contentType && contentType.includes('application/json')) {
              try {
                if (typeof res.json === 'function') {
                  res.body = await res.json();
                } else {
                  res.body = await res.text();
                  res.body = JSON.parse(res.body);
                }
              } catch (error) {
                if (contentType === 'application/json') {
                  res.err = this.parseErr;
                  resolve(res);
                  return;
                }
              }
            } else {
              res.body = await res.text();
            }

            resolve(res);
          } catch (error) {
            reject(error);
          }
        });

        try {
          await response;
        } catch (e) {}

        // update the abortTokenMap
        let mapValue = this.abortTokenMap.get(options.abortToken);
        if (mapValue && !--mapValue.count) {
          this.abortTokenMap.delete(options.abortToken);
        }

        return response;
      };
    };
  }

  auth(creds) {
    if (typeof creds === 'string') {
      const index = creds.indexOf(':');
      if (index !== -1)
        creds = [creds.substr(0, index), creds.substr(index + 1)];
    }

    if (!Array.isArray(creds)) {
      // eslint-disable-next-line prefer-rest-params
      creds = [].slice.call(arguments);
    }

    switch (creds.length) {
      case 0:
        creds = ['', ''];
        break;
      case 1:
        creds.push('');
        break;
      case 2:
        break;
      default:
        throw new Error('auth option can only have two keys `[user, pass]`');
    }

    if (typeof creds[0] !== 'string')
      throw new TypeError('auth option `user` must be a string');

    if (typeof creds[1] !== 'string')
      throw new TypeError('auth option `pass` must be a string');

    if (!creds[0] && !creds[1]) {
      delete this.headers.Authorization;
    } else {
      this.headers.Authorization = `Basic ${Buffer.from(
        creds.join(':')
      ).toString('base64')}`;
    }

    return this;
  }

  jwt(token) {
    if (token === null || token === undefined)
      delete this.headers.Authorization;
    else if (typeof token === 'string')
      this.headers.Authorization = `Bearer ${token}`;
    else throw new TypeError('jwt token must be a string');

    return this;
  }
}

module.exports = Frisbee;
<|endoftext|>


<commit_before>export Alert from './Alert';
export Badge from './Badge';
export Breadcrumb from './Breadcrumb';
export BreadcrumbItem from './BreadcrumbItem';
export Button from './Button';
export ButtonGroup from './ButtonGroup';
export ButtonToolbar from './ButtonToolbar';
export Card from './Card';
export CardColumns from './CardColumns';
export CardDeck from './CardDeck';
export CardImg from './CardImg';
export CardGroup from './CardGroup';
export Carousel from './Carousel';
export CarouselItem from './CarouselItem';
export CloseButton from './CloseButton';
export Col from './Col';
export Collapse from './Collapse';
export Dropdown from './Dropdown';
export DropdownButton from './DropdownButton';
export Fade from './Fade';

export Form from './Form';
export FormControl from './FormControl';
export FormCheck from './FormCheck';
export FormGroup from './FormGroup';
export FormLabel from './FormLabel';
export FormText from './FormText';

export Container from './Container';
export Image from './Image';
export Figure from './Figure';
export InputGroup from './InputGroup';
export Jumbotron from './Jumbotron';
export ListGroup from './ListGroup';
export ListGroupItem from './ListGroupItem';
export Media from './Media';
export Modal from './Modal';
export ModalBody from './ModalBody';
export ModalDialog from './ModalDialog';
export ModalFooter from './ModalFooter';
export ModalTitle from './ModalTitle';
export Nav from './Nav';
export Navbar from './Navbar';
export NavbarBrand from './NavbarBrand';
export NavDropdown from './NavDropdown';
export NavItem from './NavItem';
export Overlay from './Overlay';
export OverlayTrigger from './OverlayTrigger';
export PageItem from './PageItem';
export Pagination from './Pagination';
export Popover from './Popover';
export ProgressBar from './ProgressBar';
export ResponsiveEmbed from './ResponsiveEmbed';
export Row from './Row';
export SafeAnchor from './SafeAnchor';
export Spinner from './Spinner';
export SplitButton from './SplitButton';
export Tab from './Tab';
export TabContainer from './TabContainer';
export TabContent from './TabContent';
export Table from './Table';
export TabPane from './TabPane';
export Tabs from './Tabs';
export ThemeProvider from './ThemeProvider';
export ToggleButton from './ToggleButton';
export ToggleButtonGroup from './ToggleButtonGroup';
export Tooltip from './Tooltip';
<commit_msg>Export the DropdownItem from index (#3437)<commit_after>export Alert from './Alert';
export Badge from './Badge';
export Breadcrumb from './Breadcrumb';
export BreadcrumbItem from './BreadcrumbItem';
export Button from './Button';
export ButtonGroup from './ButtonGroup';
export ButtonToolbar from './ButtonToolbar';
export Card from './Card';
export CardColumns from './CardColumns';
export CardDeck from './CardDeck';
export CardImg from './CardImg';
export CardGroup from './CardGroup';
export Carousel from './Carousel';
export CarouselItem from './CarouselItem';
export CloseButton from './CloseButton';
export Col from './Col';
export Collapse from './Collapse';
export Dropdown from './Dropdown';
export DropdownButton from './DropdownButton';
export DropdownItem from './DropdownItem';
export Fade from './Fade';

export Form from './Form';
export FormControl from './FormControl';
export FormCheck from './FormCheck';
export FormGroup from './FormGroup';
export FormLabel from './FormLabel';
export FormText from './FormText';

export Container from './Container';
export Image from './Image';
export Figure from './Figure';
export InputGroup from './InputGroup';
export Jumbotron from './Jumbotron';
export ListGroup from './ListGroup';
export ListGroupItem from './ListGroupItem';
export Media from './Media';
export Modal from './Modal';
export ModalBody from './ModalBody';
export ModalDialog from './ModalDialog';
export ModalFooter from './ModalFooter';
export ModalTitle from './ModalTitle';
export Nav from './Nav';
export Navbar from './Navbar';
export NavbarBrand from './NavbarBrand';
export NavDropdown from './NavDropdown';
export NavItem from './NavItem';
export Overlay from './Overlay';
export OverlayTrigger from './OverlayTrigger';
export PageItem from './PageItem';
export Pagination from './Pagination';
export Popover from './Popover';
export ProgressBar from './ProgressBar';
export ResponsiveEmbed from './ResponsiveEmbed';
export Row from './Row';
export SafeAnchor from './SafeAnchor';
export Spinner from './Spinner';
export SplitButton from './SplitButton';
export Tab from './Tab';
export TabContainer from './TabContainer';
export TabContent from './TabContent';
export Table from './Table';
export TabPane from './TabPane';
export Tabs from './Tabs';
export ThemeProvider from './ThemeProvider';
export ToggleButton from './ToggleButton';
export ToggleButtonGroup from './ToggleButtonGroup';
export Tooltip from './Tooltip';
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var normalize = require('normalize-path')
var findParentDir = require('find-parent-dir')
var hooks = require('./hooks.json')
var pkg = require('../package.json')

function write (filename, data) {
  fs.writeFileSync(filename, data)
  fs.chmodSync(filename, parseInt('0755', 8))
}

function isHusky (filename) {
  var data = fs.readFileSync(filename, 'utf-8')
  return data.indexOf('#husky') !== -1
}

function findHooksDir (dirname) {
  var dir = findParentDir.sync(dirname, '.git')

  if (dir) {
    var gitDir = path.join(dir, '.git')
    var stats = fs.lstatSync(gitDir)

    if (stats.isFile()) {
      // Expect following format
      // git: pathToGit
      gitDir = fs
        .readFileSync(gitDir, 'utf-8')
        .split(':')[1]
        .trim()

      return path.join(dir, gitDir, 'hooks')
    }

    return path.join(gitDir, 'hooks')
  }
}

function getHookScript (hookName, relativePath, cmd) {
    // On Windows normalize path (i.e. convert \ to /)
  var normalizedPath = normalize(relativePath)

  // Hook script
  var arr = [
    '#!/bin/sh',
    '#husky ' + pkg.version,
    '',
    'command_exists () {',
    '  command -v "$1" >/dev/null 2>&1',
    '}',
    '',

    'load_nvm () {',
    '  export $1=$2',
    '  [ -s "$1/nvm.sh" ] && . $1/nvm.sh',
    '  exists nvm && [ -f .nvmrc ] && nvm use',
    '}',
    '',

    'has_hook_script () {',
    '  [ -f package.json ] && cat package.json | grep -q \'"$1"\\s*:\'',
    '}',
    ''
  ]

  arr = arr.concat([
    'cd ' + normalizedPath,
    '',
    // Fix for issue #16 #24
    // If script is not defined in package.json then exit
    'has_hook_script ' + cmd + ' || exit 0',
    ''
  ])

  // On OS X and Linux, try to use nvm if it's installed
  if (process.platform !== 'win32') {
    // ~ is unavaible, so $HOME is used
    var home = process.env.HOME

    if (process.platform === 'darwin') {
      // Add
      // Brew standard installation path /use/local/bin
      // Node standard installation path /usr/local
      // for GUI apps
      // https://github.com/typicode/husky/issues/49
      arr = arr.concat([
        'export PATH=$PATH:/usr/local/bin:/usr/local'
      ])
    }

    if (process.platform === 'darwin') {
      arr = arr.concat([
        'exists npm || load_nvm BREW_NVM_DIR /usr/local/opt/nvm',
        ''
      ])
    }

    arr = arr.concat([
      'exists npm || load_nvm NVM_DIR ' + home + '/.nvm',
      ''
    ])
  } else {
    // Add
    // Node standard installation path /c/Program Files/nodejs
    // for GUI apps
    // https://github.com/typicode/husky/issues/49
    arr = arr.concat([
      'export PATH="$PATH:/c/Program Files/nodejs"'
    ])
  }

  // Can't find npm message
  var npmNotFound = '> husky - Can\'t find npm in PATH. Skipping ' + cmd + ' script in package.json'

  arr = arr.concat([
    // Test if npm is in PATH
    'exists npm || {',
    '  echo >&2 "' + npmNotFound + '"',
    '  exit 0',
    '}',
    '',

    // Run script
    'echo',
    'echo "husky > npm run -s ' + cmd,
    'echo',
    '',

    'export GIT_PARAMS="$*"',
    'npm run -s ' + cmd + ' || {',
    '  echo',
    '  echo "> husky - ' + hookName + ' hook failed (add --no-verify to bypass)"',
    '  echo "> husky - To debug, use \'npm run precommit\'',
    '  exit 1',
    '}',
    ''
  ])

  return arr.join('\n')
}

function createHook (huskyDir, hooksDir, hookName, cmd) {
  var filename = path.join(hooksDir, hookName)

  // Assuming that this file is in node_modules/husky
  var packageDir = path.join(huskyDir, '..', '..')

  // Get project directory
  // When used in submodule, the project dir is the first .git that is found
  var projectDir = findParentDir.sync(huskyDir, '.git')

  // In order to support projects with package.json in a different directory
  // than .git, find relative path from project directory to package.json
  var relativePath = path.join('.', path.relative(projectDir, packageDir))

  var hookScript = getHookScript(hookName, relativePath, cmd)

  // Create hooks directory if needed
  if (!fs.existsSync(hooksDir)) fs.mkdirSync(hooksDir)

  if (!fs.existsSync(filename)) {
    write(filename, hookScript)
  } else {
    if (isHusky(filename)) {
      write(filename, hookScript)
    } else {
      console.log('skipping ' + hookName + ' hook (existing user hook)')
    }
  }
}

function removeHook (dir, name) {
  var filename = dir + '/' + name

  if (fs.existsSync(filename) && isHusky(filename)) {
    fs.unlinkSync(dir + '/' + name)
  }
}

function installFrom (huskyDir) {
  try {
    var isInSubNodeModule = (huskyDir.match(/node_modules/g) || []).length > 1
    if (isInSubNodeModule) {
      return console.log(
        'Trying to install from sub \'node_module\' directory,',
        'skipping Git hooks installation'
      )
    }

    var hooksDir = findHooksDir(huskyDir)

    if (hooksDir) {
      hooks.forEach(function (hookName) {
        var npmScriptName = hookName.replace(/-/g, '')
        createHook(huskyDir, hooksDir, hookName, npmScriptName)
      })
      console.log('done\n')
    } else {
      console.log('Can\'t find .git directory, skipping Git hooks installation')
    }
  } catch (e) {
    console.error(e)
  }
}

function uninstallFrom (huskyDir) {
  try {
    var hooksDir = findHooksDir(huskyDir)

    hooks.forEach(function (hookName) {
      removeHook(hooksDir, hookName)
    })
    console.log('done\n')
  } catch (e) {
    console.error(e)
  }
}

module.exports = {
  installFrom: installFrom,
  uninstallFrom: uninstallFrom
}
<commit_msg>Fix script<commit_after>var fs = require('fs')
var path = require('path')
var normalize = require('normalize-path')
var findParentDir = require('find-parent-dir')
var hooks = require('./hooks.json')
var pkg = require('../package.json')

function write (filename, data) {
  fs.writeFileSync(filename, data)
  fs.chmodSync(filename, parseInt('0755', 8))
}

function isHusky (filename) {
  var data = fs.readFileSync(filename, 'utf-8')
  return data.indexOf('#husky') !== -1
}

function findHooksDir (dirname) {
  var dir = findParentDir.sync(dirname, '.git')

  if (dir) {
    var gitDir = path.join(dir, '.git')
    var stats = fs.lstatSync(gitDir)

    if (stats.isFile()) {
      // Expect following format
      // git: pathToGit
      gitDir = fs
        .readFileSync(gitDir, 'utf-8')
        .split(':')[1]
        .trim()

      return path.join(dir, gitDir, 'hooks')
    }

    return path.join(gitDir, 'hooks')
  }
}

function getHookScript (hookName, relativePath, cmd) {
    // On Windows normalize path (i.e. convert \ to /)
  var normalizedPath = normalize(relativePath)

  // Hook script
  var arr = [
    '#!/bin/sh',
    '#husky ' + pkg.version,
    '',
    'command_exists () {',
    '  command -v "$1" >/dev/null 2>&1',
    '}',
    '',

    'load_nvm () {',
    '  export $1=$2',
    '  [ -s "$1/nvm.sh" ] && . $1/nvm.sh',
    '  exists nvm && [ -f .nvmrc ] && nvm use',
    '}',
    '',

    'has_hook_script () {',
    '  [ -f package.json ] && cat package.json | grep -q "\\"$1\\"\\s*:"',
    '}',
    ''
  ]

  arr = arr.concat([
    'cd ' + normalizedPath,
    '',
    // Fix for issue #16 #24
    // If script is not defined in package.json then exit
    'has_hook_script ' + cmd + ' || exit 0',
    ''
  ])

  // On OS X and Linux, try to use nvm if it's installed
  if (process.platform !== 'win32') {
    // ~ is unavaible, so $HOME is used
    var home = process.env.HOME

    if (process.platform === 'darwin') {
      // Add
      // Brew standard installation path /use/local/bin
      // Node standard installation path /usr/local
      // for GUI apps
      // https://github.com/typicode/husky/issues/49
      arr = arr.concat([
        'export PATH=$PATH:/usr/local/bin:/usr/local'
      ])
    }

    if (process.platform === 'darwin') {
      arr = arr.concat([
        'command_exists npm || load_nvm BREW_NVM_DIR /usr/local/opt/nvm',
        ''
      ])
    }

    arr = arr.concat([
      'command_exists npm || load_nvm NVM_DIR ' + home + '/.nvm',
      ''
    ])
  } else {
    // Add
    // Node standard installation path /c/Program Files/nodejs
    // for GUI apps
    // https://github.com/typicode/husky/issues/49
    arr = arr.concat([
      'export PATH="$PATH:/c/Program Files/nodejs"'
    ])
  }

  // Can't find npm message
  var npmNotFound = '> husky - Can\'t find npm in PATH. Skipping ' + cmd + ' script in package.json'

  arr = arr.concat([
    // Test if npm is in PATH
    'command_exists npm || {',
    '  echo >&2 "' + npmNotFound + '"',
    '  exit 0',
    '}',
    '',

    // Run script
    'echo',
    'echo "husky > npm run -s ' + cmd + '"',
    'echo',
    '',

    'export GIT_PARAMS="$*"',
    'npm run -s ' + cmd + ' || {',
    '  echo',
    '  echo "> husky - ' + hookName + ' hook failed (add --no-verify to bypass)"',
    '  echo "> husky - To debug, use \'npm run precommit\'"',
    '  exit 1',
    '}',
    ''
  ])

  return arr.join('\n')
}

function createHook (huskyDir, hooksDir, hookName, cmd) {
  var filename = path.join(hooksDir, hookName)

  // Assuming that this file is in node_modules/husky
  var packageDir = path.join(huskyDir, '..', '..')

  // Get project directory
  // When used in submodule, the project dir is the first .git that is found
  var projectDir = findParentDir.sync(huskyDir, '.git')

  // In order to support projects with package.json in a different directory
  // than .git, find relative path from project directory to package.json
  var relativePath = path.join('.', path.relative(projectDir, packageDir))

  var hookScript = getHookScript(hookName, relativePath, cmd)

  // Create hooks directory if needed
  if (!fs.existsSync(hooksDir)) fs.mkdirSync(hooksDir)

  if (!fs.existsSync(filename)) {
    write(filename, hookScript)
  } else {
    if (isHusky(filename)) {
      write(filename, hookScript)
    } else {
      console.log('skipping ' + hookName + ' hook (existing user hook)')
    }
  }
}

function removeHook (dir, name) {
  var filename = dir + '/' + name

  if (fs.existsSync(filename) && isHusky(filename)) {
    fs.unlinkSync(dir + '/' + name)
  }
}

function installFrom (huskyDir) {
  try {
    var isInSubNodeModule = (huskyDir.match(/node_modules/g) || []).length > 1
    if (isInSubNodeModule) {
      return console.log(
        'Trying to install from sub \'node_module\' directory,',
        'skipping Git hooks installation'
      )
    }

    var hooksDir = findHooksDir(huskyDir)

    if (hooksDir) {
      hooks.forEach(function (hookName) {
        var npmScriptName = hookName.replace(/-/g, '')
        createHook(huskyDir, hooksDir, hookName, npmScriptName)
      })
      console.log('done\n')
    } else {
      console.log('Can\'t find .git directory, skipping Git hooks installation')
    }
  } catch (e) {
    console.error(e)
  }
}

function uninstallFrom (huskyDir) {
  try {
    var hooksDir = findHooksDir(huskyDir)

    hooks.forEach(function (hookName) {
      removeHook(hooksDir, hookName)
    })
    console.log('done\n')
  } catch (e) {
    console.error(e)
  }
}

module.exports = {
  installFrom: installFrom,
  uninstallFrom: uninstallFrom
}
<|endoftext|>


<commit_before>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var useOracle    = false;
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
path.join(__dirname, '../oracle_driver.zip')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'yazz.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// copy the oracle files if they exist
//------------------------------------------------------------
if (fs.existsSync(path.join(__dirname, '../oracle_driver.zip'))) {
    useOracle = true;
}
if (useOracle) {
    if (!fs.existsSync(process.cwd() + '\\oracle_driver\\instantclient32')) {
      fs.createReadStream(path.join(__dirname, '../oracle_driver.zip')).pipe(unzip.Extract({ path: process.cwd() + '\\.' }));
      timeout = 3000;
      console.log('Creating oracle_driver');
    } else {
      console.log('oracle_driver already exists');
    };
}
var toeval = fs.readFileSync(path.join(__dirname, './oracle.js')).toString();
if (useOracle) {
    process.env['PATH'] = process.cwd() + '\\oracle_driver\\instantclient32' + ';' + process.env['PATH'];
}

//------------------------------------------------------------
// postgres
//------------------------------------------------------------
var pgeval = fs.readFileSync(path.join(__dirname, './postgres.js')).toString();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startYazz, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startYazz() {
  //
  // start the server
  //
  var Gun = require('gun');
  var gun = Gun({
    file: 'data.json',
    s3: {
      key: '', // AWS Access Key
      secret: '', // AWS Secret Token
      bucket: '' // The bucket you want to save into
    }
  });

  gun.wsp(app);

  console.log(typeOfSystem + ' started on port ' + port + ' with /gun');

  app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        if (useOracle) {
             eval(toeval);
        }
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      23
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = Object.keys(req);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

})

app.listen(port, hostaddress, function () {
    console.log('Example app listening on port ' + port + '!')
})

  //
  // open the app in a web browser
  //
  //console.log('Ran postgres too');

  var open = require('open');

  open('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  gun.get("connections").on().map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

  },true);

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

}
<commit_msg>see full http header<commit_after>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var useOracle    = false;
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
path.join(__dirname, '../oracle_driver.zip')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'yazz.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// copy the oracle files if they exist
//------------------------------------------------------------
if (fs.existsSync(path.join(__dirname, '../oracle_driver.zip'))) {
    useOracle = true;
}
if (useOracle) {
    if (!fs.existsSync(process.cwd() + '\\oracle_driver\\instantclient32')) {
      fs.createReadStream(path.join(__dirname, '../oracle_driver.zip')).pipe(unzip.Extract({ path: process.cwd() + '\\.' }));
      timeout = 3000;
      console.log('Creating oracle_driver');
    } else {
      console.log('oracle_driver already exists');
    };
}
var toeval = fs.readFileSync(path.join(__dirname, './oracle.js')).toString();
if (useOracle) {
    process.env['PATH'] = process.cwd() + '\\oracle_driver\\instantclient32' + ';' + process.env['PATH'];
}

//------------------------------------------------------------
// postgres
//------------------------------------------------------------
var pgeval = fs.readFileSync(path.join(__dirname, './postgres.js')).toString();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startYazz, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startYazz() {
  //
  // start the server
  //
  var Gun = require('gun');
  var gun = Gun({
    file: 'data.json',
    s3: {
      key: '', // AWS Access Key
      secret: '', // AWS Secret Token
      bucket: '' // The bucket you want to save into
    }
  });

  gun.wsp(app);

  console.log(typeOfSystem + ' started on port ' + port + ' with /gun');

  app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        if (useOracle) {
             eval(toeval);
        }
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      24
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = JSON.stringify(req);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

})

app.listen(port, hostaddress, function () {
    console.log('Example app listening on port ' + port + '!')
})

  //
  // open the app in a web browser
  //
  //console.log('Ran postgres too');

  var open = require('open');

  open('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  gun.get("connections").on().map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

  },true);

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

}
<|endoftext|>