<commit_before>import {exec} from 'child_process';
import path from 'path';
import promisify from 'es6-promisify';
import npm from 'npm';
import {gt} from 'semver';
import {log} from 'gulp-util';

import localNpm from './local-npm-helper';

const npmLoad = promisify(npm.load);

async function filterPackages(packageInfos, packageInfo) {
  const {name, version: localVersion, dir} = packageInfo;

  try {
    const publishedVersion = (await promisify(exec)(`npm show ${name} version`)).trim();

    if (gt(localVersion, publishedVersion)) {
      log('Publishing: ', name, dir);
      (await packageInfos).push(packageInfo);
    } else {
      log('Skipping: ', name, dir);
    }
  } catch (e) {
    if (e.message.match(/npm show/)) {
      log(`Warning: ${name} is not published`);
    } else {
      console.error(e.stack);
    }
  }

  return packageInfos;
}

export function getPackageInfo(file) {
  const {name, version} = JSON.parse(file.contents.toString());

  return {
    name: name,
    version: version,
    dir: path.dirname(file.path)
  };
}

export async function infoForUpdatedPackages(files) {
  const packageInfos = files.map(getPackageInfo);

  return await packageInfos.reduce(filterPackages, []);
}

export function publishPackages(registry) {
  return async (packageInfos) => {
    await npmLoad({});
    const npmPublish = promisify(npm.commands.publish);
    const npmOwner = promisify(npm.commands.owner);
    if (registry) {
      npm.config.set('registry', registry); //
      if (npm.config.get('registry') !== registry) { //
        const e = new Error('Must be pointing at private npm to test locally!');
        console.error(e);
        callback(e);
        return;
      }
    }
    for (const index in packageInfos) {
      let packageInfo = packageInfos[index];
      if (packageInfo && packageInfo.name) {

        await npmPublish([packageInfo.dir]);

        if (!registry) { //sinopia doesn't seem to support maintainers
          const owners = ['charleshansen', 'atomanyih', 'kennyw1019', 'aberkovec', 'esharma', 'chentom88', 'sjolicoeur', 'jberney', 'elana'];
          for (const owner of owners) {
            await npmOwner(['add', owner, packageInfo.name]);
          }
        }
      } else {
        log('Not a valid package', packageInfo);
      }
    }
  };
}

export function publishFakePackages() {
  return publishPackages(localNpm.registryUrl);
}
<commit_msg>Add apps-manager as an owner of pui<commit_after>import {exec} from 'child_process';
import path from 'path';
import promisify from 'es6-promisify';
import npm from 'npm';
import {gt} from 'semver';
import {log} from 'gulp-util';

import localNpm from './local-npm-helper';

const npmLoad = promisify(npm.load);

async function filterPackages(packageInfos, packageInfo) {
  const {name, version: localVersion, dir} = packageInfo;

  try {
    const publishedVersion = (await promisify(exec)(`npm show ${name} version`)).trim();

    if (gt(localVersion, publishedVersion)) {
      log('Publishing: ', name, dir);
      (await packageInfos).push(packageInfo);
    } else {
      log('Skipping: ', name, dir);
    }
  } catch (e) {
    if (e.message.match(/npm show/)) {
      log(`Warning: ${name} is not published`);
    } else {
      console.error(e.stack);
    }
  }

  return packageInfos;
}

export function getPackageInfo(file) {
  const {name, version} = JSON.parse(file.contents.toString());

  return {
    name: name,
    version: version,
    dir: path.dirname(file.path)
  };
}

export async function infoForUpdatedPackages(files) {
  const packageInfos = files.map(getPackageInfo);

  return await packageInfos.reduce(filterPackages, []);
}

export function publishPackages(registry) {
  return async (packageInfos) => {
    await npmLoad({});
    const npmPublish = promisify(npm.commands.publish);
    const npmOwner = promisify(npm.commands.owner);
    if (registry) {
      npm.config.set('registry', registry); //
      if (npm.config.get('registry') !== registry) { //
        const e = new Error('Must be pointing at private npm to test locally!');
        console.error(e);
        callback(e);
        return;
      }
    }
    for (const index in packageInfos) {
      let packageInfo = packageInfos[index];
      if (packageInfo && packageInfo.name) {

        await npmPublish([packageInfo.dir]);

        if (!registry) { //sinopia doesn't seem to support maintainers
          const owners = ['charleshansen', 'atomanyih', 'kennyw1019', 'aberkovec', 'esharma', 'chentom88', 'sjolicoeur', 'jberney', 'elana', 'apps-manager'];
          for (const owner of owners) {
            await npmOwner(['add', owner, packageInfo.name]);
          }
        }
      } else {
        log('Not a valid package', packageInfo);
      }
    }
  };
}

export function publishFakePackages() {
  return publishPackages(localNpm.registryUrl);
}
<|endoftext|>


<commit_before>BackBehaviour = {};

BackBehaviour._checkViewTreeForCallback = function _checkViewTreeForCallback (view) {
  // Hit the top of the view tree
  if (! view) {
    return null;
  }
  // If callback is defined on the template return it
  if (view.template && view.template._onBack) {
    return view;
  } else {
    // Traverse the tree
    return _checkViewTreeForCallback(view.parentView);
  }
};

BackBehaviour._getRouterOnBackCallback = function _getRouterOnBackCallback () {
  // Check for iron-router
  if (typeof Router !== 'undefined' && typeof Router.current === 'function') {
    var controller = Router.current();
    if (typeof controller.onBack === 'function') {
      // Found one, return bound to controller
      return controller.onBack.bind(controller);
    } else return null;
  // Check for flow-router
  } else if (typeof FlowRouter !== 'undefined' && typeof FlowRouter.current === 'function') {
    var controller = FlowRouter.current(),
        routeOptions = controller.route && controller.route.options;
    if (routeOptions && typeof routeOptions.onBack === 'function') {
      return routeOptions.onBack.bind(controller);
    } else return null;
  } else {
    return null;
  }
}

BackBehaviour._getContextBoundOnBack = function _getContextBoundOnBack (originTemplateInstance) {
  var viewWithOnBack, routerCallback;
  if (originTemplateInstance) {
    // Walk up the view tree to look for onBack defined on templates
    viewWithOnBack = this._checkViewTreeForCallback(originTemplateInstance.view)
  } else {
    routerCallback = BackBehaviour._getRouterOnBackCallback();
  }

  if (viewWithOnBack) {
    // If we find a callback in the view tree, return it bound to its template instance
    return viewWithOnBack.template._onBack.bind(viewWithOnBack.templateInstance());
  } else if (routerCallback) {
    return routerCallback;
  } else {
    // Hmm, no more options :(
    console.warn('BackBehaviour did not find an onBack callback to execute.');
    return null;
  }
};

BackBehaviour._detailsObj = function _detailsObj (options) {
  // return details object with expected keys defined (even as `null`)
  return _.extend({}, {
    dataContext: null,
    templateEvent: null
  }, options);
};

BackBehaviour.goBack = function (details, origin) {
  var templateInstance = Template.instance();
  if (!origin) {
    origin = 'custom';
  }
  // find the closest callback
  var onBack = this._getContextBoundOnBack(templateInstance);
  if (onBack) {
    // execute
    onBack(this._detailsObj(details), origin);
  }
};

BackBehaviour._onHardwareBackButtonDown = function (event) {
  // stop the default browser event i.e. history.go(-1)
  event.preventDefault();
  event.stopPropagation();

  // send user back via back-behaviour
  BackBehaviour.goBack({
    templateEvent: event,
  }, 'HardwareBackButton_press');
};

BackBehaviour.attachToHardwareBackButton = function (enable) {
  if (enable !== true && enable !== false) {
    console.warn('BackBehaviour.attachToHardwareBackButton called without a valid argument. Use true or false to enable or disable attachment.');
  }
  if (Meteor.isCordova) {
     if (enable === true) {
      document.addEventListener('backbutton', this._onHardwareBackButtonDown, false);
    } else if (enable === false) {
      document.removeEventListener('backbutton', this._onHardwareBackButtonDown, false);
    }
  }
};
<commit_msg>removed the else as it was causing router call back not to run<commit_after>BackBehaviour = {};

BackBehaviour._checkViewTreeForCallback = function _checkViewTreeForCallback (view) {
  // Hit the top of the view tree
  if (! view) {
    return null;
  }
  // If callback is defined on the template return it
  if (view.template && view.template._onBack) {
    return view;
  } else {
    // Traverse the tree
    return _checkViewTreeForCallback(view.parentView);
  }
};

BackBehaviour._getRouterOnBackCallback = function _getRouterOnBackCallback () {
  // Check for iron-router
  if (typeof Router !== 'undefined' && typeof Router.current === 'function') {
    var controller = Router.current();
    if (typeof controller.onBack === 'function') {
      // Found one, return bound to controller
      return controller.onBack.bind(controller);
    } else return null;
  // Check for flow-router
  } else if (typeof FlowRouter !== 'undefined' && typeof FlowRouter.current === 'function') {
    var controller = FlowRouter.current(),
        routeOptions = controller.route && controller.route.options;
    if (routeOptions && typeof routeOptions.onBack === 'function') {
      return routeOptions.onBack.bind(controller);
    } else return null;
  } else {
    return null;
  }
}

BackBehaviour._getContextBoundOnBack = function _getContextBoundOnBack (originTemplateInstance) {
  var viewWithOnBack, routerCallback;
  if (originTemplateInstance) {
    // Walk up the view tree to look for onBack defined on templates
    viewWithOnBack = this._checkViewTreeForCallback(originTemplateInstance.view);
  }

  routerCallback = BackBehaviour._getRouterOnBackCallback();

  if (viewWithOnBack) {
    // If we find a callback in the view tree, return it bound to its template instance
    return viewWithOnBack.template._onBack.bind(viewWithOnBack.templateInstance());
  } else if (routerCallback) {
    return routerCallback;
  } else {
    // Hmm, no more options :(
    console.warn('BackBehaviour did not find an onBack callback to execute.');
    return null;
  }
};

BackBehaviour._detailsObj = function _detailsObj (options) {
  // return details object with expected keys defined (even as `null`)
  return _.extend({}, {
    dataContext: null,
    templateEvent: null
  }, options);
};

