<commit_before>var _ = require('underscore');
var juttle_test_utils = require('juttle/test/runtime/specs/juttle-test-utils');
var Juttle = require('juttle/lib/runtime').Juttle;
var AWSAdapter = require('../');
var check_juttle = juttle_test_utils.check_juttle;
var expect = require('chai').expect;
var read_config = require('juttle/lib/config/read-config');

describe('aws adapter', function() {

    before(function() {

        // Try to read from the config file first. If not present,
        // look in the environment variable JUTTLE_AWS_CONFIG. In
        // TravisCI, the config is provided via the environment to
        // avoid putting sensitive information like ids/auth tokens in
        // source files.

        var config = read_config();

        if (! _.has(config, "adapters")) {
            if (! _.has(process.env, "JUTTLE_AWS_CONFIG") ||
                process.env.JUTTLE_AWS_CONFIG === '') {
                throw new Error("To run this test, you must provide the adapter config via the environment as JUTTLE_AWS_CONFIG.");
            }
            var aws_config = JSON.parse(process.env.JUTTLE_AWS_CONFIG);
            config = {
                adapters: {
                    aws: aws_config
                }
            };
        }

        var adapter = AWSAdapter(config.adapters.aws, Juttle);

        Juttle.adapters.register(adapter.name, adapter);
    });

    describe(' properly returns an error for invalid arguments like', function() {

        it(' a -from in the past', function() {
            return check_juttle({
                program: 'read aws -from :1 day ago: -to :now: product="EC2" | view table'
            })
            .catch(function(err) {
                expect(err.code).to.equal('RT-ADAPTER-UNSUPPORTED-TIME-OPTION');
            });
        });

    });

    it(' can read basic info', function() {
        this.timeout(60000);
        return check_juttle({
            program: 'read aws -from :now: -to :now: product="EC2" | view table'
        })
        .then(function(result) {
            expect(result.errors).to.have.length(0);
            expect(result.warnings).to.have.length(0);
        });
    });
});

<commit_msg>Test all products, change config fetch.<commit_after>var _ = require('underscore');
var juttle_test_utils = require('juttle/test/runtime/specs/juttle-test-utils');
var Juttle = require('juttle/lib/runtime').Juttle;
var AWSAdapter = require('../');
var check_juttle = juttle_test_utils.check_juttle;
var expect = require('chai').expect;
var read_config = require('juttle/lib/config/read-config');

describe('aws adapter', function() {

    before(function() {

        // Try to read from the config file first. If not present,
        // look in the environment variable JUTTLE_AWS_CONFIG. In
        // TravisCI, the config is provided via the environment to
        // avoid putting sensitive information like ids/auth tokens in
        // source files.

        var config = read_config();
        var aws_config;

        if (_.has(config, "adapters") &&
            _.has(config.adapters, "aws")) {
            aws_config = config.adapters.aws;
        } else {

            if (! _.has(process.env, "JUTTLE_AWS_CONFIG") ||
                process.env.JUTTLE_AWS_CONFIG === '') {
                throw new Error("To run this test, you must provide the adapter config via the environment as JUTTLE_AWS_CONFIG.");
            }
            aws_config = JSON.parse(process.env.JUTTLE_AWS_CONFIG);
        }

        var adapter = AWSAdapter(config.adapters.aws, Juttle);

        Juttle.adapters.register(adapter.name, adapter);
    });

    describe(' properly returns an error for invalid arguments like', function() {

        it(' a -from in the past', function() {
            return check_juttle({
                program: 'read aws -from :1 day ago: -to :now: | view table'
            })
            .catch(function(err) {
                expect(err.code).to.equal('RT-ADAPTER-UNSUPPORTED-TIME-OPTION');
            });
        });

    });

    it(' can read basic info', function() {
        this.timeout(60000);
        return check_juttle({
            program: 'read aws -from :now: -to :now: | view table'
        })
        .then(function(result) {
            expect(result.errors).to.have.length(0);
            expect(result.warnings).to.have.length(0);
        });
    });
});

<|endoftext|>