BackBehaviour.goBack = function (details, origin) {
  var templateInstance = Template.instance();
  if (!origin) {
    origin = 'custom';
  }
  // find the closest callback
  var onBack = this._getContextBoundOnBack(templateInstance);
  if (onBack) {
    // execute
    onBack(this._detailsObj(details), origin);
  }
};

BackBehaviour._onHardwareBackButtonDown = function (event) {
  // stop the default browser event i.e. history.go(-1)
  event.preventDefault();
  event.stopPropagation();

  // send user back via back-behaviour
  BackBehaviour.goBack({
    templateEvent: event,
  }, 'HardwareBackButton_press');
};

BackBehaviour.attachToHardwareBackButton = function (enable) {
  if (enable !== true && enable !== false) {
    console.warn('BackBehaviour.attachToHardwareBackButton called without a valid argument. Use true or false to enable or disable attachment.');
  }
  if (Meteor.isCordova) {
     if (enable === true) {
      document.addEventListener('backbutton', this._onHardwareBackButtonDown, false);
    } else if (enable === false) {
      document.removeEventListener('backbutton', this._onHardwareBackButtonDown, false);
    }
  }
};
<|endoftext|>


<commit_before>/*global require, exports, console, setInterval, clearInterval*/

var logger = require('./../common/logger').logger;

// Logger
var log = logger.getLogger("RoomController");

exports.RoomController = function (spec) {
    "use strict";

    var that = {},
        // {id: array of subscribers}
        subscribers = {},
        // {id: erizoJS_id}
        publishers = {},
        // {erizoJS_id: {publishers: [ids], ka_count: count}}
        erizos = {},

        // {id: ExternalOutput}
        externalOutputs = {};

    var amqper = spec.amqper;
    var ecch = spec.ecch;

    var KEEPALIVE_INTERVAL = 5*1000;
    var TIMEOUT_LIMIT = 2;
    var MAX_ERIZOJS_RETRIES = 2;

    var eventListeners = [];

    var callbackFor = function(erizo_id) {

        return function(ok) {
            if (!erizos[erizo_id]) return;

            if (ok !== true) {
                erizos[erizo_id].ka_count ++;

                if (erizos[erizo_id].ka_count > TIMEOUT_LIMIT) {

                    for (var p in erizos[erizo_id].publishers) {
                        log.error("Lost connection with ErizoJS, will remove publishers", erizo_id);
                        dispatchEvent("unpublish", erizos[erizo_id].publishers[p]);
                    }
                    ecch.deleteErizoJS(erizo_id);
                    delete erizos[erizo_id];
                }
            } else {
                erizos[erizo_id].ka_count = 0;
            }
        }
    };

    var sendKeepAlive = function() {
        for (var e in erizos) {
            amqper.callRpc("ErizoJS_" + e, "keepAlive", [], {callback: callbackFor(e)});
        }
    };

    var keepAliveLoop = setInterval(sendKeepAlive, KEEPALIVE_INTERVAL);

    var getErizoJS = function(callback) {
    	ecch.getErizoJS(function(erizo_id) {
            if (!erizos[erizo_id] && erizo_id !== 'timeout') {
                erizos[erizo_id] = {publishers: [], ka_count: 0};
            }
            callback(erizo_id);
        });
    };

    var getErizoQueue = function(publisher_id) {
        return "ErizoJS_" + publishers[publisher_id];
    };

    var dispatchEvent = function(type, event) {
        for (var event_id in eventListeners) {
            eventListeners[event_id](type, event);
        }

    };

/*  Prototype method to add a branch to a erizo Tree
    var shouldAddSurrogate = function(publisher_id, subscriber_id, options, callback){
        //Create new erizoJS, assign it as surrogate of publisher_id (subscribe), return id
        log.info("Adding a surrogate");
        getErizoJS(function(id){
            log.info("got a new Erizo with id", id);

//            log.info("Adding subscriber ", id, ' to publisher ', publisher_id);
            var options = {};
            if (options.audio === undefined) options.audio = true;
            if (options.video === undefined) options.video = true;

            var argsAddPub = [publisher_id, 300, true];
            log.info("Adding publisher to surrogate", "ErizoJS_"+id, "args",argsAddPub);
            var statusBranch = false;
            var statusRoot = false;
            var branchQueue = [];
            var rootQueue = [];
            log.info("calling addPublisher on branch");
            amqper.callRpc("ErizoJS_"+id, "addPublisher", argsAddPub, {callback: function(msg){
                log.info("Message from branch", msg.type);
                if (msg.type==='started'){
                    statusbranch = 'started';
                    log.info("branch Started");
                    if (branchQueue.length){
                        while (branchQueue.length>0){
                            var themessage = branchQueue.shift();
                            var argus = [publisher_id, undefined, themessage];
                            console.log("Queued msg from Erizoroot, sending to Erizobranch", argus);
                            amqper.callRpc("ErizoJS_"+id, "processSignaling", argus, {});
                        }

                    }

                }else if (msg.type === 'offer' || msg.type ==='candidate'){
                    var argsSignaling = [publisher_id, id, msg];
                    console.log("msg from Erizobranch, should to Erizoroot?");
                    if (statusroot){
                        console.log("Yes, sending", argsSignaling);
                        amqper.callRpc(getErizoQueue(publisher_id, id), "processSignaling", argsSignaling, {});
                    }else{
                        console.log("No, queuing", argsSignaling);
                        rootQueue.push(msg);
                    }
                }else if (msg.type === 'ready'){
                    log.info("Surrogate ready, firing after a second");
                    setTimeout (callback(id), 1000);
                }

            }});

            log.info("calling addSubscriber on root");
            var argsAddSub = [id, publisher_id, options];
            amqper.callRpc(getErizoQueue(publisher_id), "addSubscriber", argsAddSub, {callback: function(mess){
                log.info("Message from root", mess.type);
                if (mess.type==='started'){
                    statusroot = 'started';
                    log.info("root Started");
                    if (rootQueue.length){
                        while (rootQueue.length>0){
                            var themessage = rootQueue.shift();
                            var argsSignaling = [publisher_id, id, themessage];
                            console.log("Queued msg from Erizobranch, sending to Erizoroot", argsSignaling);
                            amqper.callRpc(getErizoQueue(publisher_id, id), "processSignaling", argsSignaling, {});
                        }

                    }

                }else if (mess.type === 'answer' || mess.type ==='candidate'){
                    if (mess.type === 'answer'){
                        mess.type = 'offer';
                    }
                    var argus = [publisher_id, subscriber_id, mess];

                    console.log("signalling from Erizoroot, should send to branch?");
                    if (statusbranch){
                        console.log("Yes, sending", argus);
                        amqper.callRpc("ErizoJS_"+id, "processSignaling", argus, {});
                    }else{
                        console.log("No, queuing", argus);
                        branchQueue.push(mess);
                    }
                }
            }});
            subscribers[publisher_id].push({id:subscriber_id, surrogate_id:id});
            // Track subscriber locally

        });

    }
*/
    that.addEventListener = function(eventListener) {
        eventListeners.push(eventListener);
    };

    that.addExternalInput = function (publisher_id, url, callback) {

        if (publishers[publisher_id] === undefined) {

            log.info("Adding external input peer_id ", publisher_id);

            getErizoJS(function(erizo_id) {
                // then we call its addPublisher method.
    	        var args = [publisher_id, url];

                // Track publisher locally
//                publishers[publisher_id] = {};
                publishers[publisher_id] = erizo_id;
                subscribers[publisher_id] = [];

                amqper.callRpc(getErizoQueue(publisher_id), "addExternalInput", args, {callback: callback});

                erizos[erizo_id].publishers.push(publisher_id);

            });
        } else {
            log.info("Publisher already set for", publisher_id);
        }
    };

    that.addExternalOutput = function (publisher_id, url, callback) {
        if (publishers[publisher_id] !== undefined) {
            log.info("Adding ExternalOutput to " + publisher_id + " url " + url);

            var args = [publisher_id, url];

            amqper.callRpc(getErizoQueue(publisher_id), "addExternalOutput", args, undefined);

            // Track external outputs
            externalOutputs[url] = publisher_id;

            // Track publisher locally
            // publishers[publisher_id] = publisher_id;
            // subscribers[publisher_id] = [];
            callback('success');
        } else {
            callback('error');
        }

    };

    that.removeExternalOutput = function (url, callback) {
        var publisher_id = externalOutputs[url];

        if (publisher_id !== undefined && publishers[publisher_id] != undefined) {
            log.info("Stopping ExternalOutput: url " + url);

            var args = [publisher_id, url];
            amqper.callRpc(getErizoQueue(publisher_id), "removeExternalOutput", args, undefined);

            // Remove track
            delete externalOutputs[url];
            callback(true);
        } else {
            callback(null, 'This stream is not being recorded');
        }
    };

    that.processSignaling = function (streamId, peerId, msg) {

        if (publishers[streamId] !== undefined) {

//            log.info("Sending signaling mess to erizoJS of st ", streamId, ' of peer ', peerId);

            var args = [streamId, peerId, msg];

            amqper.callRpc(getErizoQueue(streamId), "processSignaling", args, {});

        }
    };

    /*
     * Adds a publisher to the room. This creates a new OneToManyProcessor
     * and a new WebRtcConnection. This WebRtcConnection will be the publisher
     * of the OneToManyProcessor.
     */
    that.addPublisher = function (publisher_id, options, callback, retries) {
        if (retries === undefined)
            retries = 0;

        if (publishers[publisher_id] === undefined) {

            log.info("Adding publisher peer_id ", publisher_id, "options", options);;

            // We create a new ErizoJS with the publisher_id.
            getErizoJS(function(erizo_id) {

                if (erizo_id === 'timeout') {
                    log.error("Cannot contact ErizoAgent to add Publisher -- timeout");
                    callback('timeout-agent');
                    return;
                }
            	log.debug("ErizoJS id:", erizo_id, "assigned for publisher", publisher_id);
                // Track publisher locally

                // then we call its addPublisher method.
                var args = [publisher_id, options];
                publishers[publisher_id] = erizo_id;
                subscribers[publisher_id] = [];

                amqper.callRpc(getErizoQueue(publisher_id), "addPublisher", args, {callback: function (data){
                    if (data === 'timeout'){
                        if (retries < MAX_ERIZOJS_RETRIES){
                            publishers[publisher_id] = undefined;
                            retries++;
                            log.warn("ErizoJS timed out, trying again to publish", publisher_id, "number of tries", retries);
                            that.addPublisher(publisher_id, options,callback, retries);
                            return;
                        }
                        log.error("Can not contact ErizoJS", publisher_id , " failed add Publisher -- timeout");
                        callback('timeout-erizojs');
                        return;
                    }else{
                        callback(data);
                    }
                }});

                erizos[erizo_id].publishers.push(publisher_id);
            });

        } else {
            log.warn("Publisher already set for", publisher_id);
        }
    };

    /*
     * Adds a subscriber to the room. This creates a new WebRtcConnection.
     * This WebRtcConnection will be added to the subscribers list of the
     * OneToManyProcessor.
     */
    that.addSubscriber = function (subscriber_id, publisher_id, options, callback, retries) {
        if (subscriber_id === null){
          callback("Error: null subscriber_id");
          return;
        }
        if (retries === undefined)
            retries = 0;

        if (publishers[publisher_id] !== undefined && subscribers[publisher_id].indexOf(subscriber_id) === -1) {
            log.info("Adding subscriber ", subscriber_id, ' to publisher ', publisher_id, "options", options);

//            if (true){

                if (options.audio === undefined) options.audio = true;
                if (options.video === undefined) options.video = true;

                var args = [subscriber_id, publisher_id, options];
                //TODO: Potential problem here if erizoJS is not reachable
                amqper.callRpc(getErizoQueue(publisher_id, undefined), "addSubscriber", args, {callback: function (data){
                    if (data === 'timeout'){
                        if (retries < MAX_ERIZOJS_RETRIES){
                            retries++;
                            log.warn("ErizoJS timed out, trying again to subscribe to ", publisher_id, "from", subscriber_id, "number of tries", retries);
                            that.addSubscriber(subscriber_id, publisher_id, options, callback, retries);
                            return;
                        }
                        log.error("Can not contact to ErizoJS", publisher_id , " failed add Subscriber -- timeout");
                        callback('timeout');
                        return;
                    }else if (data === 'initializing'){
                        subscribers[publisher_id].push(subscriber_id);
                    }
                    callback(data);
                }});

/*            }else{ // Prototype for erizo_trees
                shouldAddSurrogate (publisher_id, subscriber_id, options, function(new_id){
                    log.info("Surrogate ?", new_id);

                    if (options.audio === undefined) options.audio = true;
                    if (options.video === undefined) options.video = true;

                    var args = [subscriber_id, publisher_id, options];

                    subscribers[publisher_id].push({id:subscriber_id, surrogate:new_id});
                    amqper.callRpc(getErizoQueue(publisher_id, subscriber_id), "addSubscriber", args, {callback: callback});
                    // Track subscriber locally
                });

            }
            */
        }
    };

    /*
     * Removes a publisher from the room. This also deletes the associated OneToManyProcessor.
     */
    that.removePublisher = function (publisher_id) {

        if (subscribers[publisher_id] !== undefined && publishers[publisher_id]!== undefined) {
            log.info("Removing publisher", publisher_id);

            var args = [publisher_id];
            amqper.callRpc(getErizoQueue(publisher_id), "removePublisher", args, undefined);

            // Remove tracks
            // TODO: Remove all surrogates
            var index = erizos[publishers[publisher_id]].publishers.indexOf(publisher_id);
            erizos[publishers[publisher_id]].publishers.splice(index, 1);

            delete subscribers[publisher_id];
            delete publishers[publisher_id];
            log.info('Removed muxer', publisher_id, ' muxers left ', Object.keys(publishers).length );
        }
    };

    /*
     * Removes a subscriber from the room. This also removes it from the associated OneToManyProcessor.
     */
    that.removeSubscriber = function (subscriber_id, publisher_id) {

        var index = subscribers[publisher_id].indexOf(subscriber_id);
        if (index !== -1) {
            log.info('Removing subscriber ', subscriber_id, 'to muxer ', publisher_id);

            var args = [subscriber_id, publisher_id];
            amqper.callRpc(getErizoQueue(publisher_id), "removeSubscriber", args, undefined);

            subscribers[publisher_id].splice(index, 1);
        }
    };

    /*
     * Removes all the subscribers related with a client.
     */
    that.removeSubscriptions = function (subscriber_id) {

        var publisher_id, index;

        log.info('Removing subscriptions of ', subscriber_id);

        for (publisher_id in subscribers) {
            if (subscribers.hasOwnProperty(publisher_id)) {
                index = subscribers[publisher_id].indexOf(subscriber_id);
                if (index !== -1) {
                    log.debug('Removing subscriber ', subscriber_id, 'from muxer ', publisher_id);

                    var args = [subscriber_id, publisher_id];
            		amqper.callRpc(getErizoQueue(publisher_id), "removeSubscriber", args, undefined);

            		// Remove tracks
                    subscribers[publisher_id].splice(index, 1);
                }
            }
        }
    };

    return that;
};
<commit_msg>Properly removed publisher in RoomController on erizoJS timeout<commit_after>/*global require, exports, console, setInterval, clearInterval*/

var logger = require('./../common/logger').logger;

// Logger
var log = logger.getLogger("RoomController");

exports.RoomController = function (spec) {
    "use strict";

    var that = {},
        // {id: array of subscribers}
        subscribers = {},
        // {id: erizoJS_id}
        publishers = {},
        // {erizoJS_id: {publishers: [ids], ka_count: count}}
        erizos = {},

        // {id: ExternalOutput}
        externalOutputs = {};

    var amqper = spec.amqper;
    var ecch = spec.ecch;

    var KEEPALIVE_INTERVAL = 5*1000;
    var TIMEOUT_LIMIT = 2;
    var MAX_ERIZOJS_RETRIES = 2;

    var eventListeners = [];

    var callbackFor = function(erizo_id) {

        return function(ok) {
            if (!erizos[erizo_id]) return;

            if (ok !== true) {
                erizos[erizo_id].ka_count ++;

                if (erizos[erizo_id].ka_count > TIMEOUT_LIMIT) {

                    for (var p in erizos[erizo_id].publishers) {
                        log.error("Lost connection with ErizoJS, will remove publishers", erizo_id);
                        dispatchEvent("unpublish", erizos[erizo_id].publishers[p]);
                    }
                    ecch.deleteErizoJS(erizo_id);
                    delete erizos[erizo_id];
                }
            } else {
                erizos[erizo_id].ka_count = 0;
            }
        }
    };

    var sendKeepAlive = function() {
        for (var e in erizos) {
            amqper.callRpc("ErizoJS_" + e, "keepAlive", [], {callback: callbackFor(e)});
        }
    };

    var keepAliveLoop = setInterval(sendKeepAlive, KEEPALIVE_INTERVAL);

    var getErizoJS = function(callback) {
    	ecch.getErizoJS(function(erizo_id) {
            if (!erizos[erizo_id] && erizo_id !== 'timeout') {
                erizos[erizo_id] = {publishers: [], ka_count: 0};
            }
            callback(erizo_id);
        });
    };

    var getErizoQueue = function(publisher_id) {
        return "ErizoJS_" + publishers[publisher_id];
    };

    var dispatchEvent = function(type, event) {
        for (var event_id in eventListeners) {
            eventListeners[event_id](type, event);
        }

    };

/*  Prototype method to add a branch to a erizo Tree
    var shouldAddSurrogate = function(publisher_id, subscriber_id, options, callback){
        //Create new erizoJS, assign it as surrogate of publisher_id (subscribe), return id
        log.info("Adding a surrogate");
        getErizoJS(function(id){
            log.info("got a new Erizo with id", id);

//            log.info("Adding subscriber ", id, ' to publisher ', publisher_id);
            var options = {};
            if (options.audio === undefined) options.audio = true;
            if (options.video === undefined) options.video = true;

            var argsAddPub = [publisher_id, 300, true];
            log.info("Adding publisher to surrogate", "ErizoJS_"+id, "args",argsAddPub);
            var statusBranch = false;
            var statusRoot = false;
            var branchQueue = [];
            var rootQueue = [];
            log.info("calling addPublisher on branch");
            amqper.callRpc("ErizoJS_"+id, "addPublisher", argsAddPub, {callback: function(msg){
                log.info("Message from branch", msg.type);
                if (msg.type==='started'){
                    statusbranch = 'started';
                    log.info("branch Started");
                    if (branchQueue.length){
                        while (branchQueue.length>0){
                            var themessage = branchQueue.shift();
                            var argus = [publisher_id, undefined, themessage];
                            console.log("Queued msg from Erizoroot, sending to Erizobranch", argus);
                            amqper.callRpc("ErizoJS_"+id, "processSignaling", argus, {});
                        }

                    }

                }else if (msg.type === 'offer' || msg.type ==='candidate'){
                    var argsSignaling = [publisher_id, id, msg];
                    console.log("msg from Erizobranch, should to Erizoroot?");
                    if (statusroot){
                        console.log("Yes, sending", argsSignaling);
                        amqper.callRpc(getErizoQueue(publisher_id, id), "processSignaling", argsSignaling, {});
                    }else{
                        console.log("No, queuing", argsSignaling);
                        rootQueue.push(msg);
                    }
                }else if (msg.type === 'ready'){
                    log.info("Surrogate ready, firing after a second");
                    setTimeout (callback(id), 1000);
                }

            }});

            log.info("calling addSubscriber on root");
            var argsAddSub = [id, publisher_id, options];
            amqper.callRpc(getErizoQueue(publisher_id), "addSubscriber", argsAddSub, {callback: function(mess){
                log.info("Message from root", mess.type);
                if (mess.type==='started'){
                    statusroot = 'started';
                    log.info("root Started");
                    if (rootQueue.length){
                        while (rootQueue.length>0){
                            var themessage = rootQueue.shift();
                            var argsSignaling = [publisher_id, id, themessage];
                            console.log("Queued msg from Erizobranch, sending to Erizoroot", argsSignaling);
                            amqper.callRpc(getErizoQueue(publisher_id, id), "processSignaling", argsSignaling, {});
                        }

                    }

                }else if (mess.type === 'answer' || mess.type ==='candidate'){
                    if (mess.type === 'answer'){
                        mess.type = 'offer';
                    }
                    var argus = [publisher_id, subscriber_id, mess];

                    console.log("signalling from Erizoroot, should send to branch?");
                    if (statusbranch){
                        console.log("Yes, sending", argus);
                        amqper.callRpc("ErizoJS_"+id, "processSignaling", argus, {});
                    }else{
                        console.log("No, queuing", argus);
                        branchQueue.push(mess);
                    }
                }
            }});
            subscribers[publisher_id].push({id:subscriber_id, surrogate_id:id});
            // Track subscriber locally

        });

    }
*/
    that.addEventListener = function(eventListener) {
        eventListeners.push(eventListener);
    };

    that.addExternalInput = function (publisher_id, url, callback) {

        if (publishers[publisher_id] === undefined) {

            log.info("Adding external input peer_id ", publisher_id);

            getErizoJS(function(erizo_id) {
                // then we call its addPublisher method.
    	        var args = [publisher_id, url];

                // Track publisher locally
//                publishers[publisher_id] = {};
                publishers[publisher_id] = erizo_id;
                subscribers[publisher_id] = [];

                amqper.callRpc(getErizoQueue(publisher_id), "addExternalInput", args, {callback: callback});

                erizos[erizo_id].publishers.push(publisher_id);

            });
        } else {
            log.info("Publisher already set for", publisher_id);
        }
    };

    that.addExternalOutput = function (publisher_id, url, callback) {
        if (publishers[publisher_id] !== undefined) {
            log.info("Adding ExternalOutput to " + publisher_id + " url " + url);

            var args = [publisher_id, url];

            amqper.callRpc(getErizoQueue(publisher_id), "addExternalOutput", args, undefined);

            // Track external outputs
            externalOutputs[url] = publisher_id;

            // Track publisher locally
            // publishers[publisher_id] = publisher_id;
            // subscribers[publisher_id] = [];
            callback('success');
        } else {
            callback('error');
        }

    };

    that.removeExternalOutput = function (url, callback) {
        var publisher_id = externalOutputs[url];

        if (publisher_id !== undefined && publishers[publisher_id] != undefined) {
            log.info("Stopping ExternalOutput: url " + url);

            var args = [publisher_id, url];
            amqper.callRpc(getErizoQueue(publisher_id), "removeExternalOutput", args, undefined);

            // Remove track
            delete externalOutputs[url];
            callback(true);
        } else {
            callback(null, 'This stream is not being recorded');
        }
    };

    that.processSignaling = function (streamId, peerId, msg) {

        if (publishers[streamId] !== undefined) {

//            log.info("Sending signaling mess to erizoJS of st ", streamId, ' of peer ', peerId);

            var args = [streamId, peerId, msg];

            amqper.callRpc(getErizoQueue(streamId), "processSignaling", args, {});

        }
    };

    /*
     * Adds a publisher to the room. This creates a new OneToManyProcessor
     * and a new WebRtcConnection. This WebRtcConnection will be the publisher
     * of the OneToManyProcessor.
     */
    that.addPublisher = function (publisher_id, options, callback, retries) {
        if (retries === undefined)
            retries = 0;

        if (publishers[publisher_id] === undefined) {

            log.info("Adding publisher peer_id ", publisher_id, "options", options);;

            // We create a new ErizoJS with the publisher_id.
            getErizoJS(function(erizo_id) {

                if (erizo_id === 'timeout') {
                    log.error("Cannot contact ErizoAgent to add Publisher -- timeout");
                    callback('timeout-agent');
                    return;
                }
            	log.debug("ErizoJS id:", erizo_id, "assigned for publisher", publisher_id);
                // Track publisher locally

                // then we call its addPublisher method.
                var args = [publisher_id, options];
                publishers[publisher_id] = erizo_id;
                subscribers[publisher_id] = [];

                amqper.callRpc(getErizoQueue(publisher_id), "addPublisher", args, {callback: function (data){
                    if (data === 'timeout'){
                        if (retries < MAX_ERIZOJS_RETRIES){
                            publishers[publisher_id] = undefined;
                            retries++;
                            log.warn("ErizoJS timed out, trying again to publish", publisher_id, "number of tries", retries);
                            that.addPublisher(publisher_id, options,callback, retries);
                            return;
                        }
                        log.error("Can not contact ErizoJS", publisher_id , " failed add Publisher -- timeout");
                        //TODO: Check what happens in ErizoJS, should have an unused publisher
                        var index = erizos[publishers[publisher_id]].publishers.indexOf(publisher_id);
                        erizos[publishers[publisher_id]].publishers.splice(index, 1);
                        callback('timeout-erizojs');
                        return;
                    }else{
                        callback(data);
                    }
                }});

                erizos[erizo_id].publishers.push(publisher_id);
            });

        } else {
            log.warn("Publisher already set for", publisher_id);
        }
    };

    /*
     * Adds a subscriber to the room. This creates a new WebRtcConnection.
     * This WebRtcConnection will be added to the subscribers list of the
     * OneToManyProcessor.
     */
    that.addSubscriber = function (subscriber_id, publisher_id, options, callback, retries) {
        if (subscriber_id === null){
          callback("Error: null subscriber_id");
          return;
        }
        if (retries === undefined)
            retries = 0;

        if (publishers[publisher_id] !== undefined && subscribers[publisher_id].indexOf(subscriber_id) === -1) {
            log.info("Adding subscriber ", subscriber_id, ' to publisher ', publisher_id, "options", options);

//            if (true){

                if (options.audio === undefined) options.audio = true;
                if (options.video === undefined) options.video = true;

                var args = [subscriber_id, publisher_id, options];
                //TODO: Potential problem here if erizoJS is not reachable
                amqper.callRpc(getErizoQueue(publisher_id, undefined), "addSubscriber", args, {callback: function (data){
                    if (data === 'timeout'){
                        if (retries < MAX_ERIZOJS_RETRIES){
                            retries++;
                            log.warn("ErizoJS timed out, trying again to subscribe to ", publisher_id, "from", subscriber_id, "number of tries", retries);
                            that.addSubscriber(subscriber_id, publisher_id, options, callback, retries);
                            return;
                        }
                        log.error("Can not contact to ErizoJS", publisher_id , " failed add Subscriber -- timeout");
                        callback('timeout');
                        return;
                    }else if (data === 'initializing'){
                        subscribers[publisher_id].push(subscriber_id);
                    }
                    callback(data);
                }});

/*            }else{ // Prototype for erizo_trees
                shouldAddSurrogate (publisher_id, subscriber_id, options, function(new_id){
                    log.info("Surrogate ?", new_id);

                    if (options.audio === undefined) options.audio = true;
                    if (options.video === undefined) options.video = true;

                    var args = [subscriber_id, publisher_id, options];

                    subscribers[publisher_id].push({id:subscriber_id, surrogate:new_id});
                    amqper.callRpc(getErizoQueue(publisher_id, subscriber_id), "addSubscriber", args, {callback: callback});
                    // Track subscriber locally
                });

            }
            */
        }
    };

    /*
     * Removes a publisher from the room. This also deletes the associated OneToManyProcessor.
     */
    that.removePublisher = function (publisher_id) {

        if (subscribers[publisher_id] !== undefined && publishers[publisher_id]!== undefined) {
            log.info("Removing publisher", publisher_id);

            var args = [publisher_id];
            amqper.callRpc(getErizoQueue(publisher_id), "removePublisher", args, undefined);

            // Remove tracks
            // TODO: Remove all surrogates
            var index = erizos[publishers[publisher_id]].publishers.indexOf(publisher_id);
            erizos[publishers[publisher_id]].publishers.splice(index, 1);

            delete subscribers[publisher_id];
            delete publishers[publisher_id];
            log.info('Removed muxer', publisher_id, ' muxers left ', Object.keys(publishers).length );
        }
    };

    /*
     * Removes a subscriber from the room. This also removes it from the associated OneToManyProcessor.
     */
    that.removeSubscriber = function (subscriber_id, publisher_id) {

        var index = subscribers[publisher_id].indexOf(subscriber_id);
        if (index !== -1) {
            log.info('Removing subscriber ', subscriber_id, 'to muxer ', publisher_id);

            var args = [subscriber_id, publisher_id];
            amqper.callRpc(getErizoQueue(publisher_id), "removeSubscriber", args, undefined);

            subscribers[publisher_id].splice(index, 1);
        }
    };

    /*
     * Removes all the subscribers related with a client.
     */
    that.removeSubscriptions = function (subscriber_id) {

        var publisher_id, index;

        log.info('Removing subscriptions of ', subscriber_id);

        for (publisher_id in subscribers) {
            if (subscribers.hasOwnProperty(publisher_id)) {
                index = subscribers[publisher_id].indexOf(subscriber_id);
                if (index !== -1) {
                    log.debug('Removing subscriber ', subscriber_id, 'from muxer ', publisher_id);

                    var args = [subscriber_id, publisher_id];
            		amqper.callRpc(getErizoQueue(publisher_id), "removeSubscriber", args, undefined);

            		// Remove tracks
                    subscribers[publisher_id].splice(index, 1);
                }
            }
        }
    };

    return that;
};
<|endoftext|>