<commit_before>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope) {
        var userAccount = Authentication.getAuthenticatedAccount();
        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.toggleBookmark = toggleBookmark;
        self.projects = [];
        self.previewedModule = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        self.currentPage = 1;
        self.page_data = {};
        self.page_numbers = [];
        self.switchPage = switchPage;
        self.getCollection = getCollection;
        self.has_pagination = has_pagination;
        TaskFeed.getProjects().then(
            function success(data) {
                self.projects = data[0];
                self.availableTasks = false;
                var k = 0;
                var page = [];
                //experiment code -- pagination
                for (var i = 0; i < self.projects.length; i++) {
                    page.push(self.projects[i]);
                    if (((i + 1) % 5) == 0 || self.projects.length - i == 1) {
                        k++;
                        self.page_data[k] = page;
                        page = [];
                        self.page_numbers.push(k);
                    }
                }
                for (var i = 0; i < self.projects.length; i++) {
                    for (var j = 0; j < self.projects[i].modules_filtered.length; j++) {
                        if (self.projects[i].modules_filtered[j].available_tasks != 0) {
                            self.availableTasks = true;
                            return;
                        }
                    }
                }

            },
            function error(errData) {
                self.error = errData[0].detail;
                $mdToast.showSimple('Could not get task with data.');
            }
        ).
            finally(function () {
                self.loading = false;
            });

        function toggleBookmark(project) {
            project.is_bookmarked = !project.is_bookmarked;
        }

        function showPreview(module) {
            self.previewedModule = module;
        }

        function openTask(module_id) {
            TaskWorker.attemptAllocateTask(module_id).then(
                function success(data) {
                    var task_id = data[0].task;
                    var taskWorkerId = data[0].id;
                    $location.path('/task/' + task_id + '/' + taskWorkerId);
                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(module) {
            if (module.comments && module.is_comment_expanded) {
                module.is_comment_expanded = false;
            }
            else if (module.comments && !module.is_comment_expanded) {
                module.is_comment_expanded = true;
            }
            else {
                Project.getModuleComments(module.id).then(
                    function success(data) {
                        angular.extend(module, {'comments': data[0].comments});
                        module.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(module) {
            TaskFeed.saveComment(module.id, self.comment.body).then(
                function success(data) {
                    if (module.comments == undefined) {
                        angular.extend(module, {'comments': []});
                    }
                    module.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }

        function switchPage(index) {
            var random = Math.floor(Math.random() * (5)) + 2;
            $mdToast.showSimple('Loading...');
            setTimeout(function () {
                self.currentPage = index;
                $scope.$apply();
            }, random*1000);
        }

        function getCollection(){
            if(has_pagination()){
                return self.page_data[self.currentPage];
            }
            return self.projects;
        }

        function has_pagination(){
            var fields = $rootScope.account.worker_experiment_fields;
            return (fields.pool===2 && fields.sorting_type===1);
        }
    }

})
();<commit_msg>pool 2 only<commit_after>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope) {
        var userAccount = Authentication.getAuthenticatedAccount();
        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.toggleBookmark = toggleBookmark;
        self.projects = [];
        self.previewedModule = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        self.currentPage = 1;
        self.page_data = {};
        self.page_numbers = [];
        self.switchPage = switchPage;
        self.getCollection = getCollection;
        self.has_pagination = has_pagination;
        TaskFeed.getProjects().then(
            function success(data) {
                self.projects = data[0];
                self.availableTasks = false;
                var k = 0;
                var page = [];
                //experiment code -- pagination
                for (var i = 0; i < self.projects.length; i++) {
                    page.push(self.projects[i]);
                    if (((i + 1) % 5) == 0 || self.projects.length - i == 1) {
                        k++;
                        self.page_data[k] = page;
                        page = [];
                        self.page_numbers.push(k);
                    }
                }
                for (var i = 0; i < self.projects.length; i++) {
                    for (var j = 0; j < self.projects[i].modules_filtered.length; j++) {
                        if (self.projects[i].modules_filtered[j].available_tasks != 0) {
                            self.availableTasks = true;
                            return;
                        }
                    }
                }

            },
            function error(errData) {
                self.error = errData[0].detail;
                $mdToast.showSimple('Could not get task with data.');
            }
        ).
            finally(function () {
                self.loading = false;
            });

        function toggleBookmark(project) {
            project.is_bookmarked = !project.is_bookmarked;
        }

        function showPreview(module) {
            self.previewedModule = module;
        }

        function openTask(module_id) {
            TaskWorker.attemptAllocateTask(module_id).then(
                function success(data) {
                    var task_id = data[0].task;
                    var taskWorkerId = data[0].id;
                    $location.path('/task/' + task_id + '/' + taskWorkerId);
                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(module) {
            if (module.comments && module.is_comment_expanded) {
                module.is_comment_expanded = false;
            }
            else if (module.comments && !module.is_comment_expanded) {
                module.is_comment_expanded = true;
            }
            else {
                Project.getModuleComments(module.id).then(
                    function success(data) {
                        angular.extend(module, {'comments': data[0].comments});
                        module.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(module) {
            TaskFeed.saveComment(module.id, self.comment.body).then(
                function success(data) {
                    if (module.comments == undefined) {
                        angular.extend(module, {'comments': []});
                    }
                    module.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }

        function switchPage(index) {
            var random = Math.floor(Math.random() * (5)) + 2;
            $mdToast.showSimple('Loading...');
            setTimeout(function () {
                self.currentPage = index;
                $scope.$apply();
            }, random*1000);
        }

        function getCollection(){
            if(has_pagination()){
                return self.page_data[self.currentPage];
            }
            return self.projects;
        }

        function has_pagination(){
            var fields = $rootScope.account.worker_experiment_fields;
            return (fields.pool===2);
        }
    }

})
();<|endoftext|>


<commit_before>'use strict';

var debug               = require('debug-ext')('setup')
  , ensureType          = require('dbjs/valid-dbjs-type')
  , ensureStringifiable = require('es5-ext/object/validate-stringifiable-value')
  , resolve             = require('path').resolve
  , writeFile           = require('fs2/write-file')
  , serialize           = require('es5-ext/object/serialize')
  , savePath            = 'apps-common/client/legacy/generated';
/**
 * Generates map for controls-map.js legacy (responsible for parent-child select interaction).
 * @param projectRoot {string}
 * @param config {object}
 * config.child {constructor}         - Class of the child
 * config.parent {constructor}        - Class of the parent
 * config.htmlClass {string}          - The class for html control (should be uniq in DOM)
 * config.linkingProperyName {string} - The name of child's property which points to parent
 *                                      i.e 'category'
 * config.fileNamePrefix {string}     - The prefix of the file in which the map will be stored
 * @returns promise
 */

module.exports = function (projectRoot, config) {
	var result = {
		map: {}
	};

	debug('generate-legacy-' + ensureStringifiable(config.fileNamePrefix) + '-data');
	result.htmlClass       = ensureStringifiable(config.htmlClass);
	result.parentTypeLabel = ensureType(config.parent).label;
	ensureStringifiable(config.linkingPropertyName);

	ensureType(config.child).instances.forEach(function (child) {
		var parentId = child[config.linkingPropertyName].__id__;
		if (!result.map[parentId]) {
			result.map[parentId] = {
				label: child[config.linkingPropertyName].label,
				items: []
			};
		}
		result.map[parentId].items.push(child.__id__);
	});

	return writeFile(resolve(projectRoot, savePath, config.fileNamePrefix + '-map.js'),
				'\'use strict\';\n\nmodule.exports = ' + serialize(result) + ';\n',
			{ intermediate: true });
};
<commit_msg>#988 additional check for param<commit_after>'use strict';

var debug        = require('debug-ext')('setup')
  , ensureType   = require('dbjs/valid-dbjs-type')
  , ensureString = require('es5-ext/object/validate-stringifiable-value')
  , resolve      = require('path').resolve
  , writeFile    = require('fs2/write-file')
  , serialize    = require('es5-ext/object/serialize')
  , savePath     = 'apps-common/client/legacy/generated';
/**
 * Generates map for controls-map.js legacy (responsible for parent-child select interaction).
 * @param projectRoot {string}
 * @param config {object}
 * config.child {constructor}         - Class of the child
 * config.parent {constructor}        - Class of the parent
 * config.htmlClass {string}          - The class for html control (should be uniq in DOM)
 * config.linkingProperyName {string} - The name of child's property which points to parent
 *                                      i.e 'category'
 * config.fileNamePrefix {string}     - The prefix of the file in which the map will be stored
 * @returns promise
 */

module.exports = function (projectRoot, config) {
	var result = {
		map: {}
	};

	ensureString(projectRoot);
	debug('generate-legacy-' + ensureString(config.fileNamePrefix) + '-data');
	result.htmlClass       = ensureString(config.htmlClass);
	result.parentTypeLabel = ensureType(config.parent).label;
	ensureString(config.linkingPropertyName);

	ensureType(config.child).instances.forEach(function (child) {
		var parentId = child[config.linkingPropertyName].__id__;
		if (!result.map[parentId]) {
			result.map[parentId] = {
				label: child[config.linkingPropertyName].label,
				items: []
			};
		}
		result.map[parentId].items.push(child.__id__);
	});

	return writeFile(resolve(projectRoot, savePath, config.fileNamePrefix + '-map.js'),
				'\'use strict\';\n\nmodule.exports = ' + serialize(result) + ';\n',
			{ intermediate: true });
};
<|endoftext|>


<commit_before>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');
var bodyParser = require('body-parser');

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys([]));
app.use('/mbaas', mbaasExpress.mbaas);

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

app.get('/list/:googleId', function(req,res) {
  mbaasApi.db({
          "act": "list",
          "type": 'account',
          "eq":{"sub":req.params.googleId}
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.get('/list', function(req,res) {
  mbaasApi.db({
          "act": "list",
          "type": 'accountSession'
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.get('/drop', function(req,res) {
  mbaasApi.db({
          "act": "deleteall",
          "type": 'account'
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.use('/hello', require('./lib/hello.js')());
app.use(bodyParser());

app.use('/auth', require('./lib/auth.js')());

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001;
var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
app.listen(port, host, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<commit_msg>update file /application.js<commit_after>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');
var bodyParser = require('body-parser');

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys([]));
app.use('/mbaas', mbaasExpress.mbaas);

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

app.get('/list/:session', function(req,res) {
  mbaasApi.db({
          "act": "list",
          "type": 'account',
          "eq":{"sub":req.params.googleId}
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.get('/list', function(req,res) {
  mbaasApi.db({
          "act": "list",
          "type": 'accountSession'
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.get('/drop', function(req,res) {
  mbaasApi.db({
          "act": "deleteall",
          "type": 'account'
  }, function(err, noterr) {
    if (err) {
     res.end('Boo! ' + err);
    } else {
      res.end('OOB! ' + JSON.stringify(noterr));
    }
  });
  });

app.use('/hello', require('./lib/hello.js')());
app.use(bodyParser());

app.use('/auth', require('./lib/auth.js')());

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001;
var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
app.listen(port, host, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<|endoftext|>


<commit_before>'use strict'

if(process.env.NEW_RELIC_LICENSE_KEY) { require('newrelic') }

const _ = require('lodash')
const async = require('async')
const bparser = require('body-parser')
const cparser = require('cookie-parser')
const express = require('express')
const jwt = require('jsonwebtoken')
const mongo = require('mongodb')
const passport = require('passport')
const raven = require('raven')

// global variables (and list of all used environment variables)
const APP_VERSION = process.env.VERSION || process.env.HEROKU_SLUG_COMMIT.substr(0, 7) || require('./package').version
const APP_STARTED = new Date().toISOString()

// MONGODB
// CUSTOMERS
// JWT_SECRET

// GOOGLE_ID
// GOOGLE_SECRET

// FACEBOOK_ID
// FACEBOOK_SECRET

// TWITTER_KEY
// TWITTER_SECRET

// LIVE_ID
// LIVE_SECRET

// TAAT_ENTRYPOINT
// TAAT_ISSUER
// TAAT_CERT
// TAAT_PRIVATECERT

// passport (de)serialize
passport.serializeUser((user, done) => {
    done(null, user)
})

passport.deserializeUser((user, done) => {
    done(null, user)
})

// initialize getsentry.com client
if(process.env.SENTRY_DSN) {
    raven.config(process.env.SENTRY_DSN, {
        release: process.env.VERSION || process.env.HEROKU_SLUG_COMMIT || require('./package').version,
        dataCallback: (data) => {
            delete data.request.env
            return data
        }
    }).install()
}

// start express app
var app = express()

// set locals

// returns db connection (creates if not set)
app.locals.dbs = {}
app.locals.db = (customer, callback) => {
    if(_.has(app, ['locals', 'dbs', customer])) {
        console.log('use existing connection for ' + customer)
        return callback(null, app.locals.dbs[customer])
    } else {
        console.log('Start connecting to ' + customer)
        var entuDb
        async.waterfall([
            (callback) => {
                mongo.MongoClient.connect(process.env.MONGODB, { ssl: true, sslValidate: true }, callback)
            },
            (connection, callback) => {
                entuDb = connection
                entuDb.collection('entity').findOne({ 'database_name.string': customer, 'mongodb.string': { '$exists': true }, deleted_at: { '$exists': false }, deleted_by: { '$exists': false } }, { _id: false, 'mongodb.string': true }, callback)
            },
            (url, callback) => {
                // entuDb.close()
                if (!_.has(url, 'mongodb.0.string')) { return callback('No MongoDb url')}

                mongo.MongoClient.connect(_.get(url, 'mongodb.0.string'), { ssl: true, sslValidate: true }, callback)
            },
            (connection, callback) => {
                console.log('Connected to ' + customer)

                connection.on('close', () => {
                    delete app.locals.dbs[customer]
                    console.log('Disconnected from ' + customer)
                })

                app.locals.dbs[customer] = connection

                entuDb.close(callback)
            },
        ], (err) => {
            if(err) { return callback(err) }

            console.log('Connected to ' + customer)

            return callback(null, app.locals.dbs[customer])
        })
    }
}

// Hide Powered By
app.disable('x-powered-by')

// get correct client IP behind nginx
app.set('trust proxy', true)

// logs to getsentry.com - start
if(process.env.SENTRY_DSN) {
    app.use(raven.requestHandler())
}

// Initialize Passport
app.use(passport.initialize())

// parse Cookies
app.use(cparser())

// parse POST requests
app.use(bparser.json())
app.use(bparser.urlencoded({extended: true}))

// save request info to request collection
app.use((req, res, next) => {
    req.startDt = Date.now()

    res.on('finish', () => {
        var request = {
            date: new Date(),
            ip: req.ip,
            ms: Date.now() - req.startDt,
            status: res.statusCode,
            method: req.method,
            host: req.hostname,
            browser: req.headers['user-agent'],
        }
        if(req.path) { request.path = req.path }
        if(!_.isEmpty(req.query)) { request.query = req.query }
        if(!_.isEmpty(req.body)) { request.body = req.body }
        if(req.browser) { request.browser = req.headers['user-agent'] }

        async.waterfall([
            (callback) => {
                req.app.locals.db('entu', callback)
            },
            (connection, callback) => {
                connection.collection('request').insertOne(request, callback)
            },
        ], (err) => {
            if(err) {
                console.error('Can\'t save request: ' + err.toString())
            }
        })
    })

    next(null)
})

//custom JSON output
app.use((req, res, next) => {
    res.respond = (body, errorCode) => {
        var message = {
            release: APP_VERSION,
            startDt: APP_STARTED,
            ms: Date.now() - req.startDt,
            auth: !!req.user
        }

        if (errorCode) {
            message.error = {
                code: errorCode,
                message: body
            }
            res.status(errorCode).json(message)
        } else {
            if (body.constructor === Array) {
                message.count = body.length
            }
            message.result = body
            res.json(message)
        }
    }

    next(null)
})

// check JWT
app.use((req, res, next) => {
    var parts = _.get(req, 'headers.authorization', '').split(' ')
    let jwtConf = {
        issuer: req.hostname
    }

    if (req.query.customer) {
        req.customer = req.query.customer
        jwtConf.audience = req.query.customer
    }

    if(parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') { return next(null) }

    jwt.verify(parts[1], process.env.JWT_SECRET, jwtConf, (err, decoded) => {
        if(err) { return next([401, err]) }

        _.set(req, 'user', decoded.sub)
        _.set(req, 'customer', decoded.aud)

        next(null)
    })
})

// redirect HTTP to HTTPS
app.use((req, res, next) => {
    if (req.hostname !== 'localhost' && req.protocol.toLowerCase() !== 'https') { next([418, 'I\'m a teapot']) } else { next() }
})

// routes mapping
app.use('/', require('./routes/index'))
app.use('/auth', require('./routes/auth/index'))
app.use('/user', require('./routes/user'))
app.use('/entity', require('./routes/entity'))

// provider mapping (only if configured)
app.use('/auth/id-card', require('./routes/auth/id-card'))

if(process.env.GOOGLE_ID && process.env.GOOGLE_SECRET) { app.use('/auth/google', require('./routes/auth/google')) }
if(process.env.FACEBOOK_ID && process.env.FACEBOOK_SECRET) { app.use('/auth/facebook', require('./routes/auth/facebook')) }
if(process.env.TWITTER_KEY && process.env.TWITTER_SECRET) { app.use('/auth/twitter', require('./routes/auth/twitter')) }
if(process.env.LIVE_ID && process.env.LIVE_SECRET) { app.use('/auth/live', require('./routes/auth/live')) }
if(process.env.TAAT_ENTRYPOINT && process.env.TAAT_CERT && process.env.TAAT_PRIVATECERT) { app.use('/auth/taat', require('./routes/auth/taat')) }

// logs to getsentry.com - error
if(process.env.SENTRY_DSN) {
    app.use(raven.errorHandler())
}

// show 404
app.use((req, res, next) => {
    next([404, 'Not found'])
})

// show error
app.use((err, req, res, next) => {
    if (err.constructor === Array) {
        res.respond(err[1], err[0])
    } else {
        res.respond(err.toString(), 500)
    }
})

// start server
app.listen(process.env.PORT, () => {
    console.log(new Date().toString() + ' started listening port ' + process.env.PORT)
})
<commit_msg>More logging for debug<commit_after>'use strict'

if(process.env.NEW_RELIC_LICENSE_KEY) { require('newrelic') }

const _ = require('lodash')
const async = require('async')
const bparser = require('body-parser')
const cparser = require('cookie-parser')
const express = require('express')
const jwt = require('jsonwebtoken')
const mongo = require('mongodb')
const passport = require('passport')
const raven = require('raven')

// global variables (and list of all used environment variables)
const APP_VERSION = process.env.VERSION || process.env.HEROKU_SLUG_COMMIT.substr(0, 7) || require('./package').version
const APP_STARTED = new Date().toISOString()

// MONGODB
// CUSTOMERS
// JWT_SECRET

// GOOGLE_ID
// GOOGLE_SECRET

// FACEBOOK_ID
// FACEBOOK_SECRET

// TWITTER_KEY
// TWITTER_SECRET

// LIVE_ID
// LIVE_SECRET

// TAAT_ENTRYPOINT
// TAAT_ISSUER
// TAAT_CERT
// TAAT_PRIVATECERT

// passport (de)serialize
passport.serializeUser((user, done) => {
    done(null, user)
})

passport.deserializeUser((user, done) => {
    done(null, user)
})

// initialize getsentry.com client
if(process.env.SENTRY_DSN) {
    raven.config(process.env.SENTRY_DSN, {
        release: process.env.VERSION || process.env.HEROKU_SLUG_COMMIT || require('./package').version,
        dataCallback: (data) => {
            delete data.request.env
            return data
        }
    }).install()
}

// start express app
var app = express()

// set locals

// returns db connection (creates if not set)
app.locals.dbs = {}
app.locals.db = (customer, callback) => {
    if(_.has(app, ['locals', 'dbs', customer])) {
        console.log('use existing connection for ' + customer)
        return callback(null, app.locals.dbs[customer])
    } else {
        var entuDb
        async.waterfall([
            (callback) => {
                console.log('a ' + customer)
                mongo.MongoClient.connect(process.env.MONGODB, { ssl: true, sslValidate: true }, callback)
            },
            (connection, callback) => {
                console.log('b ' + customer)
                entuDb = connection
                entuDb.collection('entity').findOne({ 'database_name.string': customer, 'mongodb.string': { '$exists': true }, deleted_at: { '$exists': false }, deleted_by: { '$exists': false } }, { _id: false, 'mongodb.string': true }, callback)
            },
            (url, callback) => {
                console.log('c ' + customer)
                if (!_.has(url, 'mongodb.0.string')) { return callback('No MongoDb url')}

                mongo.MongoClient.connect(_.get(url, 'mongodb.0.string'), { ssl: true, sslValidate: true }, callback)
            },
            (connection, callback) => {
                console.log('Connected to ' + customer)

                connection.on('close', () => {
                    delete app.locals.dbs[customer]
                    console.log('Disconnected from ' + customer)
                })

                app.locals.dbs[customer] = connection

                entuDb.close(callback)
            },
        ], (err) => {
            if(err) { return callback(err) }

            console.log('Connected to ' + customer)

            return callback(null, app.locals.dbs[customer])
        })
    }
}

// Hide Powered By
app.disable('x-powered-by')

// get correct client IP behind nginx
app.set('trust proxy', true)

// logs to getsentry.com - start
if(process.env.SENTRY_DSN) {
    app.use(raven.requestHandler())
}

// Initialize Passport
app.use(passport.initialize())

// parse Cookies
app.use(cparser())

// parse POST requests
app.use(bparser.json())
app.use(bparser.urlencoded({extended: true}))

// save request info to request collection
app.use((req, res, next) => {
    req.startDt = Date.now()

    res.on('finish', () => {
        var request = {
            date: new Date(),
            ip: req.ip,
            ms: Date.now() - req.startDt,
            status: res.statusCode,
            method: req.method,
            host: req.hostname,
            browser: req.headers['user-agent'],
        }
        if(req.path) { request.path = req.path }
        if(!_.isEmpty(req.query)) { request.query = req.query }
        if(!_.isEmpty(req.body)) { request.body = req.body }
        if(req.browser) { request.browser = req.headers['user-agent'] }

        async.waterfall([
            (callback) => {
                req.app.locals.db('entu', callback)
            },
            (connection, callback) => {
                connection.collection('request').insertOne(request, callback)
            },
        ], (err) => {
            if(err) {
                console.error('Can\'t save request: ' + err.toString())
            }
        })
    })

    next(null)
})

//custom JSON output
app.use((req, res, next) => {
    res.respond = (body, errorCode) => {
        var message = {
            release: APP_VERSION,
            startDt: APP_STARTED,
            ms: Date.now() - req.startDt,
            auth: !!req.user
        }

        if (errorCode) {
            message.error = {
                code: errorCode,
                message: body
            }
            res.status(errorCode).json(message)
        } else {
            if (body.constructor === Array) {
                message.count = body.length
            }
            message.result = body
            res.json(message)
        }
    }

    next(null)
})

// check JWT
app.use((req, res, next) => {
    var parts = _.get(req, 'headers.authorization', '').split(' ')
    let jwtConf = {
        issuer: req.hostname
    }

    if (req.query.customer) {
        req.customer = req.query.customer
        jwtConf.audience = req.query.customer
    }

    if(parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') { return next(null) }

    jwt.verify(parts[1], process.env.JWT_SECRET, jwtConf, (err, decoded) => {
        if(err) { return next([401, err]) }

        _.set(req, 'user', decoded.sub)
        _.set(req, 'customer', decoded.aud)

        next(null)
    })
})

// redirect HTTP to HTTPS
app.use((req, res, next) => {
    if (req.hostname !== 'localhost' && req.protocol.toLowerCase() !== 'https') { next([418, 'I\'m a teapot']) } else { next() }
})

// routes mapping
app.use('/', require('./routes/index'))
app.use('/auth', require('./routes/auth/index'))
app.use('/user', require('./routes/user'))
app.use('/entity', require('./routes/entity'))

// provider mapping (only if configured)
app.use('/auth/id-card', require('./routes/auth/id-card'))

if(process.env.GOOGLE_ID && process.env.GOOGLE_SECRET) { app.use('/auth/google', require('./routes/auth/google')) }
if(process.env.FACEBOOK_ID && process.env.FACEBOOK_SECRET) { app.use('/auth/facebook', require('./routes/auth/facebook')) }
if(process.env.TWITTER_KEY && process.env.TWITTER_SECRET) { app.use('/auth/twitter', require('./routes/auth/twitter')) }
if(process.env.LIVE_ID && process.env.LIVE_SECRET) { app.use('/auth/live', require('./routes/auth/live')) }
if(process.env.TAAT_ENTRYPOINT && process.env.TAAT_CERT && process.env.TAAT_PRIVATECERT) { app.use('/auth/taat', require('./routes/auth/taat')) }

// logs to getsentry.com - error
if(process.env.SENTRY_DSN) {
    app.use(raven.errorHandler())
}

// show 404
app.use((req, res, next) => {
    next([404, 'Not found'])
})

// show error
app.use((err, req, res, next) => {
    if (err.constructor === Array) {
        res.respond(err[1], err[0])
    } else {
        res.respond(err.toString(), 500)
    }
})

// start server
app.listen(process.env.PORT, () => {
    console.log(new Date().toString() + ' started listening port ' + process.env.PORT)
})
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Alibaba Group Holding Limited.
 * All rights reserved.
 *
 * Copyright (c) 2015, Facebook, Inc.  All rights reserved.
 *
 * @providesModule ReactScrollView
 */
'use strict';

import React, { PropTypes, Component} from 'react';
import ReactDOM from 'react-dom';
import ScrollResponder from 'ReactScrollResponder';
import StyleSheet from 'ReactStyleSheet';
import View from 'ReactView';
import throttle from 'domkit/throttle';
import mixin from 'react-mixin';
import autobind from 'autobind-decorator';

const SCROLLVIEW = 'ScrollView';
const INNERVIEW = 'InnerScrollView';
const CONTENT_EXT_STYLE = ['padding', 'paddingTop', 'paddingBottom', 'paddingLeft', 'paddingRight'];

/**
 * Component that wraps platform ScrollView while providing
 * integration with touch locking "responder" system.
 *
 * Keep in mind that ScrollViews must have a bounded height in order to work,
 * since they contain unbounded-height children into a bounded container (via
 * a scroll interaction). In order to bound the height of a ScrollView, either
 * set the height of the view directly (discouraged) or make sure all parent
 * views have bounded height. Forgetting to transfer `{flex: 1}` down the
 * view stack can lead to errors here, which the element inspector makes
 * easy to debug.
 *
 * Doesn't yet support other contained responders from blocking this scroll
 * view from becoming the responder.
 */
class ScrollView extends Component {

  state = this.scrollResponderMixinGetInitialState();

  /**
   * Returns a reference to the underlying scroll responder, which supports
   * operations like `scrollTo`. All ScrollView-like components should
   * implement this method so that they can be composed while providing access
   * to the underlying scroll responder's methods.
   */
  getScrollResponder() {
    return this;
  }

  getInnerViewNode() {
    return this.refs[INNERVIEW];
  }

  scrollTo(opts) {
    // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now
    // this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0);
    if (typeof opts === 'number') {
      opts = { y: opts, x: arguments[1] };
    }

    this.scrollWithoutAnimationTo(opts.y, opts.x);
  }

  scrollWithoutAnimationTo(destY?: number, destX?: number) {
    // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now
    // this.getScrollResponder().scrollResponderScrollWithouthAnimationTo(
    //   destX || 0,
    //   destY || 0,
    // );

    this._scrollViewDom = ReactDOM.findDOMNode(this.refs[SCROLLVIEW]);
    this._scrollViewDom.scrollTop = destY || 0;
    this._scrollViewDom.scrollLeft = destX || 0;
  }

  handleScroll(e: Event) {
    // if (__DEV__) {
    //   if (this.props.onScroll && !this.props.scrollEventThrottle) {
    //     console.log(
    //       'You specified `onScroll` on a <ScrollView> but not ' +
    //       '`scrollEventThrottle`. You will only receive one event. ' +
    //       'Using `16` you get all the events but be aware that it may ' +
    //       'cause frame drops, use a bigger number if you don\'t need as ' +
    //       'much precision.'
    //     );
    //   }
    // }
    // if (Platform.OS === 'android') {
    //   if (this.props.keyboardDismissMode === 'on-drag') {
    //     dismissKeyboard();
    //   }
    // }

    if (!this._scrollViewDom)
      this._scrollViewDom = ReactDOM.findDOMNode(this.refs[SCROLLVIEW]);

    e.nativeEvent = e.nativeEvent || {};
    e.nativeEvent.contentOffset = {x:this._scrollViewDom.scrollLeft, y:this._scrollViewDom.scrollTop};

    this.props.onScroll && this.props.onScroll(e);
  }

  render() {
    let {
      style,
      ...otherProps
    } = this.props;

    let contentContainerExtStyle = {};

    if (style) {
      for (let i = 0; i < CONTENT_EXT_STYLE.length; i++) {
        if (typeof style[CONTENT_EXT_STYLE[i]] === 'number') {
          contentContainerExtStyle[CONTENT_EXT_STYLE[i]] = style[CONTENT_EXT_STYLE[i]];
        }
      }
    }

    let contentContainerStyle = [
      styles.contentContainer,
      this.props.horizontal && styles.contentContainerHorizontal,
      this.props.contentContainerStyle,
      contentContainerExtStyle,
    ];
    // if (__DEV__ && this.props.style) {
    //   let style = flattenStyle(this.props.style);
    //   let childLayoutProps = ['alignItems', 'justifyContent']
    //     .filter((prop) => style && style[prop] !== undefined);
    //   invariant(
    //     childLayoutProps.length === 0,
    //     'ScrollView child layout (' + JSON.stringify(childLayoutProps) +
    //       ') must by applied through the contentContainerStyle prop.'
    //   );
    // }

    let contentContainer =
      <View
        ref={INNERVIEW}
        style={contentContainerStyle}
        removeClippedSubviews={this.props.removeClippedSubviews}
        collapsable={false}>
        {this.props.children}
      </View>;

    let alwaysBounceHorizontal =
      this.props.alwaysBounceHorizontal !== undefined ?
        this.props.alwaysBounceHorizontal :
        this.props.horizontal;

    let alwaysBounceVertical =
      this.props.alwaysBounceVertical !== undefined ?
        this.props.alwaysBounceVertical :
        !this.props.horizontal;

    let handleScroll = () => {};
    if (this.props.scrollEventThrottle && this.props.onScroll) {
      handleScroll = throttle(this.handleScroll, this.props.scrollEventThrottle ? 1000 / this.props.scrollEventThrottle : 1000);
    }

    let props = {
      ...otherProps,
      alwaysBounceHorizontal,
      alwaysBounceVertical,
      style: ([styles.base, this.props.style]: ?Array<any>),
      onTouchStart: this.scrollResponderHandleTouchStart,
      onTouchMove: this.scrollResponderHandleTouchMove,
      onTouchEnd: this.scrollResponderHandleTouchEnd,
      onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
      onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
      onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
      onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
      onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
      onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
      // onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
      // onScroll: handleScroll,
      onScrollShouldSetResponder: handleScroll,
      // replace onScroll in the props
      onScroll: () => {},
      onResponderGrant: this.scrollResponderHandleResponderGrant,
      onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
      onResponderTerminate: this.scrollResponderHandleTerminate,
      onResponderRelease: this.scrollResponderHandleResponderRelease,
      onResponderReject: this.scrollResponderHandleResponderReject,
    };

    return (
      <View {...props} ref={SCROLLVIEW}>
        {contentContainer}
      </View>
    );
  }
};

let styles = StyleSheet.create({
  base: {
    overflow: 'scroll',
    WebkitOverflowScrolling: 'touch',
    flex: 1,
  },
  contentContainer: {
    position: 'absolute',
    minWidth: '100%',
  },
  contentContainerHorizontal: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
  },
});

mixin.onClass(ScrollView, ScrollResponder.Mixin);
autobind(ScrollView);

ScrollView.isReactNativeComponent = true;

export default ScrollView;
<commit_msg>try to fix #220<commit_after>/**
 * Copyright (c) 2015-present, Alibaba Group Holding Limited.
 * All rights reserved.
 *
 * Copyright (c) 2015, Facebook, Inc.  All rights reserved.
 *
 * @providesModule ReactScrollView
 */
'use strict';

import React, { PropTypes, Component} from 'react';
import ReactDOM from 'react-dom';
import ScrollResponder from 'ReactScrollResponder';
import StyleSheet from 'ReactStyleSheet';
import View from 'ReactView';
import throttle from 'domkit/throttle';
import mixin from 'react-mixin';
import autobind from 'autobind-decorator';

const SCROLLVIEW = 'ScrollView';
const INNERVIEW = 'InnerScrollView';
const CONTENT_EXT_STYLE = ['padding', 'paddingTop', 'paddingBottom', 'paddingLeft', 'paddingRight'];

/**
 * Component that wraps platform ScrollView while providing
 * integration with touch locking "responder" system.
 *
 * Keep in mind that ScrollViews must have a bounded height in order to work,
 * since they contain unbounded-height children into a bounded container (via
 * a scroll interaction). In order to bound the height of a ScrollView, either
 * set the height of the view directly (discouraged) or make sure all parent
 * views have bounded height. Forgetting to transfer `{flex: 1}` down the
 * view stack can lead to errors here, which the element inspector makes
 * easy to debug.
 *
 * Doesn't yet support other contained responders from blocking this scroll
 * view from becoming the responder.
 */
class ScrollView extends Component {

  state = this.scrollResponderMixinGetInitialState();

  /**
   * Returns a reference to the underlying scroll responder, which supports
   * operations like `scrollTo`. All ScrollView-like components should
   * implement this method so that they can be composed while providing access
   * to the underlying scroll responder's methods.
   */
  getScrollResponder() {
    return this;
  }

  getInnerViewNode() {
    return this.refs[INNERVIEW];
  }

  scrollTo(opts) {
    // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now
    // this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0);
    if (typeof opts === 'number') {
      opts = { y: opts, x: arguments[1] };
    }

    this.scrollWithoutAnimationTo(opts.y, opts.x);
  }

  scrollWithoutAnimationTo(destY?: number, destX?: number) {
    // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now
    // this.getScrollResponder().scrollResponderScrollWithouthAnimationTo(
    //   destX || 0,
    //   destY || 0,
    // );

    this._scrollViewDom = ReactDOM.findDOMNode(this.refs[SCROLLVIEW]);
    this._scrollViewDom.scrollTop = destY || 0;
    this._scrollViewDom.scrollLeft = destX || 0;
  }

  handleScroll(e: Event) {
    // if (__DEV__) {
    //   if (this.props.onScroll && !this.props.scrollEventThrottle) {
    //     console.log(
    //       'You specified `onScroll` on a <ScrollView> but not ' +
    //       '`scrollEventThrottle`. You will only receive one event. ' +
    //       'Using `16` you get all the events but be aware that it may ' +
    //       'cause frame drops, use a bigger number if you don\'t need as ' +
    //       'much precision.'
    //     );
    //   }
    // }
    // if (Platform.OS === 'android') {
    //   if (this.props.keyboardDismissMode === 'on-drag') {
    //     dismissKeyboard();
    //   }
    // }

    if (!this._scrollViewDom)
      this._scrollViewDom = ReactDOM.findDOMNode(this.refs[SCROLLVIEW]);

    e.nativeEvent = e.nativeEvent || {};
    e.nativeEvent.contentOffset = {x:this._scrollViewDom.scrollLeft, y:this._scrollViewDom.scrollTop};

    this.props.onScroll && this.props.onScroll(e);
  }

  render() {
    let {
      style,
      ...otherProps
    } = this.props;

    let contentContainerExtStyle = {};

    if (style) {
      for (let i = 0; i < CONTENT_EXT_STYLE.length; i++) {
        if (typeof style[CONTENT_EXT_STYLE[i]] === 'number') {
          contentContainerExtStyle[CONTENT_EXT_STYLE[i]] = style[CONTENT_EXT_STYLE[i]];
        }
      }
    }

    let contentContainerStyle = [
      styles.contentContainer,
      this.props.horizontal && styles.contentContainerHorizontal,
      this.props.contentContainerStyle,
      contentContainerExtStyle,
    ];
    // if (__DEV__ && this.props.style) {
    //   let style = flattenStyle(this.props.style);
    //   let childLayoutProps = ['alignItems', 'justifyContent']
    //     .filter((prop) => style && style[prop] !== undefined);
    //   invariant(
    //     childLayoutProps.length === 0,
    //     'ScrollView child layout (' + JSON.stringify(childLayoutProps) +
    //       ') must by applied through the contentContainerStyle prop.'
    //   );
    // }

    let contentContainer =
      <View
        ref={INNERVIEW}
        style={contentContainerStyle}
        removeClippedSubviews={this.props.removeClippedSubviews}
        collapsable={false}>
        {this.props.children}
      </View>;

    let alwaysBounceHorizontal =
      this.props.alwaysBounceHorizontal !== undefined ?
        this.props.alwaysBounceHorizontal :
        this.props.horizontal;

    let alwaysBounceVertical =
      this.props.alwaysBounceVertical !== undefined ?
        this.props.alwaysBounceVertical :
        !this.props.horizontal;

    let handleScroll = () => {};
    if (this.props.scrollEventThrottle && this.props.onScroll) {
      handleScroll = throttle(this.handleScroll, this.props.scrollEventThrottle ? 1000 / this.props.scrollEventThrottle : 1000);
    }

    let props = {
      ...otherProps,
      alwaysBounceHorizontal,
      alwaysBounceVertical,
      style: ([
        styles.base,
        this.props.horizontal ? styles.horizontal : null,
        this.props.style,
      ]: ?Array<any>),
      onTouchStart: this.scrollResponderHandleTouchStart,
      onTouchMove: this.scrollResponderHandleTouchMove,
      onTouchEnd: this.scrollResponderHandleTouchEnd,
      onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
      onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
      onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
      onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
      onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
      onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
      // onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
      // onScroll: handleScroll,
      onScrollShouldSetResponder: handleScroll,
      // replace onScroll in the props
      onScroll: () => {},
      onResponderGrant: this.scrollResponderHandleResponderGrant,
      onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
      onResponderTerminate: this.scrollResponderHandleTerminate,
      onResponderRelease: this.scrollResponderHandleResponderRelease,
      onResponderReject: this.scrollResponderHandleResponderReject,
    };

    return (
      <View {...props} ref={SCROLLVIEW}>
        {contentContainer}
      </View>
    );
  }
};

let styles = StyleSheet.create({
  base: {
    overflowX: 'hidden',
    overflowY: 'scroll',
    WebkitOverflowScrolling: 'touch',
    flex: 1,
  },
  horizontal: {
    overflowX: 'scroll',
    overflowY: 'hidden',
  },
  contentContainer: {
    position: 'absolute',
    minWidth: '100%',
  },
  contentContainerHorizontal: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
  },
});

mixin.onClass(ScrollView, ScrollResponder.Mixin);
autobind(ScrollView);

ScrollView.isReactNativeComponent = true;

export default ScrollView;
<|endoftext|>


<commit_before>/**
 * Created by elad.benedict on 8/26/2015.
 */

var Q = require('q');
var _ = require('underscore');
var kalturaVO = require('./kaltura-client-lib/KalturaVO');
var kalturaClient = require('./kaltura-client-lib/KalturaClient');
var kalturaClientBase = require('./kaltura-client-lib/KalturaClientBase');
var kalturaTypes = require('./kaltura-client-lib/KalturaTypes');
var config = require('./../common/Configuration');
var logger = require('../common/logger').getLogger('BackendClient');
var ErrorUtils = require('./utils/error-utils');
var util=require('util');

var BackendClient = (function(){

    function createClientConfig() {
        var conf = new kalturaClientBase.KalturaConfiguration(partnerId);
        conf.serviceUrl = config.get('backendClient').serviceUrl;
        return conf;
    }

    function convertToMs(minutes) {
        return minutes * 60 * 1000;
    }

    var lastSessionTime = null;
    var adminSecret = config.get('backendClient').adminSecret;
    var partnerId = config.get('backendClient').partnerId;
    var mediaServerHostname = config.get('mediaServer').hostname;
    var applicationName = config.get('mediaServer').applicationName;
    var client = null;
    var clientConfig = createClientConfig();
    var sessionDuration = convertToMs(config.get('backendClient').ksSessionRefreshIntervalMinutes);
    var BackendClient = {};
    var mediaServerIdPromise = null;
    var sessionRequestPromise=null;

    function printAPIResponse(result, headers) {
        logger.info("API call headers: %j", headers);
        if(result)
            logger.info("API call result: %j", result);
    }

    function createSession() {

        var now = new Date();

        //create session
        if (!sessionRequestPromise || !lastSessionTime || (now - lastSessionTime) > sessionDuration) {

            sessionRequestPromise = null;
        }

        if (!sessionRequestPromise) {

            var deferred = Q.defer();
            logger.debug("Request for createSession started");
            client = new kalturaClient.KalturaClient(clientConfig);
            client.session.start(function (results, err, headers) {
                var endTime = new Date();
                var operationTime = endTime - now;
                logger.debug("Request for createSession took %s", operationTime);
                if (err) {
                    logger.error("Failed to create session: %s",  ErrorUtils.error2string(err));
                    printAPIResponse(results, headers);
                    deferred.reject(err);
                }
                if (results) {
                    lastSessionTime = now;
                    logger.info("session created successfully %j", results);
                    client.setSessionId(results);
                    deferred.resolve();
                }
            }, adminSecret, null, kalturaTypes.KalturaSessionType.ADMIN, partnerId, null, null);

            sessionRequestPromise = deferred.promise;
        }

        return sessionRequestPromise;
    }

    function getMediaServerIdPromise() {
        if (mediaServerIdPromise) {
            return mediaServerIdPromise;
        }

        var deferred = Q.defer();

        //get serverNode id by mediaServerHostName
        var serverNodeFilter = new kalturaVO.KalturaWowzaMediaServerNodeFilter();
        serverNodeFilter.hostNameLike = mediaServerHostname;

        client.serverNode.listAction(function(results,err,headers) {

            if (!err && results && _.isArray(results.objects) && results.objects.length>0 && results.objects[0].objectType !== 'KalturaAPIException') {
                var serverNode = results.objects[0];
                logger.info("successfully retrieve serverNodeId for host name %s id %s", mediaServerHostname, serverNode.id);
                deferred.resolve(serverNode.id);
            } else {
                logger.error("Failed to retrieve serverNodeIndex for host %s with error %s %j", mediaServerHostname,  ErrorUtils.error2string(err),results);
                printAPIResponse(results, headers);
                deferred.reject(err);
            }
        }, serverNodeFilter);

        mediaServerIdPromise = deferred.promise;

        return mediaServerIdPromise;
    }

    function convertKalturaEntry(item){
        var res = {
            "entryId" : item.id,
            "flavorParamsIds" : item.flavorParamsIds,
            "partnerId" : item.partnerId
        };
        if (item.dvrStatus === kalturaTypes.KalturaDVRStatus.ENABLED) {

            if (item.dvrWindow) {
                var entryDVRWindow = item.dvrWindow * 60;     //   assuming dvrWindow from backend is in minutes!
                res.dvrWindow = Math.max(config.get("minimalDvrWindow"), entryDVRWindow);

            }
            else {
                res.dvrWindow = config.get("defaultDvrWindow");
            }

            res.maxChunkCount = config.get("dvrMaxChunkCount");
        }
        else {
            res.maxChunkCount = config.get("liveMaxChunkCount");
        }
        return res;
    }

    function getLiveEntries() {
        var deferred = Q.defer();
        var filter = new kalturaVO.KalturaLiveStreamEntryFilter();
        filter.isLive = kalturaTypes.KalturaNullableBoolean.TRUE_VALUE;
        filter.hasMediaServerHostname = mediaServerHostname;
        var pager = {
            pageSize : 300,
            pageIndex : 1
        };
        var startTime = new Date();
        logger.debug("Request for liveStream.listAction started");
        client.liveStream.listAction(function(results, err, headers) {
            var endTime = new Date();
            var operationTime = endTime - startTime;
            logger.debug("Request for liveStream.listAction took %s", operationTime);

            if (results) {
                var objs = _.map(results.objects, convertKalturaEntry);
                logger.debug("Got live entries: %j", objs);
                deferred.resolve(objs);
            }
            else {
                printAPIResponse(results, headers);
                logger.error("Failed to get live entries: %s", err);
                deferred.reject(new Error("Failed to retrieve live entries from server"));
            }
        }, filter, pager);

        return deferred.promise;
    }

    function getServerType(serverNodeId, resultReceived) {
        return (resultReceived.primaryServerNodeId === serverNodeId) ? kalturaTypes.KalturaEntryServerNodeType.LIVE_PRIMARY :
            kalturaTypes.KalturaEntryServerNodeType.LIVE_BACKUP;
    }

    function parseServerEntryInfo(serverNodeId, apiCallResults) {
        var liveEntryObject = convertKalturaEntry(apiCallResults[0]);
        liveEntryObject.serverType = getServerType(serverNodeId, apiCallResults[0]);

        _.each(apiCallResults[1].objects, function(s) {
            if (s.serverNodeId === serverNodeId) {
                liveEntryObject.liveStatus = s.status;
                liveEntryObject.entryServerNodeId = s.id;
            }
        });

        return liveEntryObject;
    }

    function getEntryInfo(entryId, serverNodeId) {
        var deferred = Q.defer();

        client.startMultiRequest();
        var entryServerNodeFilter = new kalturaVO.KalturaEntryServerNodeFilter();
        entryServerNodeFilter.entryIdEqual = entryId;
        client.liveStream.get(null, entryId);
        client.entryServerNode.listAction(null, entryServerNodeFilter);

        var startTime = new Date();
        client.doMultiRequest(function(results, err, headers) {
            var endTime = new Date();
            var operationTime = endTime - startTime;
            logger.info("[%s] Got server node info (took %d)", entryId, operationTime);
            printAPIResponse(results, headers);

            if (!err && results && _.isArray(results) && results.length===2 && results[0] && results[1] &&
                (results[0].objectType !== "KalturaAPIException" || results[1].objectType !== "KalturaAPIException")) {  //Use to indicate success operation
                var liveEntry = parseServerEntryInfo(serverNodeId, results);
                deferred.resolve(liveEntry);
            }
            else {
                var msg=util.format("[%s] Failed to retrieve live stream entry info for from server: %s %j", entryId,  ErrorUtils.error2string(err), results);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        });

        return deferred.promise;
    }

    function registerEntryInDatabase(entryId, serverIndex, state, event) {
        var deferred = Q.defer();
        logger.debug("[%s] Calling registerMediaServer. Hostname: [%s], serverIndex: [%s], Application: [%s], state: [%s]", entryId, mediaServerHostname, serverIndex, applicationName, state);
        client.liveStream.registerMediaServer(function(result, err, headers) {
            printAPIResponse(result, headers);
            if (result && result.objectType === "KalturaLiveStreamEntry") {  //Use to indicate success operation
                logger.info("[%s] Register media server finished successfully - '%s'", entryId, event.toUpperCase());
                deferred.resolve(result);   //check which object, if any, need to pass.
            }
            else {
                var msg=util.format("[%s] Failed to register media from server: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryId, mediaServerHostname, serverIndex, applicationName , state);
        return deferred.promise;
    }

    function unregisterEntryInDatabase(entryId, serverIndex) {
        var deferred = Q.defer();
        logger.debug("[%s] Calling unregisterMediaServer. Hostname: [%s], serverIndex: [%s], Application: [%s]", entryId, mediaServerHostname, serverIndex, applicationName);
        client.liveStream.unregisterMediaServer(function(result, err, headers) {
            printAPIResponse(result, headers);
            if (result && result.objectType === "KalturaLiveStreamEntry") {  //Use to indicate success operation
                logger.info("[%s] Unregister media server finished successfully", entryId);
                deferred.resolve(result);   //check which object, if any, need to pass.
            }
            else {
                var msg=util.format("[%s] Failed to unregister media from server: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryId, mediaServerHostname, serverIndex, applicationName);
        return deferred.promise;
    }

    function updateStreamInfo(entryId, entryServerNodeId, liveEntryServerNode)
    {
        var deferred = Q.defer();
        logger.debug("[%s] Calling updateStreamInfo for entryServerNode id [%s], with stream info array [%j]",entryId,  entryServerNodeId, liveEntryServerNode.streams);
        client.entryServerNode.update(function(result, err, headers) {
            printAPIResponse(result, headers);
            if(err) {
                logger.debug("[%s] Failed to updateStreamInfo for entryServerNode id [%s] with error [%s]",entryId,  entryServerNodeId,  ErrorUtils.error2string(err));
            }
            deferred.resolve();
        }, entryServerNodeId, liveEntryServerNode);

        return deferred.promise;
    }

    function getLiveEntryServerNodes(entryId) {
        var deferred = Q.defer();
        logger.debug("[%s] get entry server node list", entryId);
        var entryServerNodeFilter = new kalturaVO.KalturaEntryServerNodeFilter();
        entryServerNodeFilter.entryIdEqual = entryId;
        client.entryServerNode.listAction(function(result, err, headers) {

            printAPIResponse(result, headers);
            if (result && result.objectType !== "KalturaAPIException" && result.objects) {  //Use to indicate success operation
                logger.info("[%s] entry server node list successfully retrieved [%j]", entryId, result.objects);

                deferred.resolve(result.objects);
            }
            else {
                var msg=util.format("[%s] Failed to retrieve entry server node list: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryServerNodeFilter);

        return deferred.promise;
    }

    BackendClient.getLiveEntryServerNodes = function(entryId) {
        return createSession()
            .then(function() {
                return getLiveEntryServerNodes(entryId);
            });
    };

    BackendClient.getLiveEntriesForMediaServer = function() {
       return createSession()
           .then(function() {
                return getLiveEntries();
            });
    };

    BackendClient.getEntryInfo = function(entryId) {
        return createSession()
            .then(function () {
                return getMediaServerIdPromise().then(function(index) {
                    return getEntryInfo(entryId, index);
                });
            });
    };

    BackendClient.registerEntryInDatabase = function(entryObject, state, event) {
        logger.debug("Entered registerEntryInDatabase. Creating session and calling register");
        return createSession()
            .then(function() {
                return registerEntryInDatabase(entryObject.entryId, entryObject.serverType, state, event);
            });
    };

    BackendClient.unregisterEntryInDatabase = function(entryObject) {
        logger.debug("Entered unregisterEntryInDatabase. Creating session and calling unregister");
        return createSession()
            .then(function() {
                return unregisterEntryInDatabase(entryObject.entryId, entryObject.serverType);
            });
    };

    BackendClient.updateStreamInfo = function(entryId, entryServerNodeId, flavorsObjArray) {
        logger.debug("Calling updateStreamInfo, with new flavors object array");

        var liveEntryServerNode = new kalturaVO.KalturaLiveEntryServerNode();
        var streamInfoArray = [];
        _.each(flavorsObjArray, function(flavorInfo) {
            var KalturaLiveStreamParams = new kalturaVO.KalturaLiveStreamParams();
            KalturaLiveStreamParams.bitrate = flavorInfo.bandwidth;
            KalturaLiveStreamParams.flavorId = flavorInfo.name;
            KalturaLiveStreamParams.width = flavorInfo.resolution ? flavorInfo.resolution[0] : null;
            KalturaLiveStreamParams.height = flavorInfo.resolution ? flavorInfo.resolution[1] : null;

            streamInfoArray.push(KalturaLiveStreamParams);
        });
        liveEntryServerNode.streams = streamInfoArray;

        return createSession()
            .then(function() {
                return updateStreamInfo(entryId, entryServerNodeId, liveEntryServerNode);
            });
    };

    return BackendClient;
})();

module.exports = BackendClient;
<commit_msg>Add mising reject<commit_after>/**
 * Created by elad.benedict on 8/26/2015.
 */

var Q = require('q');
var _ = require('underscore');
var kalturaVO = require('./kaltura-client-lib/KalturaVO');
var kalturaClient = require('./kaltura-client-lib/KalturaClient');
var kalturaClientBase = require('./kaltura-client-lib/KalturaClientBase');
var kalturaTypes = require('./kaltura-client-lib/KalturaTypes');
var config = require('./../common/Configuration');
var logger = require('../common/logger').getLogger('BackendClient');
var ErrorUtils = require('./utils/error-utils');
var util=require('util');

var BackendClient = (function(){

    function createClientConfig() {
        var conf = new kalturaClientBase.KalturaConfiguration(partnerId);
        conf.serviceUrl = config.get('backendClient').serviceUrl;
        return conf;
    }

    function convertToMs(minutes) {
        return minutes * 60 * 1000;
    }

    var lastSessionTime = null;
    var adminSecret = config.get('backendClient').adminSecret;
    var partnerId = config.get('backendClient').partnerId;
    var mediaServerHostname = config.get('mediaServer').hostname;
    var applicationName = config.get('mediaServer').applicationName;
    var client = null;
    var clientConfig = createClientConfig();
    var sessionDuration = convertToMs(config.get('backendClient').ksSessionRefreshIntervalMinutes);
    var BackendClient = {};
    var mediaServerIdPromise = null;
    var sessionRequestPromise=null;

    function printAPIResponse(result, headers) {
        logger.info("API call headers: %j", headers);
        if(result)
            logger.info("API call result: %j", result);
    }

    function createSession() {

        var now = new Date();

        //create session
        if (!sessionRequestPromise || !lastSessionTime || (now - lastSessionTime) > sessionDuration) {

            sessionRequestPromise = null;
        }

        if (!sessionRequestPromise) {

            var deferred = Q.defer();
            logger.debug("Request for createSession started");
            client = new kalturaClient.KalturaClient(clientConfig);
            client.session.start(function (results, err, headers) {
                var endTime = new Date();
                var operationTime = endTime - now;
                logger.debug("Request for createSession took %s", operationTime);
                if (err) {
                    logger.error("Failed to create session: %s",  ErrorUtils.error2string(err));
                    printAPIResponse(results, headers);
                    deferred.reject(err);
                }
                if (results) {
                    lastSessionTime = now;
                    logger.info("session created successfully %j", results);
                    client.setSessionId(results);
                    deferred.resolve();
                }
            }, adminSecret, null, kalturaTypes.KalturaSessionType.ADMIN, partnerId, null, null);

            sessionRequestPromise = deferred.promise;
        }

        return sessionRequestPromise;
    }

    function getMediaServerIdPromise() {
        if (mediaServerIdPromise) {
            return mediaServerIdPromise;
        }

        var deferred = Q.defer();

        //get serverNode id by mediaServerHostName
        var serverNodeFilter = new kalturaVO.KalturaWowzaMediaServerNodeFilter();
        serverNodeFilter.hostNameLike = mediaServerHostname;

        client.serverNode.listAction(function(results,err,headers) {

            if (!err && results && _.isArray(results.objects) && results.objects.length>0 && results.objects[0].objectType !== 'KalturaAPIException') {
                var serverNode = results.objects[0];
                logger.info("successfully retrieve serverNodeId for host name %s id %s", mediaServerHostname, serverNode.id);
                deferred.resolve(serverNode.id);
            } else {
                logger.error("Failed to retrieve serverNodeIndex for host %s with error %s %j", mediaServerHostname,  ErrorUtils.error2string(err),results);
                printAPIResponse(results, headers);
                deferred.reject(err);
            }
        }, serverNodeFilter);

        mediaServerIdPromise = deferred.promise;

        return mediaServerIdPromise;
    }

    function convertKalturaEntry(item){
        var res = {
            "entryId" : item.id,
            "flavorParamsIds" : item.flavorParamsIds,
            "partnerId" : item.partnerId
        };
        if (item.dvrStatus === kalturaTypes.KalturaDVRStatus.ENABLED) {

            if (item.dvrWindow) {
                var entryDVRWindow = item.dvrWindow * 60;     //   assuming dvrWindow from backend is in minutes!
                res.dvrWindow = Math.max(config.get("minimalDvrWindow"), entryDVRWindow);

            }
            else {
                res.dvrWindow = config.get("defaultDvrWindow");
            }

            res.maxChunkCount = config.get("dvrMaxChunkCount");
        }
        else {
            res.maxChunkCount = config.get("liveMaxChunkCount");
        }
        return res;
    }

    function getLiveEntries() {
        var deferred = Q.defer();
        var filter = new kalturaVO.KalturaLiveStreamEntryFilter();
        filter.isLive = kalturaTypes.KalturaNullableBoolean.TRUE_VALUE;
        filter.hasMediaServerHostname = mediaServerHostname;
        var pager = {
            pageSize : 300,
            pageIndex : 1
        };
        var startTime = new Date();
        logger.debug("Request for liveStream.listAction started");
        client.liveStream.listAction(function(results, err, headers) {
            var endTime = new Date();
            var operationTime = endTime - startTime;
            logger.debug("Request for liveStream.listAction took %s", operationTime);

            if (results) {
                var objs = _.map(results.objects, convertKalturaEntry);
                logger.debug("Got live entries: %j", objs);
                deferred.resolve(objs);
            }
            else {
                printAPIResponse(results, headers);
                logger.error("Failed to get live entries: %s", err);
                deferred.reject(new Error("Failed to retrieve live entries from server"));
            }
        }, filter, pager);

        return deferred.promise;
    }

    function getServerType(serverNodeId, resultReceived) {
        return (resultReceived.primaryServerNodeId === serverNodeId) ? kalturaTypes.KalturaEntryServerNodeType.LIVE_PRIMARY :
            kalturaTypes.KalturaEntryServerNodeType.LIVE_BACKUP;
    }

    function parseServerEntryInfo(serverNodeId, apiCallResults) {
        var liveEntryObject = convertKalturaEntry(apiCallResults[0]);
        liveEntryObject.serverType = getServerType(serverNodeId, apiCallResults[0]);

        _.each(apiCallResults[1].objects, function(s) {
            if (s.serverNodeId === serverNodeId) {
                liveEntryObject.liveStatus = s.status;
                liveEntryObject.entryServerNodeId = s.id;
            }
        });

        return liveEntryObject;
    }

    function getEntryInfo(entryId, serverNodeId) {
        var deferred = Q.defer();

        client.startMultiRequest();
        var entryServerNodeFilter = new kalturaVO.KalturaEntryServerNodeFilter();
        entryServerNodeFilter.entryIdEqual = entryId;
        client.liveStream.get(null, entryId);
        client.entryServerNode.listAction(null, entryServerNodeFilter);

        var startTime = new Date();
        client.doMultiRequest(function(results, err, headers) {
            var endTime = new Date();
            var operationTime = endTime - startTime;
            logger.info("[%s] Got server node info (took %d)", entryId, operationTime);
            printAPIResponse(results, headers);

            if (!err && results && _.isArray(results) && results.length===2 && results[0] && results[1] &&
                (results[0].objectType !== "KalturaAPIException" || results[1].objectType !== "KalturaAPIException")) {  //Use to indicate success operation
                var liveEntry = parseServerEntryInfo(serverNodeId, results);
                deferred.resolve(liveEntry);
            }
            else {
                var msg=util.format("[%s] Failed to retrieve live stream entry info for from server: %s %j", entryId,  ErrorUtils.error2string(err), results);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        });

        return deferred.promise;
    }

    function registerEntryInDatabase(entryId, serverIndex, state, event) {
        var deferred = Q.defer();
        logger.debug("[%s] Calling registerMediaServer. Hostname: [%s], serverIndex: [%s], Application: [%s], state: [%s]", entryId, mediaServerHostname, serverIndex, applicationName, state);
        client.liveStream.registerMediaServer(function(result, err, headers) {
            printAPIResponse(result, headers);
            if (result && result.objectType === "KalturaLiveStreamEntry") {  //Use to indicate success operation
                logger.info("[%s] Register media server finished successfully - '%s'", entryId, event.toUpperCase());
                deferred.resolve(result);   //check which object, if any, need to pass.
            }
            else {
                var msg=util.format("[%s] Failed to register media from server: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryId, mediaServerHostname, serverIndex, applicationName , state);
        return deferred.promise;
    }

    function unregisterEntryInDatabase(entryId, serverIndex) {
        var deferred = Q.defer();
        logger.debug("[%s] Calling unregisterMediaServer. Hostname: [%s], serverIndex: [%s], Application: [%s]", entryId, mediaServerHostname, serverIndex, applicationName);
        client.liveStream.unregisterMediaServer(function(result, err, headers) {
            printAPIResponse(result, headers);
            if (result && result.objectType === "KalturaLiveStreamEntry") {  //Use to indicate success operation
                logger.info("[%s] Unregister media server finished successfully", entryId);
                deferred.resolve(result);   //check which object, if any, need to pass.
            }
            else {
                var msg=util.format("[%s] Failed to unregister media from server: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryId, mediaServerHostname, serverIndex, applicationName);
        return deferred.promise;
    }

    function updateStreamInfo(entryId, entryServerNodeId, liveEntryServerNode)
    {
        var deferred = Q.defer();
        logger.debug("[%s] Calling updateStreamInfo for entryServerNode id [%s], with stream info array [%j]",entryId,  entryServerNodeId, liveEntryServerNode.streams);
        client.entryServerNode.update(function(result, err, headers) {
            printAPIResponse(result, headers);
            if(err) {
                logger.debug("[%s] Failed to updateStreamInfo for entryServerNode id [%s] with error [%s]",entryId,  entryServerNodeId,  ErrorUtils.error2string(err));
                deferred.reject();
            }
            deferred.resolve();
        }, entryServerNodeId, liveEntryServerNode);

        return deferred.promise;
    }

    function getLiveEntryServerNodes(entryId) {
        var deferred = Q.defer();
        logger.debug("[%s] get entry server node list", entryId);
        var entryServerNodeFilter = new kalturaVO.KalturaEntryServerNodeFilter();
        entryServerNodeFilter.entryIdEqual = entryId;
        client.entryServerNode.listAction(function(result, err, headers) {

            printAPIResponse(result, headers);
            if (result && result.objectType !== "KalturaAPIException" && result.objects) {  //Use to indicate success operation
                logger.info("[%s] entry server node list successfully retrieved [%j]", entryId, result.objects);

                deferred.resolve(result.objects);
            }
            else {
                var msg=util.format("[%s] Failed to retrieve entry server node list: %s %j", entryId,  ErrorUtils.error2string(err), result);
                logger.error(msg);
                deferred.reject(new Error(msg));
            }
        }, entryServerNodeFilter);

        return deferred.promise;
    }

    BackendClient.getLiveEntryServerNodes = function(entryId) {
        return createSession()
            .then(function() {
                return getLiveEntryServerNodes(entryId);
            });
    };

    BackendClient.getLiveEntriesForMediaServer = function() {
       return createSession()
           .then(function() {
                return getLiveEntries();
            });
    };

    BackendClient.getEntryInfo = function(entryId) {
        return createSession()
            .then(function () {
                return getMediaServerIdPromise().then(function(index) {
                    return getEntryInfo(entryId, index);
                });
            });
    };

    BackendClient.registerEntryInDatabase = function(entryObject, state, event) {
        logger.debug("Entered registerEntryInDatabase. Creating session and calling register");
        return createSession()
            .then(function() {
                return registerEntryInDatabase(entryObject.entryId, entryObject.serverType, state, event);
            });
    };

    BackendClient.unregisterEntryInDatabase = function(entryObject) {
        logger.debug("Entered unregisterEntryInDatabase. Creating session and calling unregister");
        return createSession()
            .then(function() {
                return unregisterEntryInDatabase(entryObject.entryId, entryObject.serverType);
            });
    };

    BackendClient.updateStreamInfo = function(entryId, entryServerNodeId, flavorsObjArray) {
        logger.debug("Calling updateStreamInfo, with new flavors object array");

        var liveEntryServerNode = new kalturaVO.KalturaLiveEntryServerNode();
        var streamInfoArray = [];
        _.each(flavorsObjArray, function(flavorInfo) {
            var KalturaLiveStreamParams = new kalturaVO.KalturaLiveStreamParams();
            KalturaLiveStreamParams.bitrate = flavorInfo.bandwidth;
            KalturaLiveStreamParams.flavorId = flavorInfo.name;
            KalturaLiveStreamParams.width = flavorInfo.resolution ? flavorInfo.resolution[0] : null;
            KalturaLiveStreamParams.height = flavorInfo.resolution ? flavorInfo.resolution[1] : null;

            streamInfoArray.push(KalturaLiveStreamParams);
        });
        liveEntryServerNode.streams = streamInfoArray;

        return createSession()
            .then(function() {
                return updateStreamInfo(entryId, entryServerNodeId, liveEntryServerNode);
            });
    };

    return BackendClient;
})();

module.exports = BackendClient;
<|endoftext|>


<commit_before>'use strict'

const cheerio = require('cheerio')
const got = require('got')
const querystring = require('querystring')

module.exports = class EZTV {

  constructor({baseUrl = 'https://eztv.ag/', debug = false} = {}) {
    this._baseUrl = baseUrl
    this._debug = debug

    EZTV._eztvMap = {
      '10-oclock-live': '10-o-clock-live',
      'battlestar-galactica': 'battlestar-galactica-2003',
      'house-of-cards-2013': 'house-of-cards',
      'black-box': 'the-black-box',
      'brooklyn-nine-nine': 'brooklyn-ninenine',
      'cracked': 'cracked-2013',
      'golden-boy': 'golden-boy-2013',
      'hank': 'hank-2009',
      'hawaii-five-0-2010': 'hawaii-fiveo-2010',
      'legit': 'legit-2013',
      'louie': 'louie-2010',
      'marvels-agent-carter': 'marvel-s-agent-carter',
      'marvels-agents-of-shield': 'marvel-s-agents-of-s-h-i-e-l-d',
      'marvels-avengers-assemble': 'marvel-s-avengers-assemble',
      'marvels-daredevil': 'marvel-s-daredevil',
      'marvels-guardians-of-the-galaxy': 'marvel-s-guardians-of-the-galaxy',
      'power-2014': 'power',
      'reign': 'reign-2013',
      'resurrection-us': 'resurrection',
      'scandal-us': 'scandal-2012',
      'the-fosters': 'the-fosters-2013',
      'the-goldbergs': 'the-goldbergs-2013',
      'the-good-guys': 'the-good-guys-2010',
      'the-killing': 'the-killing-us',
      'the-office': 'the-office-us',
      'vikings-us': 'vikings'
    }

    EZTV._imdbMap = {
      'tt0093036': 'tt3074694',
      'tt0102517': 'tt1657505',
      'tt0264270': 'the-late-late-show',
      'tt0288918': 'big-brother-s-little-brother',
      'tt0413541': 'big-brother-s-big-mouth',
      'tt0432648': 'celebrity-fit-club-2005',
      'tt0983782': 'thank-god-you-re-here',
      'tt1038686': 'dominion',
      'tt1039922': 'la-ink',
      'tt1083958': 'the-pickup-artist',
      'tt1095158': 'the-paper',
      'tt1136131': 'cheerleader-u',
      'tt1190536': 'black-dynamite',
      'tt1198108': 'the-chopping-block-2009',
      'tt1262762': 'mark-loves-sharon',
      'tt1277979': 'hole-in-the-wall',
      'tt1312022': 'time-warp',
      'tt1360544': 'paris-hilton-s-british-best-friend',
      'tt1371997': 'hows-your-news',
      'tt1380582': 'missing',
      'tt1405169': 'newswipe-with-charlie-brooker',
      'tt1470539': 'you-have-been-watching',
      'tt1536736': 'john-safran-s-race-relations',
      'tt1607037': 'gordon-s-great-escape',
      'tt1538090': 'frankie-neffe',
      'tt1673792': 'boston-med',
      'tt1717499': 'onion-news-network',
      'tt1724572': 'the-suspicions-of-mr-whicher',
      'tt1786826': 'get-out-alive-with-bear-grylls',
      'tt1803123': 'royal-institution-christmas-lectures',
      'tt1886866': 'chemistry-2011',
      'tt1926955': 'young-james-herriot',
      'tt2069311': 'fry-s-planet-word',
      'tt2091762': 'the-celebrity-apprentice-australia',
      'tt1989007': 'feasting-on-waves',
      'tt2141186': 'derek',
      'tt2151670': 'planet-earth-live',
      'tt2171637': 'the-story-of-musicals',
      'tt2272367': 'loiter-squad',
      'tt2292521': 'hooters-dream-girls',
      'tt2297363': 'duets-2012',
      'tt2317255': 'the-secret-policeman-s-ball',
      'tt2346091': 'earthflight',
      'tt2724068': 'boston-s-finest',
      'tt2788282': 'bikinis-boardwalks',
      'tt2814102': 'weed-country',
      'tt2936390': 'tt2069449',
      'tt2947494': 'brooklyn-da',
      'tt3351392': 'long-way-round',
      'tt3394574': 'the-great-christmas-light-fight',
      'tt3475768': 'duck-quacks-don-t-echo-uk',
      'tt3529910': 'victoria-wood-s-nice-cup-of-tea',
      'tt3689584': 'satisfaction',
      'tt3713876': 'kirstie-s-handmade-christmas',
      'tt3888812': 'shannons-legends-of-motorsport',
      'tt4135218': 'tt1930315',
      'tt4370492': 'tt0106179',
      'tt4453314': 'jail-las-vegas',
      'tt4472994': 'the-strange-case-of-the-law',
      'tt4563714': 'louis-theroux',
      'tt4614532': 'walking-through-history',
      'tt4726488': 'homes-by-the-sea',
      'tt4883746': 'ali-g-rezurection',
      'tt4903026': 'topp-country',
      'tt4908908': 'carol-klein-s-plant-odysseys',
      'tt4930646': 'epic-attractions',
      'tt5006660': 'tt5090150',
      'tt5013506': 'masterchef-new-zealand',
      'tt5047494': 'dash-dolls',
      'tt5072140': 'sex-diaries',
      'tt5133970': 'building-cars-live',
      'tt5176246': 'tiny-house-world',
      'tt5397520': 'dark-net',
      'tt5489746': 'evil-lives-here'
    }
  }

  _get(uri, query = {}) {
    if (this._debug) {
      console.warn(`Making request to: '${uri}${querystring.stringify(query)}'`)
    }

    return got.get(`${this._baseUrl}/${uri}`, { query })
      .then(({body}) => cheerio.load(body))
  }

  _getEpisodeData(data, $) {
    let imdb = $('div[itemtype="http://schema.org/AggregateRating"]')
      .find('a[target="_blank"]')
      .attr('href')
    imdb = imdb ? imdb.match(/\/title\/(.*)\//)[1] : undefined
    imdb = imdb in EZTV._imdbMap ? EZTV._imdbMap[imdb] : imdb
    data.imdb = imdb

    $('tr.forum_header_border[name="hover"]').each(function () {
      const title = $(this).children('td').eq(1)
        .text()
        .replace('x264', '')
      const magnet = $(this).children('td').eq(2)
        .children('a.magnet')
        .first()
        .attr('href')

      if (!magnet) {
        return
      }

      const seasonBased = /S?0*(\d+).[xE]0*(\d+)/
      const dateBased = /(\d{4}).(\d{2}.\d{2})/
      const quality = title.match(/(\d{3,4})p/)
        ? title.match(/(\d{3,4})p/)[0]
        : '480p'

      let season, episode
      const torrent = {
        url: magnet,
        seeds: 0,
        peers: 0,
        provider: 'EZTV'
      }

      data.episodes = {}
      if (title.match(seasonBased)) {
        season = parseInt(title.match(seasonBased)[1], 10)
        episode = parseInt(title.match(seasonBased)[2], 10)
        data.episodes.dateBased = false
      } else if (title.match(dateBased)) {
        season = title.match(dateBased)[1]
        episode = title.match(dateBased)[2].replace(/\s/g, '-')
        data.episodes.dateBased = true
      } else {
        return
      }

      if (season && episode) {
        if (!data.episodes[season]) {
          data.episodes[season] = {}
        }

        if (!data.episodes[season][episode]) {
          data.episodes[season][episode] = {}
        }

        if (!data.episodes[season][episode][quality] ||
          title.toLowerCase().indexOf('repack') > -1) {
          data.episodes[season][episode][quality] = torrent
        }
      }
    })

    return data
  }

  getAllShows() {
    return this._get('showlist/').then($ => {
      const eztvMap = EZTV._eztvMap

      const regex = /\/shows\/(.*)\/(.*)\//

      const allShows = []
      $('.thread_link').each(function () {
        const show = $(this).text()
        const id = $(this).attr('href').match(regex)[1]
        let slug = $(this).attr('href').match(regex)[2]
        slug = slug in eztvMap ? eztvMap[slug] : slug

        allShows.push({
          show,
          id,
          slug
        })
      })

      return allShows
    })
  }

  getShowData(data) {
    return this._get(`shows/${data.id}/${data.slug}/`)
      .then(res => this._getEpisodeData(data, res))
  }

  getShowEpisodes(data) {
    return this._get(`search/`, {
      q2: data.id
    }).then(res => this._getEpisodeData(data, res))
  }

}
<commit_msg>make sure id is a number<commit_after>'use strict'

const cheerio = require('cheerio')
const got = require('got')
const querystring = require('querystring')

module.exports = class EZTV {

  constructor({baseUrl = 'https://eztv.ag/', debug = false} = {}) {
    this._baseUrl = baseUrl
    this._debug = debug

    EZTV._eztvMap = {
      '10-oclock-live': '10-o-clock-live',
      'battlestar-galactica': 'battlestar-galactica-2003',
      'house-of-cards-2013': 'house-of-cards',
      'black-box': 'the-black-box',
      'brooklyn-nine-nine': 'brooklyn-ninenine',
      'cracked': 'cracked-2013',
      'golden-boy': 'golden-boy-2013',
      'hank': 'hank-2009',
      'hawaii-five-0-2010': 'hawaii-fiveo-2010',
      'legit': 'legit-2013',
      'louie': 'louie-2010',
      'marvels-agent-carter': 'marvel-s-agent-carter',
      'marvels-agents-of-shield': 'marvel-s-agents-of-s-h-i-e-l-d',
      'marvels-avengers-assemble': 'marvel-s-avengers-assemble',
      'marvels-daredevil': 'marvel-s-daredevil',
      'marvels-guardians-of-the-galaxy': 'marvel-s-guardians-of-the-galaxy',
      'power-2014': 'power',
      'reign': 'reign-2013',
      'resurrection-us': 'resurrection',
      'scandal-us': 'scandal-2012',
      'the-fosters': 'the-fosters-2013',
      'the-goldbergs': 'the-goldbergs-2013',
      'the-good-guys': 'the-good-guys-2010',
      'the-killing': 'the-killing-us',
      'the-office': 'the-office-us',
      'vikings-us': 'vikings'
    }

    EZTV._imdbMap = {
      'tt0093036': 'tt3074694',
      'tt0102517': 'tt1657505',
      'tt0264270': 'the-late-late-show',
      'tt0288918': 'big-brother-s-little-brother',
      'tt0413541': 'big-brother-s-big-mouth',
      'tt0432648': 'celebrity-fit-club-2005',
      'tt0983782': 'thank-god-you-re-here',
      'tt1038686': 'dominion',
      'tt1039922': 'la-ink',
      'tt1083958': 'the-pickup-artist',
      'tt1095158': 'the-paper',
      'tt1136131': 'cheerleader-u',
      'tt1190536': 'black-dynamite',
      'tt1198108': 'the-chopping-block-2009',
      'tt1262762': 'mark-loves-sharon',
      'tt1277979': 'hole-in-the-wall',
      'tt1312022': 'time-warp',
      'tt1360544': 'paris-hilton-s-british-best-friend',
      'tt1371997': 'hows-your-news',
      'tt1380582': 'missing',
      'tt1405169': 'newswipe-with-charlie-brooker',
      'tt1470539': 'you-have-been-watching',
      'tt1536736': 'john-safran-s-race-relations',
      'tt1607037': 'gordon-s-great-escape',
      'tt1538090': 'frankie-neffe',
      'tt1673792': 'boston-med',
      'tt1717499': 'onion-news-network',
      'tt1724572': 'the-suspicions-of-mr-whicher',
      'tt1786826': 'get-out-alive-with-bear-grylls',
      'tt1803123': 'royal-institution-christmas-lectures',
      'tt1886866': 'chemistry-2011',
      'tt1926955': 'young-james-herriot',
      'tt2069311': 'fry-s-planet-word',
      'tt2091762': 'the-celebrity-apprentice-australia',
      'tt1989007': 'feasting-on-waves',
      'tt2141186': 'derek',
      'tt2151670': 'planet-earth-live',
      'tt2171637': 'the-story-of-musicals',
      'tt2272367': 'loiter-squad',
      'tt2292521': 'hooters-dream-girls',
      'tt2297363': 'duets-2012',
      'tt2317255': 'the-secret-policeman-s-ball',
      'tt2346091': 'earthflight',
      'tt2724068': 'boston-s-finest',
      'tt2788282': 'bikinis-boardwalks',
      'tt2814102': 'weed-country',
      'tt2936390': 'tt2069449',
      'tt2947494': 'brooklyn-da',
      'tt3351392': 'long-way-round',
      'tt3394574': 'the-great-christmas-light-fight',
      'tt3475768': 'duck-quacks-don-t-echo-uk',
      'tt3529910': 'victoria-wood-s-nice-cup-of-tea',
      'tt3689584': 'satisfaction',
      'tt3713876': 'kirstie-s-handmade-christmas',
      'tt3888812': 'shannons-legends-of-motorsport',
      'tt4135218': 'tt1930315',
      'tt4370492': 'tt0106179',
      'tt4453314': 'jail-las-vegas',
      'tt4472994': 'the-strange-case-of-the-law',
      'tt4563714': 'louis-theroux',
      'tt4614532': 'walking-through-history',
      'tt4726488': 'homes-by-the-sea',
      'tt4883746': 'ali-g-rezurection',
      'tt4903026': 'topp-country',
      'tt4908908': 'carol-klein-s-plant-odysseys',
      'tt4930646': 'epic-attractions',
      'tt5006660': 'tt5090150',
      'tt5013506': 'masterchef-new-zealand',
      'tt5047494': 'dash-dolls',
      'tt5072140': 'sex-diaries',
      'tt5133970': 'building-cars-live',
      'tt5176246': 'tiny-house-world',
      'tt5397520': 'dark-net',
      'tt5489746': 'evil-lives-here'
    }
  }

  _get(uri, query = {}) {
    if (this._debug) {
      console.warn(`Making request to: '${uri}${querystring.stringify(query)}'`)
    }

    return got.get(`${this._baseUrl}/${uri}`, { query })
      .then(({body}) => cheerio.load(body))
  }

  _getEpisodeData(data, $) {
    let imdb = $('div[itemtype="http://schema.org/AggregateRating"]')
      .find('a[target="_blank"]')
      .attr('href')
    imdb = imdb ? imdb.match(/\/title\/(.*)\//)[1] : undefined
    imdb = imdb in EZTV._imdbMap ? EZTV._imdbMap[imdb] : imdb
    data.imdb = imdb

    $('tr.forum_header_border[name="hover"]').each(function () {
      const title = $(this).children('td').eq(1)
        .text()
        .replace('x264', '')
      const magnet = $(this).children('td').eq(2)
        .children('a.magnet')
        .first()
        .attr('href')

      if (!magnet) {
        return
      }

      const seasonBased = /S?0*(\d+).[xE]0*(\d+)/
      const dateBased = /(\d{4}).(\d{2}.\d{2})/
      const quality = title.match(/(\d{3,4})p/)
        ? title.match(/(\d{3,4})p/)[0]
        : '480p'

      let season, episode
      const torrent = {
        url: magnet,
        seeds: 0,
        peers: 0,
        provider: 'EZTV'
      }

      data.episodes = {}
      if (title.match(seasonBased)) {
        season = parseInt(title.match(seasonBased)[1], 10)
        episode = parseInt(title.match(seasonBased)[2], 10)
        data.episodes.dateBased = false
      } else if (title.match(dateBased)) {
        season = title.match(dateBased)[1]
        episode = title.match(dateBased)[2].replace(/\s/g, '-')
        data.episodes.dateBased = true
      } else {
        return
      }

      if (season && episode) {
        if (!data.episodes[season]) {
          data.episodes[season] = {}
        }

        if (!data.episodes[season][episode]) {
          data.episodes[season][episode] = {}
        }

        if (!data.episodes[season][episode][quality] ||
          title.toLowerCase().indexOf('repack') > -1) {
          data.episodes[season][episode][quality] = torrent
        }
      }
    })

    return data
  }

  getAllShows() {
    return this._get('showlist/').then($ => {
      const eztvMap = EZTV._eztvMap

      const regex = /\/shows\/(.*)\/(.*)\//

      const allShows = []
      $('.thread_link').each(function () {
        const show = $(this).text()
        const id = parseInt($(this).attr('href').match(regex)[1], 10)
        let slug = $(this).attr('href').match(regex)[2]
        slug = slug in eztvMap ? eztvMap[slug] : slug

        allShows.push({
          show,
          id,
          slug
        })
      })

      return allShows
    })
  }

  getShowData(data) {
    return this._get(`shows/${data.id}/${data.slug}/`)
      .then($ => this._getEpisodeData(data, $))
  }

  getShowEpisodes(data) {
    return this._get(`search/`
    //   {
    //   q2: data.id
    // }
  ).then($ => this._getEpisodeData(data, $))
  }

}
<|endoftext|>