<commit_before>import React from 'react'
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

import style from './style.css';
import { Input, Search } from 'semantic-ui-react'

function searchBar(props) {
  const handleKeyUp = async (e, { value }) => {
    console.log(value);
    props.data.refetch({
      query: value,
    });
  }

  let results = [];
  if (props.data.services)
    results = props.data.services.map( s => ({ title: s.name }) );

  return (
    <div className={`${props.className}`}>
      <Search
        loading={props.data.loading}
        onResultSelect={() => {}}
        onSearchChange={handleKeyUp}
        results={results}
        className={style.search}
      />

  );
}

const ServiceSearchQuery = gql`
  query ServiceSearchQuery($query: String) {
    services(query: $query) {
      id
      name
    }
  }
`;

export default (graphql(ServiceSearchQuery)(searchBar));
<commit_msg>service search with results<commit_after>import React from 'react';
import { Redirect } from 'react-router-dom';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

import style from './style.css';
import { Input, Search } from 'semantic-ui-react'

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      redirectTo: null,
    };
  }

  handleKeyUp = (e, { value }) => {
    this.props.data.refetch({
      query: value,
    });
  }

  handleResultSelect = (e, { result }) => {
    this.setState({
      redirectTo: `/services?q=${result.title}`
    });
  }

  render() {
    if (this.state.redirectTo)
      return (
        <Redirect push to={this.state.redirectTo} />
      );

    let results = [];
    if (this.props.data.services)
      results = this.props.data.services.map( s => ({ title: s.name }) );

    return (
      <div className={`${this.props.className}`}>
        <Search
          loading={this.props.data.loading}
          onResultSelect={this.handleResultSelect}
          onSearchChange={this.handleKeyUp}
          results={results}
          className={style.search}
        />

    );
  }
}

const ServiceSearchQuery = gql`
  query ServiceSearchQuery($query: String) {
    services(query: $query) {
      id
      name
    }
  }
`;

export default (graphql(ServiceSearchQuery)(SearchBar));
<|endoftext|>


<commit_before>print = function(o) {
    console.log(o);
    if (window.dump) {
      window.dump(o + '\n');
    }
}

function formatLine(name, t) {
  print("[PERF]," + name + "," + t);
}

function printPerfTiming() {
  print("[PERF] perf block start")
  formatLine("testcase", window.location);
  formatLine("title", document.title.replace(/,/g, ","));
  formatLine("navigationStart", performance.timing.navigationStart);
  formatLine("unloadEventStart", performance.timing.unloadEventStart);
  formatLine("unloadEventEnd", performance.timing.unloadEventEnd);
  formatLine("redirectStart", performance.timing.redirectStart);
  formatLine("redirectEnd", performance.timing.redirectEnd);
  formatLine("fetchStart", performance.timing.fetchStart);
  formatLine("domainLookupStart", performance.timing.domainLookupStart);
  formatLine("domainLookupEnd", performance.timing.domainLookupEnd);
  formatLine("connectStart", performance.timing.connectStart);
  formatLine("connectEnd", performance.timing.connectEnd);
  formatLine("secureConnectionStart", performance.timing.secureConnectionStart);
  formatLine("requestStart", performance.timing.requestStart);
  formatLine("responseStart", performance.timing.responseStart);
  formatLine("responseEnd", performance.timing.responseEnd);
  formatLine("domLoading", performance.timing.domLoading);
  formatLine("domInteractive", performance.timing.domInteractive);
  formatLine("domContentLoadedEventStart", performance.timing.domContentLoadedEventStart);
  formatLine("domContentLoadedEventEnd", performance.timing.domContentLoadedEventEnd);
  formatLine("domComplete", performance.timing.domComplete);
  formatLine("loadEventStart", performance.timing.loadEventStart);
  formatLine("loadEventEnd", performance.timing.loadEventEnd);
  print("[PERF] perf block end")
}

if (document.readyState === "complete") {
    printPerfTiming()
    window.close();
} else {
    window.addEventListener('load', printPerfTiming);
    var timeout = 5;
    window.setTimeout(function() {
        print("[PERF] Timeout after " + timeout + " min. Force stop");
        printPerfTiming();
        window.close();
    }, timeout * 60 * 1000)
}
<commit_msg>Capture loadEventEnd in test-perf.<commit_after>print = function(o) {
    console.log(o);
    if (window.dump) {
      window.dump(o + '\n');
    }
}

function formatLine(name, t) {
  print("[PERF]," + name + "," + t);
}

function printPerfTiming() {
  print("[PERF] perf block start")
  formatLine("testcase", window.location);
  formatLine("title", document.title.replace(/,/g, ","));
  formatLine("navigationStart", performance.timing.navigationStart);
  formatLine("unloadEventStart", performance.timing.unloadEventStart);
  formatLine("unloadEventEnd", performance.timing.unloadEventEnd);
  formatLine("redirectStart", performance.timing.redirectStart);
  formatLine("redirectEnd", performance.timing.redirectEnd);
  formatLine("fetchStart", performance.timing.fetchStart);
  formatLine("domainLookupStart", performance.timing.domainLookupStart);
  formatLine("domainLookupEnd", performance.timing.domainLookupEnd);
  formatLine("connectStart", performance.timing.connectStart);
  formatLine("connectEnd", performance.timing.connectEnd);
  formatLine("secureConnectionStart", performance.timing.secureConnectionStart);
  formatLine("requestStart", performance.timing.requestStart);
  formatLine("responseStart", performance.timing.responseStart);
  formatLine("responseEnd", performance.timing.responseEnd);
  formatLine("domLoading", performance.timing.domLoading);
  formatLine("domInteractive", performance.timing.domInteractive);
  formatLine("domContentLoadedEventStart", performance.timing.domContentLoadedEventStart);
  formatLine("domContentLoadedEventEnd", performance.timing.domContentLoadedEventEnd);
  formatLine("domComplete", performance.timing.domComplete);
  formatLine("loadEventStart", performance.timing.loadEventStart);
  formatLine("loadEventEnd", performance.timing.loadEventEnd);
  print("[PERF] perf block end")
}

if (document.readyState === "complete") {
    printPerfTiming()
    window.close();
} else {
    window.addEventListener('load', function () {
	window.setTimeout(printPerfTiming, 0);
    });
    var timeout = 5;
    window.setTimeout(function() {
        print("[PERF] Timeout after " + timeout + " min. Force stop");
        printPerfTiming();
        window.close();
    }, timeout * 60 * 1000)
}
<|endoftext|>


<commit_before>// jQuery
var $renderPort = $('#renderPort');

// SocketIO
var socket = io();
var connected = false;

// Phone variables
var vX = 0, vY = 0, vZ = 0,
  sX = 0, sY = 0, sZ = 0,
  alpha = 0, beta = 0, gamma = 0;

// 3D Scene variables
var scene, camera, renderer, cube;
var ambientlight, hemispherelight, dirlight, pointlight;

// Setup 3D scene
function setupScene() {
  // Scene object
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, $renderPort.width()/$renderPort.height(), 0.1, 10000);

  // Create renderer
  renderer = new THREE.WebGLRenderer( { alpha: true } );
  renderer.setSize( $renderPort.width(), $renderPort.height());

  // Light
  ambientlight = new THREE.AmbientLight( 0x404040 );
  scene.add( ambientlight );

  dirLight = new THREE.DirectionalLight(0xffffff, 1);
  dirLight.position.set(400, 500, 50);
  scene.add(dirLight);

  hemispherelight = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  hemispherelight.position.set(0, 500, 0);
  hemispherelight.color.setHSL( 0.6, 1, 0.6 );
  hemispherelight.groundColor.setHSL( 0.095, 1, 0.75 );
  scene.add( hemispherelight );

  // Add renderer
  $renderPort.append( renderer.domElement );

  // Cam position
  camera.position.z = 900;
  camera.position.y = 0;
  camera.position.x = 0;
  camera.up = new THREE.Vector3( 0, 1, 0 );

  scene.add( new THREE.AxisHelper( 600 ));

  // Add cube
  addCube();

  camera.lookAt( cube.position );
  scene.add( camera );
}

function addCube() {
  var geometry = new THREE.BoxGeometry( 300,300,300 );
  var material = new THREE.MeshPhongMaterial( { color: 0x47d1d1 });
  cube = new THREE.Mesh( geometry, material );
  cube.castShadow = true;
  scene.add( cube );
}

var render = function () {
  // cube.rotation.x += gamma*2;
  cube.rotation.y += gamma*2;
  cube.rotation.z += beta*2;

  requestAnimationFrame( render );
  renderer.render( scene, camera );
}

window.addEventListener('resize', function() {
  renderer.setSize( $renderPort.width(), $renderPort.height());
  camera.aspect = $renderPort.width()/$renderPort.height();
  camera.updateProjectionMatrix();
});

// Kickstart
setupScene();
render();

// Check connection
socket.on('connection', function() {
  connected = true;
});

// If client has accelerometer and gyro data
if (window.DeviceMotionEvent) {
  window.addEventListener('devicemotion', function (data) {
    var acc = data.accelerationIncludingGravity;
    var vel = { vX: vX, vY: vY, vZ: vZ };
    var disp = { sX: sX, sY: sY, sZ: sZ };

    var phoneData = {
      accelerometer: acc,
      velocity: vel,
      displacement: disp,
      rotationRate: data.rotationRate,
      interval: data.interval
    };

    // Tell server
    socket.emit('phone-data', phoneData);
  }, false);
}

socket.on('phone-data', function (data) {
    vX = data.velocity.vX;
    vY = data.velocity.vY;
    vZ = data.velocity.vZ;

    sX = data.displacement.sX;
    sY = data.displacement.sY;
    sZ = data.displacement.sZ;

  // Check and update angle
  if (aboveAbsThreshold(data.rotationRate.alpha, 0.1) || aboveAbsThreshold(data.rotationRate.beta, 0.1) || aboveAbsThreshold(data.rotationRate.gamma, 0.1)) {
    var scalar = 100;
    alpha = data.rotationRate.alpha*data.interval/scalar;
    beta = data.rotationRate.beta*data.interval/scalar;
    gamma = data.rotationRate.gamma*data.interval/scalar;
  }

});
function aboveAbsThreshold(input, threshold) {
  return Math.abs(input) > threshold ? true : false;
}<commit_msg>Fixing axes.<commit_after>// jQuery
var $renderPort = $('#renderPort');

// SocketIO
var socket = io();
var connected = false;

// Phone variables
var vX = 0, vY = 0, vZ = 0,
  sX = 0, sY = 0, sZ = 0,
  alpha = 0, beta = 0, gamma = 0;

// 3D Scene variables
var scene, camera, renderer, cube;
var ambientlight, hemispherelight, dirlight, pointlight;

// Setup 3D scene
function setupScene() {
  // Scene object
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, $renderPort.width()/$renderPort.height(), 0.1, 10000);

  // Create renderer
  renderer = new THREE.WebGLRenderer( { alpha: true } );
  renderer.setSize( $renderPort.width(), $renderPort.height());

  // Light
  ambientlight = new THREE.AmbientLight( 0x404040 );
  scene.add( ambientlight );

  dirLight = new THREE.DirectionalLight(0xffffff, 1);
  dirLight.position.set(400, 500, 50);
  scene.add(dirLight);

  hemispherelight = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  hemispherelight.position.set(0, 500, 0);
  hemispherelight.color.setHSL( 0.6, 1, 0.6 );
  hemispherelight.groundColor.setHSL( 0.095, 1, 0.75 );
  scene.add( hemispherelight );

  // Add renderer
  $renderPort.append( renderer.domElement );

  // Cam position
  camera.position.z = 900;
  camera.position.y = 0;
  camera.position.x = 0;
  camera.up = new THREE.Vector3( 0, 1, 0 );

  scene.add( new THREE.AxisHelper( 600 ));

  // Add cube
  addCube();

  camera.lookAt( cube.position );
  scene.add( camera );
}

function addCube() {
  var geometry = new THREE.BoxGeometry( 300,300,300 );
  var material = new THREE.MeshPhongMaterial( { color: 0x47d1d1 });
  cube = new THREE.Mesh( geometry, material );
  cube.castShadow = true;
  scene.add( cube );
}

var render = function () {
  // cube.rotation.x += gamma*2;
  cube.rotation.y += gamma*2;
  cube.rotation.z -= beta*2;

  requestAnimationFrame( render );
  renderer.render( scene, camera );
}

window.addEventListener('resize', function() {
  renderer.setSize( $renderPort.width(), $renderPort.height());
  camera.aspect = $renderPort.width()/$renderPort.height();
  camera.updateProjectionMatrix();
});

// Kickstart
setupScene();
render();

// Check connection
socket.on('connection', function() {
  connected = true;
});

// If client has accelerometer and gyro data
if (window.DeviceMotionEvent) {
  window.addEventListener('devicemotion', function (data) {
    var acc = data.accelerationIncludingGravity;
    var vel = { vX: vX, vY: vY, vZ: vZ };
    var disp = { sX: sX, sY: sY, sZ: sZ };

    var phoneData = {
      accelerometer: acc,
      velocity: vel,
      displacement: disp,
      rotationRate: data.rotationRate,
      interval: data.interval
    };

    // Tell server
    socket.emit('phone-data', phoneData);
  }, false);
}

socket.on('phone-data', function (data) {
    vX = data.velocity.vX;
    vY = data.velocity.vY;
    vZ = data.velocity.vZ;

    sX = data.displacement.sX;
    sY = data.displacement.sY;
    sZ = data.displacement.sZ;

  // Check and update angle
  if (aboveAbsThreshold(data.rotationRate.alpha, 0.1) || aboveAbsThreshold(data.rotationRate.beta, 0.1) || aboveAbsThreshold(data.rotationRate.gamma, 0.1)) {
    var scalar = 100;
    alpha = data.rotationRate.alpha*data.interval/scalar;
    beta = data.rotationRate.beta*data.interval/scalar;
    gamma = data.rotationRate.gamma*data.interval/scalar;
  }

});
function aboveAbsThreshold(input, threshold) {
  return Math.abs(input) > threshold ? true : false;
}<|endoftext|>


<commit_before>/*
  backgrid-text-cell
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  Licensed under the MIT @license.
*/
(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['underscore', 'backgrid'], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory(require("underscore"),
                             require("backgrid"));
  } else {
    // Browser globals
    factory(root._, root.Backgrid);
  }

}(this, function (_, Backgrid)  {

  /**
     Renders a form with a text area and a save button in a modal dialog.

     @class Backgrid.Extension.TextareaEditor
     @extends Backgrid.CellEditor
  */
  var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({

    /** @property */
    tagName: "div",

    /** @property */
    className: "modal fade",

    /** @property {function(Object, ?Object=): string} template */
    template: function (data) {
      return '

<form>
<button type="button" class="close" data-dismiss="modal">×</button>
' + data.column.get("label")  + '

<textarea cols="' + data.cols + '" rows="' + data.rows + '">' + data.content + '</textarea>

<input class="btn btn-primary" type="submit" value="Save"/>
</form>

';
    },

    /** @property */
    cols: 80,

    /** @property */
    rows: 10,

    /** @property */
    events: {
      "keydown textarea": "clearError",
      "submit": "saveOrCancel",
      "hide.bs.modal": "saveOrCancel",
      "hidden.bs.modal": "close",
      "shown.bs.modal": "focus"
    },

    /**
       @property {Object} modalOptions The options passed to Bootstrap's modal
       plugin.
    */
    modalOptions: {
      backdrop: false
    },

    /**
       Renders a modal form dialog with a textarea, submit button and a close button.
    */
    render: function () {
      this.$el.html($(this.template({
        column: this.column,
        cols: this.cols,
        rows: this.rows,
        content: this.formatter.fromRaw(this.model.get(this.column.get("name")))
      })));

      this.delegateEvents();

      this.$el.modal(this.modalOptions);

      return this;
    },

    /**
       Event handler. Saves the text in the text area to the model when
       submitting. When cancelling, if the text area is dirty, a confirmation
       dialog will pop up. If the user clicks confirm, the text will be saved to
       the model.

       Triggers a Backbone `backgrid:error` event from the model along with the
       model, column and the existing value as the parameters if the value
       cannot be converted.

       @param {Event} e
    */
    saveOrCancel: function (e) {
      if (e && e.type == "submit") {
        e.preventDefault();
        e.stopPropagation();
      }

      var model = this.model;
      var column = this.column;
      var val = this.$el.find("textarea").val();
      var newValue = this.formatter.toRaw(val);

      if (_.isUndefined(newValue)) {
        model.trigger("backgrid:error", model, column, val);

        if (e) {
          e.preventDefault();
          e.stopPropagation();
        }
      }
      else if (!e || e.type == "submit" ||
               (e.type == "hide" &&
                newValue !== (this.model.get(this.column.get("name")) || '').replace(/\r/g, '') &&
                confirm("Would you like to save your changes?"))) {

        model.set(column.get("name"), newValue);
        this.$el.modal("hide");
      }
      else if (e.type != "hide") this.$el.modal("hide");
    },

    /**
       Clears the error class on the parent cell.
     */
    clearError: _.debounce(function () {
      if (!_.isUndefined(this.formatter.toRaw(this.$el.find("textarea").val()))) {
        this.$el.parent().removeClass("error");
      }
    }, 150),

    /**
       Triggers a `backgrid:edited` event along with the cell editor as the
       parameter after the modal is hidden.

       @param {Event} e
    */
    close: function (e) {
      var model = this.model;
      model.trigger("backgrid:edited", model, this.column,
                    new Backgrid.Command(e));
    },

    /**
       Focuses the textarea when the modal is shown.
    */
    focus: function () {
      this.$el.find("textarea").focus();
    }

  });

  /**
     TextCell is a string cell type that renders a form with a text area in a
     modal dialog instead of an input box editor. It is best suited for entering
     a large body of text.

     @class Backgrid.Extension.TextCell
     @extends Backgrid.StringCell
  */
  Backgrid.Extension.TextCell = Backgrid.StringCell.extend({

    /** @property */
    className: "text-cell",

    /** @property  */
    editor: TextareaEditor

  });

}));
<commit_msg>lodash + global.Backgrid<commit_after>/*
  backgrid-text-cell
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  Licensed under the MIT @license.
*/
(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['underscore', 'backgrid'], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    var Backgrid = global.Backgrid || require("backgrid");
    module.exports = factory(require("lodash"),
                             Backgrid);
  } else {
    // Browser globals
    factory(root._, root.Backgrid);
  }

}(this, function (_, Backgrid)  {

  /**
     Renders a form with a text area and a save button in a modal dialog.

     @class Backgrid.Extension.TextareaEditor
     @extends Backgrid.CellEditor
  */
  var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({

    /** @property */
    tagName: "div",

    /** @property */
    className: "modal fade",

    /** @property {function(Object, ?Object=): string} template */
    template: function (data) {
      return '

<form>
<button type="button" class="close" data-dismiss="modal">×</button>
' + data.column.get("label")  + '

<textarea cols="' + data.cols + '" rows="' + data.rows + '">' + data.content + '</textarea>

<input class="btn btn-primary" type="submit" value="Save"/>
</form>

';
    },

    /** @property */
    cols: 80,

    /** @property */
    rows: 10,

    /** @property */
    events: {
      "keydown textarea": "clearError",
      "submit": "saveOrCancel",
      "hide.bs.modal": "saveOrCancel",
      "hidden.bs.modal": "close",
      "shown.bs.modal": "focus"
    },

    /**
       @property {Object} modalOptions The options passed to Bootstrap's modal
       plugin.
    */
    modalOptions: {
      backdrop: false
    },

    /**
       Renders a modal form dialog with a textarea, submit button and a close button.
    */
    render: function () {
      this.$el.html($(this.template({
        column: this.column,
        cols: this.cols,
        rows: this.rows,
        content: this.formatter.fromRaw(this.model.get(this.column.get("name")))
      })));

      this.delegateEvents();

      this.$el.modal(this.modalOptions);

      return this;
    },

    /**
       Event handler. Saves the text in the text area to the model when
       submitting. When cancelling, if the text area is dirty, a confirmation
       dialog will pop up. If the user clicks confirm, the text will be saved to
       the model.

       Triggers a Backbone `backgrid:error` event from the model along with the
       model, column and the existing value as the parameters if the value
       cannot be converted.

       @param {Event} e
    */
    saveOrCancel: function (e) {
      if (e && e.type == "submit") {
        e.preventDefault();
        e.stopPropagation();
      }

      var model = this.model;
      var column = this.column;
      var val = this.$el.find("textarea").val();
      var newValue = this.formatter.toRaw(val);

      if (_.isUndefined(newValue)) {
        model.trigger("backgrid:error", model, column, val);

        if (e) {
          e.preventDefault();
          e.stopPropagation();
        }
      }
      else if (!e || e.type == "submit" ||
               (e.type == "hide" &&
                newValue !== (this.model.get(this.column.get("name")) || '').replace(/\r/g, '') &&
                confirm("Would you like to save your changes?"))) {

        model.set(column.get("name"), newValue);
        this.$el.modal("hide");
      }
      else if (e.type != "hide") this.$el.modal("hide");
    },

    /**
       Clears the error class on the parent cell.
     */
    clearError: _.debounce(function () {
      if (!_.isUndefined(this.formatter.toRaw(this.$el.find("textarea").val()))) {
        this.$el.parent().removeClass("error");
      }
    }, 150),

    /**
       Triggers a `backgrid:edited` event along with the cell editor as the
       parameter after the modal is hidden.

       @param {Event} e
    */
    close: function (e) {
      var model = this.model;
      model.trigger("backgrid:edited", model, this.column,
                    new Backgrid.Command(e));
    },

    /**
       Focuses the textarea when the modal is shown.
    */
    focus: function () {
      this.$el.find("textarea").focus();
    }

  });

  /**
     TextCell is a string cell type that renders a form with a text area in a
     modal dialog instead of an input box editor. It is best suited for entering
     a large body of text.

     @class Backgrid.Extension.TextCell
     @extends Backgrid.StringCell
  */
  Backgrid.Extension.TextCell = Backgrid.StringCell.extend({

    /** @property */
    className: "text-cell",

    /** @property  */
    editor: TextareaEditor

  });

}));
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

/**
 * This file contains the wrapper function for network manager
 */

var config = process.mainModule.exports['config'];
var orch = require('../orchestration/orchestration.api');

var orchModels = orch.getOrchestrationModels();

var openstackNetworkApi = require('../orchestration/plugins/openstack/glance.api');
var cloudstackNetworkApi  =
    require('../orchestration/plugins/cloudstack/cloudstack.api');
var noOrchestrationNetworkApi  =
    require('../orchestration/plugins/no-orch/noOrchestration.api');
var vCenterNetworkApi =
    require('../orchestration/plugins/vcenter/vcenter.common');

var getNetworkMethod = {
    'vcenter': vCenterNetworkApi,
    'openstack': openstackNetworkApi,
    'cloudstack' : cloudstackNetworkApi,
    'none'       : noOrchestrationNetworkApi
}

function apiGet (reqUrl, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].get(reqUrl, req, function(err, data) {
        callback(err, data);
    });
}

function apiPost (reqUrl, postData, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].post(reqUrl, postData, req, function(err, data) {
        callback(err, data);
    });
}

function apiPut (reqUrl, putData, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].put(reqUrl, putData, req, function(err, data) {
        callback(err, data);
    });
}

function apiDelete (reqUrl, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].delete(reqUrl, req, function(err, data) {
        callback(err, data);
    });
}

function createNetworkPort (req, postData, project, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    req.cookies.project = project;
    getNetworkMethod[loggedInOrchMode].createNetworkPort(req, postData, callback);
}

function deleteNetworkPort (req, portId, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].deleteNetworkPort(req, portId, callback);
}

function updateRouter (req, postData, portId,  callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].updateRouter(req, postData, portId, callback);
}

exports.apiGet = apiGet;
exports.apiPost = apiPost;
exports.apiPut = apiPut;
exports.apiDelete = apiDelete;
exports.createNetworkPort = createNetworkPort;
exports.deleteNetworkPort = deleteNetworkPort;
exports.updateRouter =  updateRouter;
<commit_msg>Wrongly imported glance module instead of neutron module and corrected it<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

/**
 * This file contains the wrapper function for network manager
 */

var config = process.mainModule.exports['config'];
var orch = require('../orchestration/orchestration.api');

var orchModels = orch.getOrchestrationModels();

var openstackNetworkApi = require('../orchestration/plugins/openstack/neutron.api');
var cloudstackNetworkApi  =
    require('../orchestration/plugins/cloudstack/cloudstack.api');
var noOrchestrationNetworkApi  =
    require('../orchestration/plugins/no-orch/noOrchestration.api');
var vCenterNetworkApi =
    require('../orchestration/plugins/vcenter/vcenter.common');

var getNetworkMethod = {
    'vcenter': vCenterNetworkApi,
    'openstack': openstackNetworkApi,
    'cloudstack' : cloudstackNetworkApi,
    'none'       : noOrchestrationNetworkApi
}

function apiGet (reqUrl, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].get(reqUrl, req, function(err, data) {
        callback(err, data);
    });
}

function apiPost (reqUrl, postData, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].post(reqUrl, postData, req, function(err, data) {
        callback(err, data);
    });
}

function apiPut (reqUrl, putData, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].put(reqUrl, putData, req, function(err, data) {
        callback(err, data);
    });
}

function apiDelete (reqUrl, req, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].delete(reqUrl, req, function(err, data) {
        callback(err, data);
    });
}

function createNetworkPort (req, postData, project, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    req.cookies.project = project;
    getNetworkMethod[loggedInOrchMode].createNetworkPort(req, postData, callback);
}

function deleteNetworkPort (req, portId, callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].deleteNetworkPort(req, portId, callback);
}

function updateRouter (req, postData, portId,  callback)
{
    var loggedInOrchMode = orch.getLoggedInOrchestrationMode(req);
    getNetworkMethod[loggedInOrchMode].updateRouter(req, postData, portId, callback);
}

exports.apiGet = apiGet;
exports.apiPost = apiPost;
exports.apiPut = apiPut;
exports.apiDelete = apiDelete;
exports.createNetworkPort = createNetworkPort;
exports.deleteNetworkPort = deleteNetworkPort;
exports.updateRouter =  updateRouter;
<|endoftext|>


<commit_before>function targetValue(e) {
  return e.target.value
}

function turnOn(id) {
  return $.ajaxAsObservable({ url: "/api/on?id=" + id, cache: false })
}

function turnOff(id) {
  return $.ajaxAsObservable({ url: "/api/off?id=" + id, cache: false })
}

function updateSensorData(data) {
  $('.temperature.wc').text(data.temp1)
  $('.humidity.wc').text(data.humidity1)

  $('.temperature.outside').text(data.temp2)
  $('.humidity.outside').text(data.humidity2)
}

$(function() {
  $('button.switch.on').clickAsObservable().select(targetValue).subscribe(function(id) {
    turnOn(id).subscribe(function(x) {  console.log("Turned on " + id) })
  })

  $('button.switch.off').clickAsObservable().select(targetValue).subscribe(function(id) {
    turnOff(id).subscribe(function(x) {  console.log("Turned off " + id) })
  })

  var connection = new WebSocket("ws://"+window.location.hostname+":9001")
  connection.onmessage = function (event) {
    console.log(event)
    updateSensorData(event.data)
  }
})<commit_msg>parse json<commit_after>function targetValue(e) {
  return e.target.value
}

function turnOn(id) {
  return $.ajaxAsObservable({ url: "/api/on?id=" + id, cache: false })
}

function turnOff(id) {
  return $.ajaxAsObservable({ url: "/api/off?id=" + id, cache: false })
}

function updateSensorData(data) {
  $('.temperature.wc').text(data.temp1)
  $('.humidity.wc').text(data.humidity1)

  $('.temperature.outside').text(data.temp2)
  $('.humidity.outside').text(data.humidity2)
}

$(function() {
  $('button.switch.on').clickAsObservable().select(targetValue).subscribe(function(id) {
    turnOn(id).subscribe(function(x) {  console.log("Turned on " + id) })
  })

  $('button.switch.off').clickAsObservable().select(targetValue).subscribe(function(id) {
    turnOff(id).subscribe(function(x) {  console.log("Turned off " + id) })
  })

  var connection = new WebSocket("ws://"+window.location.hostname+":9001")
  connection.onmessage = function (event) {
    updateSensorData(JSON.parse(event.data))
  }
})<|endoftext|>


<commit_before>// Set the RequireJS configuration
require.config({
  paths : {
    "text" : "libs/text",
    "jquery" : "libs/jquery",
    "hotkeys" : "libs/jquery.hotkeys",
    "terminal" : "libs/terminal/terminal",
    "underscore" : "libs/underscore",
    "backbone" : "libs/backbone",
    "handlebars" : "libs/handlebars.runtime",
    "compiledTemplates" : "libs/compiled_handlebars",
    "crypto" : "libs/Crypto_AES",
    "pouch" : "libs/pouch.alpha",
    "backbone_pouchdb" : "libs/backbone-pouchdb",
    "backbone_couchdb" : "libs/backbone-couchdb",
    "bootstrap" : "bootstrap/js/bootstrap",
    "bootstrap-transition" : "bootstrap/js/bootstrap-transition",
    "bootstrap-alert" : "bootstrap/js/bootstrap-alert",
    "bootstrap-modal" : "bootstrap/js/bootstrap-modal",
    "bootstrap-dropdown" : "bootstrap/js/bootstrap-dropdown",
    "bootstrap-scrollspy" : "bootstrap/js/bootstrap-scrollspy",
    "bootstrap-tab" : "bootstrap/js/bootstrap-tab",
    "bootstrap-tooltip" : "bootstrap/js/bootstrap-tooltip",
    "bootstrap-popover" : "bootstrap/js/bootstrap-popover",
    "bootstrap-button" : "bootstrap/js/bootstrap-button",
    "bootstrap-collapse" : "bootstrap/js/bootstrap-collapse",
    "bootstrap-carousel" : "bootstrap/js/bootstrap-carousel",
    "bootstrap-typeahead" : "bootstrap/js/bootstrap-typeahead"
  },
  shim : {
    "underscore" : {
      exports : "_"
    },

    "jquery" : {
      exports : "$"
    },

    "bootstrap" :{
      deps : [ "jquery", "bootstrap-transition", "bootstrap-alert",
          "bootstrap-modal", "bootstrap-dropdown", "bootstrap-scrollspy",
          "bootstrap-tab", "bootstrap-tooltip", "bootstrap-popover",
          "bootstrap-button", "bootstrap-collapse", "bootstrap-carousel",
          "bootstrap-typeahead" ],
      exports : function($) {
        return $;
      }
    },

    "pouch" :{
      exports: "Pouch"
    },

    "backbone" : {
      deps : [ "underscore", "jquery", "compiledTemplates" ],
      exports : function(_, $) {
        return Backbone;
      }
    },
    "backbone_pouchdb" :{
      deps : ["backbone", "pouch", "backbone_couchdb"],
      exports : function(Backbone, Pouch, backbone_couchdb) {
        return Backbone;
      }
    },

    "backbone_couchdb" :{
      deps : ["backbone", "pouch"],
      exports : function(Backbone, Pouch) {
        return Backbone;
      }
    },

    "handlebars" : {
      deps : ["bootstrap"],
      exports : "Handlebars"
    },

    "crypto" : {
      exports : "CryptoJS"
    },

    "compiledTemplates" : {
      deps : [ "handlebars" ],
      exports : function(Handlebars) {
        return Handlebars;
      }
    },
    "terminal" : {
      exports : "Terminal"
    }

  }
});

// Initialization
require([
    "app/App",
    "app/AppView",
    "app/AppRouter",
    "corpus/Corpus",
    "data_list/DataList",
    "datum/Datum",
    "datum/Session",
    "user/User",
    "user/UserWelcomeView",
    "handlebars",
    "compiledTemplates",
    "backbone",
    "backbone_pouchdb",
    "libs/Utils"
], function(
    App,
    AppView,
    AppRouter,
    Corpus,
    DataList,
    Datum,
    Session,
    User,
    UserWelcomeView,
    Handlebars,
    compiledTemplates,
    Backbone,
    forcingpouchtoloadonbackboneearly
) {

  /**
   * This function is the only place that starts the app, notably the app view and app router.
   * It is called either by the main.js or by the UserWelcomeView.js
   */
  window.startApp = function(a, callback){
    window.app = a;

    // Create and display the AppView and its dependents
    window.appView = new AppView({model: a});
    window.appView.render();

    // Start the Router
    app.router = new AppRouter();
    Backbone.history.start();

    if(typeof callback == "function"){
      callback();
    }

  };
  /*
   * Start the pub sub hub
   */
  window.hub = {};
  Utils.makePublisher(window.hub);

  /*
   * Clear the app completely
   * TODO this doesnt work any more because each corpus is in a different pouch.
   */
//  Pouch.destroy('idb://db');
//  Pouch.destroy('idb://dbdefault');
//  Pouch.destroy('idb://dbsapir-firstcorpus');
//  localStorage.removeItem("appids");
//  localStorage.removeItem("corpusname");
//  ids.corpusid = "4C1A0D9F-D548-491D-AEE5-19028ED85F2B";
//  ids.sessionid = "1423B167-D728-4315-80DE-A10D28D8C4AE";
//  ids.datalistid = "1C1F1187-329F-4473-BBC9-3B15D01D6A11";

  // Load the App from localStorage
  var appjson = localStorage.getItem("appids");
  if (appjson) {
    Utils.debug("Loading app from localStorage");
    appjson = JSON.parse(appjson);
    a = new App();
    var corpusname = null;
    var couchConnection = null;
    if(localStorage.getItem("mostRecentCouchConnection")){
      corpusname = JSON.parse(localStorage.getItem("mostRecentCouchConnection")).corpusname;
      couchConnection = JSON.parse(localStorage.getItem("mostRecentCouchConnection"));
    }
    a.createAppBackboneObjects(corpusname ,function(){
      a.loadBackboneObjectsById(couchConnection, appjson, function(){
        window.startApp(a);
      });
    });
  } else {
    Utils.debug("Loading fresh app");
    $(".testcss").html("changing it dynamically");
    // Create a UserWelcomeView modal
    var welcomeUserView = new UserWelcomeView();
    welcomeUserView.render();
    $('#user-welcome-modal').modal("show");
  }

});
<commit_msg>dividing bootstrap dependants and bootstrap into two loads so that bootstrap will be loaded before its dependants, maybe this will fix the undefined is not a function errors<commit_after>// Set the RequireJS configuration
require.config({
  paths : {
    "text" : "libs/text",
    "jquery" : "libs/jquery",
    "hotkeys" : "libs/jquery.hotkeys",
    "terminal" : "libs/terminal/terminal",
    "underscore" : "libs/underscore",
    "backbone" : "libs/backbone",
    "handlebars" : "libs/handlebars.runtime",
    "compiledTemplates" : "libs/compiled_handlebars",
    "crypto" : "libs/Crypto_AES",
    "pouch" : "libs/pouch.alpha",
    "backbone_pouchdb" : "libs/backbone-pouchdb",
    "backbone_couchdb" : "libs/backbone-couchdb",
    "bootstrap" : "bootstrap/js/bootstrap",
    "bootstrap-transition" : "bootstrap/js/bootstrap-transition",
    "bootstrap-alert" : "bootstrap/js/bootstrap-alert",
    "bootstrap-modal" : "bootstrap/js/bootstrap-modal",
    "bootstrap-dropdown" : "bootstrap/js/bootstrap-dropdown",
    "bootstrap-scrollspy" : "bootstrap/js/bootstrap-scrollspy",
    "bootstrap-tab" : "bootstrap/js/bootstrap-tab",
    "bootstrap-tooltip" : "bootstrap/js/bootstrap-tooltip",
    "bootstrap-popover" : "bootstrap/js/bootstrap-popover",
    "bootstrap-button" : "bootstrap/js/bootstrap-button",
    "bootstrap-collapse" : "bootstrap/js/bootstrap-collapse",
    "bootstrap-carousel" : "bootstrap/js/bootstrap-carousel",
    "bootstrap-typeahead" : "bootstrap/js/bootstrap-typeahead"
  },
  shim : {
    "underscore" : {
      exports : "_"
    },

    "jquery" : {
      exports : "$"
    },

    "bootstrap" :{
      deps : [ "jquery" ],
      exports : function($) {
        return $;
      }
    },

    "bootstrap-typeahead" :{
      deps : [ "jquery", "bootstrap","bootstrap-transition", "bootstrap-alert",
          "bootstrap-modal", "bootstrap-dropdown", "bootstrap-scrollspy",
          "bootstrap-tab", "bootstrap-tooltip", "bootstrap-popover",
          "bootstrap-button", "bootstrap-collapse", "bootstrap-carousel"
           ],
      exports : function($) {
        return $;
      }
    },

    "pouch" :{
      exports: "Pouch"
    },

    "backbone" : {
      deps : [ "underscore", "jquery", "compiledTemplates" ],
      exports : function(_, $) {
        return Backbone;
      }
    },
    "backbone_pouchdb" :{
      deps : ["backbone", "pouch", "backbone_couchdb"],
      exports : function(Backbone, Pouch, backbone_couchdb) {
        return Backbone;
      }
    },

    "backbone_couchdb" :{
      deps : ["backbone", "pouch"],
      exports : function(Backbone, Pouch) {
        return Backbone;
      }
    },

    "handlebars" : {
      deps : ["bootstrap","jquery"],
      exports : "Handlebars"
    },

    "crypto" : {
      exports : "CryptoJS"
    },

    "compiledTemplates" : {
      deps : [ "handlebars" ],
      exports : function(Handlebars) {
        return Handlebars;
      }
    },
    "terminal" : {
      deps : ["bootstrap","jquery"],
      exports : "Terminal"
    }

  }
});

// Initialization
require([
    "app/App",
    "app/AppView",
    "app/AppRouter",
    "corpus/Corpus",
    "data_list/DataList",
    "datum/Datum",
    "datum/Session",
    "user/User",
    "user/UserWelcomeView",
    "handlebars",
    "compiledTemplates",
    "backbone",
    "backbone_pouchdb",
    "libs/Utils"
], function(
    App,
    AppView,
    AppRouter,
    Corpus,
    DataList,
    Datum,
    Session,
    User,
    UserWelcomeView,
    Handlebars,
    compiledTemplates,
    Backbone,
    forcingpouchtoloadonbackboneearly
) {

  /**
   * This function is the only place that starts the app, notably the app view and app router.
   * It is called either by the main.js or by the UserWelcomeView.js
   */
  window.startApp = function(a, callback){
    window.app = a;

    // Create and display the AppView and its dependents
    window.appView = new AppView({model: a});
    window.appView.render();

    // Start the Router
    app.router = new AppRouter();
    Backbone.history.start();

    if(typeof callback == "function"){
      callback();
    }

  };
  /*
   * Start the pub sub hub
   */
  window.hub = {};
  Utils.makePublisher(window.hub);

  /*
   * Clear the app completely
   * TODO this doesnt work any more because each corpus is in a different pouch.
   */
//  Pouch.destroy('idb://db');
//  Pouch.destroy('idb://dbdefault');
//  Pouch.destroy('idb://dbsapir-firstcorpus');
//  localStorage.removeItem("appids");
//  localStorage.removeItem("corpusname");
//  ids.corpusid = "4C1A0D9F-D548-491D-AEE5-19028ED85F2B";
//  ids.sessionid = "1423B167-D728-4315-80DE-A10D28D8C4AE";
//  ids.datalistid = "1C1F1187-329F-4473-BBC9-3B15D01D6A11";

  // Load the App from localStorage
  var appjson = localStorage.getItem("appids");
  if (appjson) {
    Utils.debug("Loading app from localStorage");
    appjson = JSON.parse(appjson);
    a = new App();
    var corpusname = null;
    var couchConnection = null;
    if(localStorage.getItem("mostRecentCouchConnection")){
      corpusname = JSON.parse(localStorage.getItem("mostRecentCouchConnection")).corpusname;
      couchConnection = JSON.parse(localStorage.getItem("mostRecentCouchConnection"));
    }
    a.createAppBackboneObjects(corpusname ,function(){
      a.loadBackboneObjectsById(couchConnection, appjson, function(){
        window.startApp(a);
      });
    });
  } else {
    Utils.debug("Loading fresh app");
    $(".testcss").html("changing it dynamically");
    // Create a UserWelcomeView modal
    var welcomeUserView = new UserWelcomeView();
    welcomeUserView.render();
    $('#user-welcome-modal').modal("show");
  }

});
<|endoftext|>