<commit_before>/*
 * Created for OpenROV:  www.openrov.com
 * Author:  Bran Sorem (www.bransorem.com)
 * Date: 04/21/12
 *
 * Description:
 * This script is the Node.js server for OpenROV.  It creates a server and instantiates an OpenROV
 * and sets the interval to grab frames.  The interval is set with the DELAY variable which is in
 * milliseconds.
 *
 * License
 * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a
 * letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
 */

var express = require('express');

var app = express.createServer(express.static(__dirname + '/static'))
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , OpenROVCamera = require('./lib/OpenROVCamera')
  , OpenROVController = require('./lib/OpenROVController')
  ;

var CONFIG = require('./lib/config');

var DELAY = Math.round(1000 / CONFIG.video_frame_rate);
var camera = new OpenROVCamera({delay : DELAY});
var controller = new OpenROVController();

app.get('/config.js', function(req, res) {
  res.send('var CONFIG = ' + JSON.stringify(CONFIG));
});

// no debug messages
io.configure(function(){ io.set('log level', 1); });

var connections = 0;
// SOCKET connection ==============================
io.sockets.on('connection', function (socket) {
  connections++;

  socket.send('initialize');  // opens socket with client

  socket.on('control_update', function(controls) {
    controller.sendCommand(controls.throttle, controls.yaw, controls.lift);
  });
  camera.capture(function(err) {
    if (err) {
      connections--;
      camera.close();
      return console.error('couldn\'t initialize camera. got:', err);
    }
    // when frame emits, send it
    camera.on('frame', function(img){
      if (CONFIG.debug) console.log('emitting frame')
      socket.volatile.emit('frame', img);
    });
  });
});

// SOCKET disconnection ==============================
io.sockets.on('disconnect', function(socket){
  connections--;
  if(connections === 0) rov.close();
});

camera.on('error.device', function(err) {
  console.error('camera emitted an error:', err);
});

process.on('SIGTERM', function() {
  console.error('got SIGTERM, shutting down...');
  camera.close();
  process.exit(0);
});

process.on('SIGINT', function() {
  console.error('got SIGINT, shutting down...');
  camera.close();
  process.exit(0);
})

app.listen(CONFIG.port);<commit_msg>setup logging<commit_after>/*
 * Created for OpenROV:  www.openrov.com
 * Author:  Bran Sorem (www.bransorem.com)
 * Date: 04/21/12
 *
 * Description:
 * This script is the Node.js server for OpenROV.  It creates a server and instantiates an OpenROV
 * and sets the interval to grab frames.  The interval is set with the DELAY variable which is in
 * milliseconds.
 *
 * License
 * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a
 * letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
 */

var express = require('express');

var app = express.createServer(express.static(__dirname + '/static'))
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , OpenROVCamera = require('./lib/OpenROVCamera')
  , OpenROVController = require('./lib/OpenROVController')
  ;

var CONFIG = require('./lib/config');

var DELAY = Math.round(1000 / CONFIG.video_frame_rate);
var camera = new OpenROVCamera({delay : DELAY});
var controller = new OpenROVController();

app.get('/config.js', function(req, res) {
  res.send('var CONFIG = ' + JSON.stringify(CONFIG));
});

// no debug messages
io.configure(function(){ io.set('log level', 1); });

var connections = 0;
// SOCKET connection ==============================
io.sockets.on('connection', function (socket) {
  connections++;

  socket.send('initialize');  // opens socket with client

  socket.on('control_update', function(controls) {
    controller.sendCommand(controls.throttle, controls.yaw, controls.lift);
  });
  camera.capture(function(err) {
    if (err) {
      connections--;
      camera.close();
      return console.error('couldn\'t initialize camera. got:', err);
    }

    console.log('initialized camera, adding listener for \'frame\' event');
    // when frame emits, send it
    camera.on('frame', function(img){
      if (CONFIG.debug) console.log('emitting frame')
      socket.volatile.emit('frame', img);
    });
  });
});

// SOCKET disconnection ==============================
io.sockets.on('disconnect', function(socket){
  connections--;
  if(connections === 0) rov.close();
});

camera.on('error.device', function(err) {
  console.error('camera emitted an error:', err);
});

process.on('SIGTERM', function() {
  console.error('got SIGTERM, shutting down...');
  camera.close();
  process.exit(0);
});

process.on('SIGINT', function() {
  console.error('got SIGINT, shutting down...');
  camera.close();
  process.exit(0);
})

app.listen(CONFIG.port);<|endoftext|>


<commit_before>// Copyright 2011 Marcel Laverdet
"use strict";
this.create = create;
this.invoke = invoke;
this.construct = construct;

require('fibers');

/**
 * container for the context that the runtime maintains across async calls
 */
 var globals = require('../globals');

/**
 * Creates a function that builds a fiber when called and automatically returns a future.
 *
 * rewrite:
 * function foo(arg, _) {
 *	 ...
 * }
 * ->
 * var foo = create(foo(arg, _) {
 *	 ...
 * }, 1);
 */
function create(fn, idx) {
	function F() {
		// If there was no callback passed then this function needs to return a future, so setup the
		// bookkeeping for that.
		var cb = arguments[idx];
		var err, val, q, resolved = false;
		var memoize = cb || function(e, v) {
			err = e;
			val = v;
			resolved = true;
			q && q.forEach(function(f) {
				try {
					f(err, val);
				} catch (ex) {
					if (globals.context && globals.context.errorHandler) globals.context.errorHandler(ex);
					else throw ex;
				}
			});
			q = null;
		};

		// Start a new fiber
		var that = this, args = arguments;
		new Fiber(function() {
			var val;
			try {
				val = fn.apply(that, args);
			} catch (err) {
				memoize(err);
				return;
			}
			memoize(null, val);
		}).run();

		// Return a future if no callback
		if (!cb) {
			return function future(cb) {
				if (!cb) return future;
				if (resolved) {
					cb(err && makeError(err, true), val);
				} else if (q) {
					q.push(cb);
				} else {
					q = [cb];
				}
			};
		}
	};

	// Memoize the original function for fast passing later
	F.fstreamlineFunction = fn;
	return F;
}

/**
 * Invokes an async function and yields currently running fiber until it callsback.
 *
 * rewrite:
 * fs.readFile(file, _);
 * ->
 * invoke(fs, 'readFile', [file], 1);
 */
function invoke(that, fn, args, idx) {
	// Resolve the function to be called
	if (typeof fn !== 'function') {
		if (typeof that === 'function' && that.fstreamlineFunction && fn === 'call') {
			return that.fstreamlineFunction.apply(args[0], args.slice(1));
		}
		fn = that[fn];
	}

	// If we're waiting on a fstreamline.create function we can just call it directly instead
	if (fn.fstreamlineFunction) {
		try {
			return fn.fstreamlineFunction.apply(that, args);
		} catch (e) {
			throw makeError(e, false);
		}
	}

	// Setup callback to resume fiber after it's yielded
	var fiber = Fiber.current;
	var err, val, yielded = false, cx;
	args[idx] = function(e, v) {
		if (!yielded) {
			yielded = true;
			err = e;
			val = v;
		} else {
			globals.context = cx;
			if (e) {
				fiber.throwInto(e);
			} else {
				fiber.run(v);
			}
		}
	};

	// Invoke the function and yield
	fn.apply(that, args);
	if (yielded) {
		if (err) {
			throw err;
		}
		return val;
	}
	yielded = true;
	cx = globals.context;
	try {
		return Fiber.yield();
	} catch (e) {
		throw makeError(e, true);
	}
}

function construct(constructor, i) {
	if (!constructor.fstreamlineFunction) throw new Error("async constructor only allowed on streamlined functions")
	var key = '__async' + i;
	return constructor[key] || (constructor[key] = function() {
		var that = Object.create(constructor.prototype);
		constructor.fstreamlineFunction.apply(that, arguments);
		return that;
	});
}

// Double stack capture size because we may filter out half of them
Error.stackTraceLimit *= 2;

// Wraps an error to fix stacktrace
function makeError(e, incomplete) {
	if (!(e instanceof Error)) return e;
	var extra;
	if (incomplete) {
		extra = {};
		Error.captureStackTrace(extra);
	} else if (e.streamlined) {
		return e;
	}
	var ne = Object.create(e);
	ne.streamlined = e;
	Object.defineProperty(ne, 'stack', {
		get: function() {
			return e.stack && e.stack.split('\n').concat(extra ? extra.stack.split('\n').slice(2) : []).filter(function(frame) {
				return frame.indexOf('streamline/lib/fibers/runtime.js') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}
require("streamline/lib/fibers/builtins");
<commit_msg>Fix issue #105 for fibers too.<commit_after>// Copyright 2011 Marcel Laverdet
"use strict";
this.create = create;
this.invoke = invoke;
this.construct = construct;

require('../util/require')('fibers', module.parent.filename);

/**
 * container for the context that the runtime maintains across async calls
 */
 var globals = require('../globals');

/**
 * Creates a function that builds a fiber when called and automatically returns a future.
 *
 * rewrite:
 * function foo(arg, _) {
 *	 ...
 * }
 * ->
 * var foo = create(foo(arg, _) {
 *	 ...
 * }, 1);
 */
function create(fn, idx) {
	function F() {
		// If there was no callback passed then this function needs to return a future, so setup the
		// bookkeeping for that.
		var cb = arguments[idx];
		var err, val, q, resolved = false;
		var memoize = cb || function(e, v) {
			err = e;
			val = v;
			resolved = true;
			q && q.forEach(function(f) {
				try {
					f(err, val);
				} catch (ex) {
					if (globals.context && globals.context.errorHandler) globals.context.errorHandler(ex);
					else throw ex;
				}
			});
			q = null;
		};

		// Start a new fiber
		var that = this, args = arguments;
		new Fiber(function() {
			var val;
			try {
				val = fn.apply(that, args);
			} catch (err) {
				memoize(err);
				return;
			}
			memoize(null, val);
		}).run();

		// Return a future if no callback
		if (!cb) {
			return function future(cb) {
				if (!cb) return future;
				if (resolved) {
					cb(err && makeError(err, true), val);
				} else if (q) {
					q.push(cb);
				} else {
					q = [cb];
				}
			};
		}
	};

	// Memoize the original function for fast passing later
	F.fstreamlineFunction = fn;
	return F;
}

/**
 * Invokes an async function and yields currently running fiber until it callsback.
 *
 * rewrite:
 * fs.readFile(file, _);
 * ->
 * invoke(fs, 'readFile', [file], 1);
 */
function invoke(that, fn, args, idx) {
	// Resolve the function to be called
	if (typeof fn !== 'function') {
		if (typeof that === 'function' && that.fstreamlineFunction && fn === 'call') {
			return that.fstreamlineFunction.apply(args[0], args.slice(1));
		}
		fn = that[fn];
	}

	// If we're waiting on a fstreamline.create function we can just call it directly instead
	if (fn.fstreamlineFunction) {
		try {
			return fn.fstreamlineFunction.apply(that, args);
		} catch (e) {
			throw makeError(e, false);
		}
	}

	// Setup callback to resume fiber after it's yielded
	var fiber = Fiber.current;
	var err, val, yielded = false, cx;
	args[idx] = function(e, v) {
		if (!yielded) {
			yielded = true;
			err = e;
			val = v;
		} else {
			globals.context = cx;
			if (e) {
				fiber.throwInto(e);
			} else {
				fiber.run(v);
			}
		}
	};

	// Invoke the function and yield
	fn.apply(that, args);
	if (yielded) {
		if (err) {
			throw err;
		}
		return val;
	}
	yielded = true;
	cx = globals.context;
	try {
		return Fiber.yield();
	} catch (e) {
		throw makeError(e, true);
	}
}

function construct(constructor, i) {
	if (!constructor.fstreamlineFunction) throw new Error("async constructor only allowed on streamlined functions")
	var key = '__async' + i;
	return constructor[key] || (constructor[key] = function() {
		var that = Object.create(constructor.prototype);
		constructor.fstreamlineFunction.apply(that, arguments);
		return that;
	});
}

// Double stack capture size because we may filter out half of them
Error.stackTraceLimit *= 2;

// Wraps an error to fix stacktrace
function makeError(e, incomplete) {
	if (!(e instanceof Error)) return e;
	var extra;
	if (incomplete) {
		extra = {};
		Error.captureStackTrace(extra);
	} else if (e.streamlined) {
		return e;
	}
	var ne = Object.create(e);
	ne.streamlined = e;
	Object.defineProperty(ne, 'stack', {
		get: function() {
			return e.stack && e.stack.split('\n').concat(extra ? extra.stack.split('\n').slice(2) : []).filter(function(frame) {
				return frame.indexOf('streamline/lib/fibers/runtime.js') < 0;
			}).join('\n');
		},
		enumerable: true,
	});
	return ne;
}
require("streamline/lib/fibers/builtins");
<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * A field for dealing with related resources
 * @module tastypie/fields/related
 * @author Eric Satterwhite
 * @since 0.5.0
 * requires path
 * @requires tastypie/lib/class
 * @requires tastypie/lib/fields/api
 */

var path     = require( 'path' )
  , Class    = require( '../class' )
  , ApiField = require( './api' )
  , debug    = require('debug')('tastypie:field:related')
  , get      = require('mout/object/get')
  , async    = require('async')
  , toModule = require('../utility').toModule
  , RelatedField
  ;

/**
 * @constructor
 * @alias module:tastypie/fields/related
 * @extends module:tastypie/fields/api
 * @param {Object} options
 * @param {String} [options.root=os.tempDir()]
 * @param {String} [options.dir]
 */
RelatedField = new Class({
	inherits:ApiField
	,options:{
		to:null,
		minimal: false,
		full: false
	}
	,is_related: true
	,constructor: function(to, options){
		if( arguments.length === 1){
			options = to;
			to = options.to;
		}

		this.parent('constructor', options);
		this.options.to = to;
		this.instance = new this.cls();
	}
	,dehydrate: function( obj,cb ){
		var that = this;
		if( !this.instance.options.apiname ){
			debug('setting related apiname - %s', this.resource.options.apiname )
			this.instance.setOptions({
				apiname: this.resource.options.apiname
			})
		}

		this.parent('dehydrate', obj, function( err, value ){
			if( err ){
				return cb && cb( err, null )
			}

			if( that.options.full ){
				return cb( err, value )
			} else if( that.options.minimal ){
				async.map(
					value,
					that.to_minimal.bind( that ),
					cb
				)
			} else{
				return cb( err, value && value.map(that.instance.to_uri.bind( that.instance ) ) )
			}
		});
	}
	/**
	 * converts a full object in to a minimal representation
	 * @method module:tastypie/lib/field/related#to_minimal
	 * @param {Object} obj A template object instance to introspect
	 * @return {TYPE} DESCRIPTION
	 **/
	,to_minimal: function( obj, cb ){
		var label = this.instance.options.labelField || 'display'
		  , that  = this
		  , related_field
		  ;
		debug('lable field %s', label )
		related_field = this.instance.fields[label];
		related_field.dehydrate( obj, function( err, value ){
			var out = {};
			out.uri =  that.instance.to_uri( obj );
			out[  label ] = value;
			that = label = related_field = null;
			cb( null, out );
		});
	}
});

Object.defineProperties(RelatedField.prototype,{
	cls:{
		enumerable:false
		,writeable: false
		,get: function(){
            if( typeof this.options.to === 'string' ){
                this.options.to = toModule( this.options.to );
            }
            return this.options.to;
		}
	}
});

module.exports = RelatedField;
<commit_msg>Fixing related field docs and logging<commit_after>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * A field for dealing with related resources
 * @module tastypie/fields/related
 * @author Eric Satterwhite
 * @since 0.5.0
 * @requires path
 * @requires async
 * @requires debug
 * @requires mout/object/get
 * @requires tastypie/lib/class
 * @requires tastypie/lib/utility
 * @requires tastypie/lib/fields/api
 */

var path     = require( 'path' )
  , debug    = require('debug')('tastypie:field:related')
  , get      = require('mout/object/get')
  , async    = require('async')
  , ApiField = require( './api' )
  , Class    = require( '../class' )
  , toModule = require('../utility').toModule
  , RelatedField
  ;

/**
 * @constructor
 * @alias module:tastypie/fields/related
 * @extends module:tastypie/fields/api
 * @param {Object} options
 * @param {String} [options.root=os.tempDir()]
 * @param {String} [options.dir]
 */
RelatedField = new Class({
	inherits:ApiField
	,options:{
		to:null,
		minimal: false,
		full: false
	}
	,is_related: true
	,constructor: function(to, options){
		if( arguments.length === 1){
			options = to;
			to = options.to;
		}

		this.parent('constructor', options);
		this.options.to = to;
		this.instance = new this.cls();
	}
	,dehydrate: function( obj,cb ){
		var that = this;
		if( !this.instance.options.apiname ){
			debug('setting field %s related apiname - %s', this.options.name, this.resource.options.apiname );
			this.instance.setOptions({
				apiname: this.resource.options.apiname
			})
		}

		this.parent('dehydrate', obj, function( err, value ){
			if( err ){
				return cb && cb( err, null )
			}

			if( that.options.full ){
				return cb( err, value )
			} else if( that.options.minimal ){
				async.map(
					value,
					that.to_minimal.bind( that ),
					cb
				)
			} else{
				return cb( err, value && value.map(that.instance.to_uri.bind( that.instance ) ) )
			}
		});
	}
	/**
	 * converts a full object in to a minimal representation
	 * @method module:tastypie/lib/field/related#to_minimal
	 * @param {Object} obj A template object instance to introspect
	 * @param {Function} callback a callback function to execute when the related field dehydration is completed
	 **/
	,to_minimal: function( obj, cb ){
		var label = this.instance.options.labelField || 'display'
		  , that  = this
		  , related_field
		  ;
		related_field = this.instance.fields[label];
		related_field.dehydrate( obj, function( err, value ){
			var out = {};
			out.uri =  that.instance.to_uri( obj );
			out[  label ] = value;
			that = label = related_field = null;
			cb( null, out );
		});
	}
});

Object.defineProperties(RelatedField.prototype,{
	cls:{
		enumerable:false
		,writeable: false
		,get: function(){
            if( typeof this.options.to === 'string' ){
                this.options.to = toModule( this.options.to );
            }
            return this.options.to;
		}
	}
});

module.exports = RelatedField;
<|endoftext|>


<commit_before>/**
 * Entry point for orchestrator lambda function
 */
'use strict';

const
  logger = require('./common/logger'),
  constants = require('./common/constants'),
  bottle = constants.BOTTLE_CONTAINER,
  apiRouter = require('./api/api-router'),
  tasksRouter = require('./tasks/tasks-router'),
  error = require('./services/error'),
  glob = require('glob'),
  config = require('config'),
  GitHub = require('github-api'),
  _ = require('lodash'),
  AWS = require('aws-sdk'),
  path = require('path');

// Load all modules (to ensure all bottle services are loaded)
glob.sync('./src/**/*.js').forEach(file => {
  require(path.resolve(file));
});

function registerCommonServices() {
  bottle.value('githubApi', new GitHub({
    token: config.github.token
  }));
  bottle.value('stepFunctions', new AWS.StepFunctions(_.merge({}, config.aws)));
}

module.exports = {

  createRoutesHandler: () => {
    //Setup common bottle services / values
    registerCommonServices();

    // Return the handler
    return (event, context, callback) => {
      logger.info(`Routes: Begin: `, event, context);

      // API Gateway Events
      if(event.path) {
        return apiRouter.handler(event, context, callback);
      }
      // Finally, throw error if no event handler found
      callback(new error.EventHandlerNotRegistered());
    };
  },

  createTasksHandler: () => {

    //Setup common bottle services / values
    registerCommonServices();

    // Return the handler
    return (event, context, callback) => {
      logger.info(`Step Functions: Begin: `, event, context);

      return tasksRouter.handler(event, context, callback);
      // Finally, throw error if no event handler found
      callback(new error.EventHandlerNotRegistered());
    };
  }
};<commit_msg>Fix JSHint issues<commit_after>/**
 * Entry point for orchestrator lambda function
 */
'use strict';

const
  logger = require('./common/logger'),
  constants = require('./common/constants'),
  bottle = constants.BOTTLE_CONTAINER,
  apiRouter = require('./api/api-router'),
  tasksRouter = require('./tasks/tasks-router'),
  error = require('./services/error'),
  glob = require('glob'),
  config = require('config'),
  GitHub = require('github-api'),
  _ = require('lodash'),
  AWS = require('aws-sdk'),
  path = require('path');

// Load all modules (to ensure all bottle services are loaded)
glob.sync('./src/**/*.js').forEach(file => {
  require(path.resolve(file));
});

function registerCommonServices() {
  bottle.value('githubApi', new GitHub({
    token: config.github.token
  }));
  bottle.value('stepFunctions', new AWS.StepFunctions(_.merge({}, config.aws)));
}

module.exports = {

  createRoutesHandler: () => {
    //Setup common bottle services / values
    registerCommonServices();

    // Return the handler
    return (event, context, callback) => {
      logger.info(`Routes: Begin: `, event, context);

      // API Gateway Events
      if(event.path) {
        return apiRouter.handler(event, context, callback);
      }
      // Finally, throw error if no event handler found
      callback(new error.EventHandlerNotRegistered());
    };
  },

  createTasksHandler: () => {

    //Setup common bottle services / values
    registerCommonServices();

    // Return the handler
    return (event, context, callback) => {
      logger.info(`Step Functions: Begin: `, event, context);

      return tasksRouter.handler(event, context, callback);
    };
  }
};<|endoftext|>


<commit_before>const angular = require('angular');
const ngRoute = require('angular-route');
const app = angular.module('app', ['ngRoute']);

var links = [
  {
    "title":"Bloodstone",
    "url":"http://bloodstonedevelopment.tk/"
  },
  {
    "title":"Github",
    "url":"https://github.com/"
  },
  {
    "title":"hvg.hu",
    "url":"http://hvg.hu"
  },
  {
    "title":"Green Fox Academy",
    "url":"http://greenfoxacademy.com"
  },
  {
    "title":"Angular JS",
    "url":"https://angularjs.org/"
  },
  {
    "title":"Origo",
    "url":"http://origo.hu"
  },
  {
    "title":"b.hu",
    "url":"http://b.hu"
  },
  {
    "title":"JS Garden",
    "url":"http://bonsaiden.github.io/JavaScript-Garden/"
  }
];

// *************** ROUTING ***************

app.config(['$routeProvider', function routeProvider($routeProvider) {
  $routeProvider
  .when('/login', {
    templateUrl: './views/login.html',
    controller: 'LoginController'
  })
  .when('/register', {
    templateUrl: './views/register.html',
    controller: 'RegistrationController'
  })
  .when('/home', {
    templateUrl: './views/list.html',
    controller: 'RenderController',
    resolve: {
      logincheck: checkLoggedin,
    }
  })
  .otherwise({
    redirectTo: '/login', // NOTE: Temporarily
  });
}]);

const checkLoggedin = function checkLoggedin($q, $timeout, $http, $location, $rootScope) {
  const deferred = $q.defer();

  $http.get('/api/loggedin')
    .then(function(user) {
      console.log(user);
      $rootScope.errorMessage = null;
      // User is Authenticated
      if (user.data !== '0') {
        $rootScope.currentUser = user;
        deferred.resolve();
      } else { // User not Auth.
        $rootScope.errorMessage = 'Error! You need to log in.';
        deferred.reject();
        $location.url('/login');
      }
    });
  return deferred.promise;
};

app.factory('sessionFactory', ['$location', '$http', '$rootScope', function ($location, $http, $rootScope) {
  var login = function (loginData) {
    return $http.post('/api/login', JSON.stringify(loginData))
      .then(function (response) {
        console.log('Login response: ', response);
        if (loginData.email === response.data) {
          console.log($location.path);
          $rootScope.currentUser = response;
          $location.path('/home');
          console.log($location.path);
        }
      })
      .catch(function (err) {
        console.log('Login error: ', err);
      });
  };

  var register = function (userRegData) {
    return $http.post('/api/register', JSON.stringify(userRegData))
    .then(function (response) {
      console.log("Reg. response: ", response);
      if (response.data.message) {
        $location.url('/home');
      }
    })
    .catch(function (err) {
      console.log('Registration error: ', err);
    });
  };

  return {
    login: login,
    register: register
  }
}]);

// *********** CONTROLLERS ************
app.controller('LoginController', ['$scope', 'sessionFactory', '$rootScope', function ($scope, sessionFactory, $rootScope) {
  $scope.userLogin = function userLogin() {
    var userLog = {
      email: $scope.user.email,
      password: $scope.user.password
    };
    sessionFactory.login(userLog);
  };
}]);

app.controller('RegistrationController', ['$scope', 'sessionFactory', '$rootScope', function ($scope, sessionFactory, $rootScope) {
  $scope.userRegister = function userRegister() {
    if ($scope.user.password !== $scope.user.passwordRepeat) {
      console.log("Error! Passwords don't match!")
    }
    else {
      var userRegData = {
        email: $scope.user.email,
        password: $scope.user.password
      };
      console.log(userRegData);
      sessionFactory.register(userRegData);
    }
  };
}]);

app.controller('RenderController', ['$scope', '$rootScope', '$http', '$location', function ($scope, $rootScope, $http, $location) {
  $scope.dummyLinks = links;
  $scope.logout = function() {
    $http.post('/api/logout')
      .then(function() {
        $rootScope.currentUser = null;
        $location.url('/home');
      });
  }
}]);

module.exports = app;
<commit_msg>INDEV: checkLoggedin wrapped as a factory. ERROR: checkLoggedin not defined.<commit_after>const angular = require('angular');
const ngRoute = require('angular-route');
const app = angular.module('app', ['ngRoute']);

var links = [
  {
    "title":"Bloodstone",
    "url":"http://bloodstonedevelopment.tk/"
  },
  {
    "title":"Github",
    "url":"https://github.com/"
  },
  {
    "title":"hvg.hu",
    "url":"http://hvg.hu"
  },
  {
    "title":"Green Fox Academy",
    "url":"http://greenfoxacademy.com"
  },
  {
    "title":"Angular JS",
    "url":"https://angularjs.org/"
  },
  {
    "title":"Origo",
    "url":"http://origo.hu"
  },
  {
    "title":"b.hu",
    "url":"http://b.hu"
  },
  {
    "title":"JS Garden",
    "url":"http://bonsaiden.github.io/JavaScript-Garden/"
  }
];

// *************** ROUTING ***************

app.config(['$routeProvider', 'checkLoggedin', function routeProvider($routeProvider, checkLoggedin) {
  $routeProvider
  .when('/login', {
    templateUrl: './views/login.html',
    controller: 'LoginController'
  })
  .when('/register', {
    templateUrl: './views/register.html',
    controller: 'RegistrationController'
  })
  .when('/home', {
    templateUrl: './views/list.html',
    controller: 'RenderController',
    resolve: {
      logincheck: checkLoggedin.check,
    }
  })
  .otherwise({
    redirectTo: '/login', // NOTE: Temporarily
  });
}]);

// Check loggedin service
app.factory('checkLoggedin',
  ['$q', '$timeout', '$http', '$location', '$rootScope',
  function ($q, $timeout, $http, $location, $rootScope) {
    const check = function () {
      const deferred = $q.defer();
      $http.get('/api/loggedin')
        .then(function(user) {
          console.log(user);
          $rootScope.errorMessage = null;
          // User is Authenticated
          if (user.data !== '0') {
            $rootScope.currentUser = user;
            deferred.resolve();
          } else { // User not Auth.
            $rootScope.errorMessage = 'Error! You need to log in.';
            deferred.reject();
            $location.url('/login');
          }
        });
      return deferred.promise;
    };

    return {
      check: check,
    };
  }
]);

app.factory('userSession', ['$location', '$http', '$rootScope', function ($location, $http, $rootScope) {
  const login = function (loginData) {
    return $http.post('/api/login', JSON.stringify(loginData))
      .then(function (response) {
        console.log('Login response: ', response);
        if (loginData.email === response.data) {
          console.log($location.path);
          $rootScope.currentUser = response;
          $location.path('/home');
          console.log($location.path);
        }
      })
      .catch(function (err) {
        console.log('Login error: ', err);
      });
  };

  const register = function (userRegData) {
    return $http.post('/api/register', JSON.stringify(userRegData))
    .then(function (response) {
      console.log("Reg. response: ", response);
      if (response.data.message) {
        $location.url('/home');
      }
    })
    .catch(function (err) {
      console.log('Registration error: ', err);
    });
  };

  return {
    login: login,
    register: register
  }
}]);

// *********** CONTROLLERS ************
app.controller('LoginController', ['$scope', 'sessionFactory', '$rootScope', function ($scope, sessionFactory, $rootScope) {
  $scope.userLogin = function userLogin() {
    var userLog = {
      email: $scope.user.email,
      password: $scope.user.password
    };
    sessionFactory.login(userLog);
  };
}]);

app.controller('RegistrationController', ['$scope', 'sessionFactory', '$rootScope', function ($scope, sessionFactory, $rootScope) {
  $scope.userRegister = function userRegister() {
    if ($scope.user.password !== $scope.user.passwordRepeat) {
      console.log("Error! Passwords don't match!")
    }
    else {
      var userRegData = {
        email: $scope.user.email,
        password: $scope.user.password
      };
      console.log(userRegData);
      sessionFactory.register(userRegData);
    }
  };
}]);

app.controller('RenderController', ['$scope', '$rootScope', '$http', '$location', function ($scope, $rootScope, $http, $location) {
  $scope.dummyLinks = links;
  $scope.logout = function() {
    $http.post('/api/logout')
      .then(function() {
        $rootScope.currentUser = null;
        $location.url('/home');
      });
  }
}]);

module.exports = app;
<|endoftext|>


<commit_before>import { Element as PolymerElement } from '/node_modules/@polymer/polymer/polymer-element.js'
import { html } from '/node_modules/lit-html/lit-html.js'
import { render } from '/node_modules/lit-html/lib/lit-extended.js'
import '/src/components/tap-button/index.js'
import '/src/components/connect-button/index.js'
import '/src/components/connect-bluetooth-button/index.js'
import '/src/components/download-config-button/index.js'
import '/src/components/bpm-meter/index.js'
import '/src/components/channel-grid/index.js'
import '/src/components/device-list/index.js'
import '/src/components/midi-manager/index.js'
import '/src/components/timeline-item/index.js'

import BluetoothManager from '/src/core/BluetoothManager.js'
import USBManager from '/src/core/USBManager.js'
import MidiManager from '/src/core/MidiManager.js'
import StorageManager from '/src/core/StorageManager.js'
import DeviceManager from '/src/devices/DeviceManager.js'
import AnimationManager from '/src/core/AnimationManager.js'
import SceneManager from '/src/core/SceneManager.js'
import Render from '/src/core/Render.js'
import Configuration from '/src/core/Configuration.js'

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

class AppContent extends PolymerElement {

  constructor() {
    super()
    this.storage = new StorageManager()
    this.configuration = new Configuration({
      storage: this.storage,
      restore: false
    })
    this.config = this.configuration
    window.configuration = this.configuration

    this.bluetooth = new BluetoothManager({ configuration: this.configuration })

    this.usb = new USBManager({ configuration: this.configuration })
    window.usbManager = this.usb

    // Manage connected MIDI devices
    this.midiManager = new MidiManager({ config: this.config.getConfig() })
    // Expose it globally so we can use it in the console
    window.midiManager = this.midiManager

    this.deviceManager = new DeviceManager({
      configuration: this.configuration,
      output: this.usb.output
    })
    this.deviceManager.register()

    // Initialize all animations
    this.animationManager = new AnimationManager({
      config: this.config.getConfig(),
      deviceManager: this.deviceManager
    })
    this.animationManager.register()

    // Initialize all scenes
    this.sceneManager = new SceneManager({
      config: this.config.getConfig(),
      animationManager: this.animationManager
    })
    this.sceneManager.register()

    // Manage playback of all animations, scenes, timelines
    this.render = new Render({
      config: this.config,
      dmxUsbInterface: this.usb,
      sceneManager: this.sceneManager
    })
    // this.render.start(this.config.getConfig().global.fps)

    this.deviceManager.reset()

    const bpm = this.configuration.getConfig().global.bpm || 120
    const measures = 8
    this.state = {
      bpm: bpm,
      measures,
      connected: false,
      bluetoothConnected: false,
      time: new Date(),
      duration: ~~(60 / bpm * 1000 * measures)
    }

    this.dmxList = [...this.deviceManager.list].map((e, i) => {
      const [key, value] = e

      return {
        id: key,
        channel: i,
        bufferOffset: value.instance.bufferOffset,
        deviceId: value.instance.deviceId,
        type: value.type,
        params: Object.keys(value.instance.params).map(x => ({
          param: x,
          channels: value.instance.params[x].channels
        }))
      }
    })
    this.scenesList = [...this.sceneManager.list].map((e, i) => {
      const [key, value] = e
      return {key, value}
    })

    this.dmxList.sort((a, b) => a.bufferOffset - b.bufferOffset)
    // console.log(this.scenesList)
  }

  setState(newState) {
    if (typeof this.state === 'object') {
      Promise.resolve().then(()=> {
        this.state = {...(this.state), ...newState}
      })
    } else {
      throw new Error('no state is available. Please make sure to define an initital state in your constructor')
    }
  }

  connectedCallback() {
    super.connectedCallback()
    this.listen()
    this.setTime()
  }

  setTime(){
    const {time, bpm, measures, duration} = this.state
    const now = new Date()
    const timeCounter = (now - time) / duration
    if (now - time > duration) {
      this.setState({
        time: now,
      })
    }
    this.setState({
      timeCounter
    })
    this.runTimeline(timeCounter)
    requestAnimationFrame(this.setTime.bind(this))
  }

  runTimeline(counter) {
    const values = this.getValues(counter)

    values.forEach(scene => {
      scene.children.forEach(layer => {
        layer.children.forEach(animation => {
          animation.animation.values = animation.children
          animation.animation.run()

          animation.children.forEach(prop => {
            const [r, g, b] = prop.children
            console.log(`${prop.name} (${layer.devices.join(', ')}): rgb(${~~(r)}, ${~~(g)}, ${~~(b)})`)
          })
        })
      })
    })

    // Render all DMX devices into a buffer
    this.render.run()
  }

  getValues(counter) {
    const items = this.scenesList.map(scene => {
      return {
        id: scene.key,
        children: scene.value.layers.map(layer => {
          return {
            id: layer.layerId,
            devices: layer.devices,
            children: layer.animations.map(animation => {
              const progress = counter * this.state.measures / animation.duration
              const values = animation.timeline.values(progress)
              return {
                id: animation.animationId,
                devices: animation.devices,
                animation: animation,
                children: Object.keys(values).map(key => {
                  return {
                    name: key,
                    children: values[key]
                  }
                })
              }
            })
          }
        })
      }
    })

    return items
  }

  ready() {
    super.ready()
  }

  listen() {
    window.addEventListener('USBDriver', event => {
      const {connected} = event.detail
      // Connection status for USB DMX controller
      this.configuration.getConfig().dmxInterface.connected = connected
      this.setState({connected})
    })
  }

  handleTap(e) {
    const {bpm} = e.detail
    const duration = ~~(60 / bpm * 1000 * this.state.measures)
    this.configuration.data.global.bpm = bpm
    this.setState({bpm, duration})
  }

  handleConnect(e) {
    this.usb.enable()
  }

  handleDisconnect(e) {
    this.usb.port.disconnect()
    this.usb.port = null
  }

  handleUpdate(e) {
    const { value, channelId } = e.detail
    this.usb.update(channelId, value)
  }

  handleBluetoothConnect(e) {
    this.bluetooth.enable()
    this.state.bluetoothConnected = true
  }

  handleBluetoothDisconnect(e) {
  }

  handleDownload(e) {
    console.log(window.configuration.data)
  }

  static get template() {
    return `

          <connect-button connected="{{state.connected}}"
                          on-connect="handleConnect"
                          on-disconnect="handleDisconnect"></connect-button>
          <connect-bluetooth-button connected="{{state.bluetoothConnected}}"
                          on-connect="handleBluetoothConnect"
                          on-disconnect="handleBluetoothDisconnect"></connect-bluetooth-button>

          <download-config-button on-download="handleDownload"></download-config-button>

          <bpm-meter bpm="{{state.bpm}}"></bpm-meter>
          <tap-button class="one"
                      on-tap="handleTap"
                      delay="1500"
                      items="2"
                      controllerId="korgnanopad2"
                      partId="button16"
                      ></tap-button>

          <timeline-item scenes="{{scenesList}}"
                         time="{{state.timeCounter}}"
                         duration="{{state.duration}}"
                         bpm="{{state.bpm}}"
                         measure$="{{state.measures}}"></timeline-item>

          <device-list on-update="handleUpdate"
                       list="{{dmxList}}"></device-list>

    `
  }
}

class MyApp extends PolymerElement {
  static get template() {
    return render(html`<app-content></app-content>`, document.body)
  }
}
customElements.define('my-app', MyApp)
customElements.define('app-content', AppContent)
<commit_msg>refactor(timeline): data as object<commit_after>import { Element as PolymerElement } from '/node_modules/@polymer/polymer/polymer-element.js'
import { html } from '/node_modules/lit-html/lit-html.js'
import { render } from '/node_modules/lit-html/lib/lit-extended.js'
import '/src/components/tap-button/index.js'
import '/src/components/connect-button/index.js'
import '/src/components/connect-bluetooth-button/index.js'
import '/src/components/download-config-button/index.js'
import '/src/components/bpm-meter/index.js'
import '/src/components/channel-grid/index.js'
import '/src/components/device-list/index.js'
import '/src/components/midi-manager/index.js'
import '/src/components/timeline-item/index.js'

import BluetoothManager from '/src/core/BluetoothManager.js'
import USBManager from '/src/core/USBManager.js'
import MidiManager from '/src/core/MidiManager.js'
import StorageManager from '/src/core/StorageManager.js'
import DeviceManager from '/src/devices/DeviceManager.js'
import AnimationManager from '/src/core/AnimationManager.js'
import SceneManager from '/src/core/SceneManager.js'
import Render from '/src/core/Render.js'
import Configuration from '/src/core/Configuration.js'

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

class AppContent extends PolymerElement {

  constructor() {
    super()
    this.storage = new StorageManager()
    this.configuration = new Configuration({
      storage: this.storage,
      restore: false
    })
    this.config = this.configuration
    window.configuration = this.configuration

    this.bluetooth = new BluetoothManager({ configuration: this.configuration })

    this.usb = new USBManager({ configuration: this.configuration })
    window.usbManager = this.usb

    // Manage connected MIDI devices
    this.midiManager = new MidiManager({ config: this.config.getConfig() })
    // Expose it globally so we can use it in the console
    window.midiManager = this.midiManager

    this.deviceManager = new DeviceManager({
      configuration: this.configuration,
      output: this.usb.output
    })
    this.deviceManager.register()

    // Initialize all animations
    this.animationManager = new AnimationManager({
      config: this.config.getConfig(),
      deviceManager: this.deviceManager
    })
    this.animationManager.register()

    // Initialize all scenes
    this.sceneManager = new SceneManager({
      config: this.config.getConfig(),
      animationManager: this.animationManager
    })
    this.sceneManager.register()

    // Manage playback of all animations, scenes, timelines
    this.render = new Render({
      config: this.config,
      dmxUsbInterface: this.usb,
      sceneManager: this.sceneManager
    })
    // this.render.start(this.config.getConfig().global.fps)

    this.deviceManager.reset()

    const bpm = this.configuration.getConfig().global.bpm || 120
    const measures = 8
    this.state = {
      bpm: bpm,
      measures,
      connected: false,
      bluetoothConnected: false,
      time: new Date(),
      duration: ~~(60 / bpm * 1000 * measures)
    }

    this.dmxList = [...this.deviceManager.list].map((e, i) => {
      const [key, value] = e

      return {
        id: key,
        channel: i,
        bufferOffset: value.instance.bufferOffset,
        deviceId: value.instance.deviceId,
        type: value.type,
        params: Object.keys(value.instance.params).map(x => ({
          param: x,
          channels: value.instance.params[x].channels
        }))
      }
    })
    this.scenesList = [...this.sceneManager.list].map((e, i) => {
      const [key, value] = e
      return {key, value}
    })

    this.dmxList.sort((a, b) => a.bufferOffset - b.bufferOffset)
    // console.log(this.scenesList)
  }

  setState(newState) {
    if (typeof this.state === 'object') {
      Promise.resolve().then(()=> {
        this.state = {...(this.state), ...newState}
      })
    } else {
      throw new Error('no state is available. Please make sure to define an initital state in your constructor')
    }
  }

  connectedCallback() {
    super.connectedCallback()
    this.listen()
    this.setTime()
  }

  setTime(){
    const {time, bpm, measures, duration} = this.state
    const now = new Date()
    const timeCounter = (now - time) / duration
    if (now - time > duration) {
      this.setState({
        time: now,
      })
    }
    this.setState({
      timeCounter
    })
    this.runTimeline(timeCounter)
    requestAnimationFrame(this.setTime.bind(this))
  }

  runTimeline(counter) {
    const values = this.getValues(counter)

    values.forEach(scene => {
      scene.children.forEach(layer => {
        layer.children.forEach(animation => {
          animation.animation.values = animation.values
          animation.animation.run()

        })
      })
    })

    // Render all DMX devices into a buffer
    this.render.run()
  }

  getValues(counter) {
    const items = this.scenesList.map(scene => {
      return {
        id: scene.key,
        children: scene.value.layers.map(layer => {
          return {
            id: layer.layerId,
            devices: layer.devices,
            children: layer.animations.map(animation => {
              const progress = counter * this.state.measures / animation.duration
              const values = animation.timeline.values(progress)
              return {
                id: animation.animationId,
                devices: animation.devices,
                animation: animation,
                values: values
              }
            })
          }
        })
      }
    })

    return items
  }

  ready() {
    super.ready()
  }

  listen() {
    window.addEventListener('USBDriver', event => {
      const {connected} = event.detail
      // Connection status for USB DMX controller
      this.configuration.getConfig().dmxInterface.connected = connected
      this.setState({connected})
    })
  }

  handleTap(e) {
    const {bpm} = e.detail
    const duration = ~~(60 / bpm * 1000 * this.state.measures)
    this.configuration.data.global.bpm = bpm
    this.setState({bpm, duration})
  }

  handleConnect(e) {
    this.usb.enable()
  }

  handleDisconnect(e) {
    this.usb.port.disconnect()
    this.usb.port = null
  }

  handleUpdate(e) {
    const { value, channelId } = e.detail
    this.usb.update(channelId, value)
  }

  handleBluetoothConnect(e) {
    this.bluetooth.enable()
    this.state.bluetoothConnected = true
  }

  handleBluetoothDisconnect(e) {
  }

  handleDownload(e) {
    console.log(window.configuration.data)
  }

  static get template() {
    return `

          <connect-button connected="{{state.connected}}"
                          on-connect="handleConnect"
                          on-disconnect="handleDisconnect"></connect-button>
          <connect-bluetooth-button connected="{{state.bluetoothConnected}}"
                          on-connect="handleBluetoothConnect"
                          on-disconnect="handleBluetoothDisconnect"></connect-bluetooth-button>

          <download-config-button on-download="handleDownload"></download-config-button>

          <bpm-meter bpm="{{state.bpm}}"></bpm-meter>
          <tap-button class="one"
                      on-tap="handleTap"
                      delay="1500"
                      items="2"
                      controllerId="korgnanopad2"
                      partId="button16"
                      ></tap-button>

          <timeline-item scenes="{{scenesList}}"
                         time="{{state.timeCounter}}"
                         duration="{{state.duration}}"
                         bpm="{{state.bpm}}"
                         measure$="{{state.measures}}"></timeline-item>

          <device-list on-update="handleUpdate"
                       list="{{dmxList}}"></device-list>

    `
  }
}

class MyApp extends PolymerElement {
  static get template() {
    return render(html`<app-content></app-content>`, document.body)
  }
}
customElements.define('my-app', MyApp)
customElements.define('app-content', AppContent)
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var base = require('./base');

const development = _.merge({}, base, {
  env: 'development',
  auth0: {
    callbackURL: 'http://localhost:9000/auth/callback',
    clientID: 'uyTltKDRg1BKu3nzDu6sLpHS44sInwOu'
  },
  cip: {
    client: {
      logRequests: true
    }
  },
  siteTitle: 'kbhbilleder.dk (dev)',
  allowRobots: true,
  es: {
    log: 'error' //use 'trace' for verbose mode
  },
  features: {
    feedback: true,
    motifTagging: true,
    users: true,
    requireEmailVerification: true
    feedback: false,
    geoTagging: false,
    motifTagging: false,
    requireEmailVerification: true,
    users: false
  }
});

module.exports = development;
<commit_msg>Fixed a missing comma<commit_after>'use strict';

var _ = require('lodash');
var base = require('./base');

const development = _.merge({}, base, {
  env: 'development',
  auth0: {
    callbackURL: 'http://localhost:9000/auth/callback',
    clientID: 'uyTltKDRg1BKu3nzDu6sLpHS44sInwOu'
  },
  cip: {
    client: {
      logRequests: true
    }
  },
  siteTitle: 'kbhbilleder.dk (dev)',
  allowRobots: true,
  es: {
    log: 'error' //use 'trace' for verbose mode
  },
  features: {
    feedback: true,
    motifTagging: true,
    users: true,
    requireEmailVerification: true,
    feedback: false,
    geoTagging: false,
    motifTagging: false,
    requireEmailVerification: true,
    users: false
  }
});

module.exports = development;
<|endoftext|>


<commit_before>'use strict';

var FilteredCollection = require('../vendor/filtered-collection');
var SortedCollection = require('backbone-sorted-collection');
var sortsFilters = require('./sorts-filters');

function apply(collection, filter, sort) {
  var c = new FilteredCollection(null, { model: collection.model, collection: collection });
  c.setFilter(filter);
  var sorted = new SortedCollection(c);
  sorted.setSort(sort);

  return sorted;
}

module.exports = {
  favourites: function(collection) {
    return apply(collection, sortsFilters.model.favourites.filter, sortsFilters.model.favourites.sort);
  },
  recents: function(collection) {
    return apply(collection, sortsFilters.model.recent.filter, sortsFilters.model.recent.sort);
  },
  unreads: function(collection) {
    return apply(collection, sortsFilters.model.unreads.filter, sortsFilters.model.unreads.sort);
  }
};

<commit_msg>Update filtered-rooms.js<commit_after>'use strict';

var FilteredCollection = require('../vendor/filtered-collection');
var SortedCollection = require('backbone-sorted-collection');
var sortsFilters = require('./sorts-filters');

function apply(collection, filter, sort) {
  var c = new FilteredCollection(null, { model: collection.model, collection: collection });
  c.setFilter(filter);
  var sorted = new SortedCollection(c);
  sorted.setSort(sort);

  return sorted;
}

module.exports = {
  favourites: function(collection) {
    return apply(collection, sortsFilters.model.favourites.filter, sortsFilters.model.favourites.sort);
  },
  recents: function(collection) {
    return apply(collection, sortsFilters.model.recents.filter, sortsFilters.model.recents.sort);
  },
  unreads: function(collection) {
    return apply(collection, sortsFilters.model.unreads.filter, sortsFilters.model.unreads.sort);
  }
};

<|endoftext|>


<commit_before>exports.config = {
  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8080',

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  },

  specs: [ '../src/**/*.e2e.spec.js' ]
};

if (process.env['TRAVIS']) {
  exports.config.sauceUser = process.env['SAUCE_USERNAME'];
  exports.config.sauceKey  = process.env['SAUCE_ACCESS_KEY'];
  exports.config.multiCapabilities =  [{
    'browserName': 'internet explorer',
    'version': '11'
  }];

  for(var i=0; i<exports.config.multiCapabilities.length; i++) {
    exports.config.multiCapabilities[i]['tunnel-identifier'] = process.env['TRAVIS_JOB_NUMBER'];
  }

} else {
  exports.config.seleniumServerJar = '/usr/local/lib/node_modules/protractor/selenium/selenium-server-standalone-2.41.0.jar';
}
<commit_msg>maybe its the ie stuff that is unreliable<commit_after>exports.config = {
  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8080',

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  },

  specs: [ '../src/**/*.e2e.spec.js' ]
};

if (process.env['TRAVIS']) {
  exports.config.sauceUser = process.env['SAUCE_USERNAME'];
  exports.config.sauceKey  = process.env['SAUCE_ACCESS_KEY'];
  exports.config.multiCapabilities =  [{
    'browserName': 'firefox'
  }];

  for(var i=0; i<exports.config.multiCapabilities.length; i++) {
    exports.config.multiCapabilities[i]['tunnel-identifier'] = process.env['TRAVIS_JOB_NUMBER'];
  }

} else {
  exports.config.seleniumServerJar = '/usr/local/lib/node_modules/protractor/selenium/selenium-server-standalone-2.41.0.jar';
}
<|endoftext|>


<commit_before>
module.exports = {
    w3cmemes: {
        origin:         "W3CMemes"
    ,   name:           "W3CMemes"
    ,   description:    "The official news agency for the W3C community"
    }
,   w3cnews: {
        origin:         "W3C News"
    ,   name:           "W3C News"
    ,   description:    "The party line"
    }
,   "html-wg":  {
        origin:         "github"
    ,   name:           "HTML WG"
    ,   description:    "HTML Working Group work stream"
    ,   repository:     [
                            "w3c/html"
                        ,   "w3c/charter-html"
                        ,   "w3c/test-results"
                        ,   "w3c/dom"
                        ,   "w3c/aria-in-html"
                        ]
    }
,   wpt:  {
        origin:         "github"
    ,   name:           "WPT"
    ,   description:    "Web Platform Tests work stream"
    ,   repository:     [
                            "w3c/web-platform-tests"
                        ,   "w3c/wpt-runner"
                        ,   "w3c/test-results"
                        ,   "w3c/wpt-tools"
                        ,   "w3c/testharness.js"
                        ]
    }
,   "modern-tooling":   {
        origin:         "github"
    ,   name:           "Modern Tooling"
    ,   description:    "Work stream for the Modern Tooling project"
    ,   repository:     [
                            "w3c/echidna"
                        ,   "w3c/modern-tooling"
                        ,   "w3c/pheme"
                        ,   "w3c/midgard"
                        ,   "w3c/ash-nazg"
                        ,   "w3c/specberus"
                        ,   "w3c/respec"
                        ,   "w3c/respec-docs"
                        ,   "w3c/w3c-api"
                        ,   "w3c/developers"
                        ,   "w3c/third-party-resources-checker"
                        ,   "w3c/tr-design"
                        ]
    }
,   "html-future":   {
        origin:         "github"
    ,   name:           "Future of HTML"
    ,   description:    "Discussion on the future of HTML"
    ,   repository:     [
                            "w3c/charter-html"
                        ]
    }
,   "webrtc":   {
        origin:         "github"
    ,   name:           "WebRTC specs"
    ,   description:    "Github activity on WebRTC specs"
    ,   repository:     [
                            "w3c/webrtc-pc"
                        ,   "w3c/mediacapture-main"
                        ,   "w3c/mediacapture-record"
                        ,   "w3c/mediacapture-image"
                        ,   "w3c/mediacapture-depth"
                        ,   "w3c/mediacapture-fromelement"
                        ,   "w3c/mediacapture-output"
                        ,   "w3c/webrtc-stats"
                        ,   "w3c/webrtc-screen-share"
                        ,   "w3c/mediacapture-worker"
                        ,   "w3c/webrtc-respec-ci"
                        ]
    }
,   "csvw":   {
        origin:         "github"
    ,   name:           "CSVW Specs"
    ,   description:    "Github activity on the CSV on the Web specs"
    ,   repository:     [
                            "w3c/csvw"
                        ]
    }
,   "dpub":   {
        origin:         "github"
    ,   name:           "DPUB documents"
    ,   description:    "Github activity around digital publishing"
    ,   repository:     [
                            "w3c/dpub",
                            "w3c/dpub-accessibility",
                            "w3c/dpub-annotation",
                            "w3c/dpub-content-and-markup",
                            "w3c/dpub-metadata",
                            "w3c/dpub-stem",
                            "w3c/dpub-validation",
                            "w3c/dpub-pwp",
                            "w3c/dpub-pwp-loc",
                            "w3c/dpub-pwp-arch",
                            "w3c/dpub-pwp-ucr"
                        ]
    }
,   "publ": {
        origin:      "github"
    ,   name:        "Publishing Working Group documents"
    ,   description: "Github activities around the Publishing on the Web WG specs"
    ,   repository:  [
                         "w3c/publ-wg",
                         "w3c/wpub",
                         "w3c/pwpub",
                         "w3c/epub4",
                         "w3c/dpub-aria-2.0",
                         "w3c/publ-a11y"
                     ]
    }
,   "poe": {
        origin:      "github"
    ,   name:        "POE Working Group documents"
    ,   description: "Github activity around the Permissions and Obligations Expression Working Group"
    ,   repository:  [
                         "w3c/poe"
                     ]
    }
,   "annotation":   {
        origin:         "github"
    ,   name:           "Web Annotations specs"
    ,   description:    "Github activity on Web Annotation specs"
    ,   repository:     [
                            "w3c/web-annotation",
                            "w3c/findtext"
                        ]
    }
,   "das":   {
        origin:         "github"
    ,   name:           "Device & Sensors specs"
    ,   description:    "Github activity on Device & Sensors Working Group specs"
    ,   repository:     [
                            "w3c/sensors"
                        ,   "w3c/ambient-light"
                        ,   "w3c/proximity"
                        ,   "w3c/vibration"
                        ,   "w3c/battery"
                        ,   "w3c/wake-lock"
                        ,   "w3c/html-media-capture"
                        ,   "w3c/devicesensors-wg"
                        ,   "w3c/gyroscope"
                        ,   "w3c/accelerometer"
                        ]
    }
};
<commit_msg>Add  webrtc-charter to repo list for webrtc<commit_after>
module.exports = {
    w3cmemes: {
        origin:         "W3CMemes"
    ,   name:           "W3CMemes"
    ,   description:    "The official news agency for the W3C community"
    }
,   w3cnews: {
        origin:         "W3C News"
    ,   name:           "W3C News"
    ,   description:    "The party line"
    }
,   "html-wg":  {
        origin:         "github"
    ,   name:           "HTML WG"
    ,   description:    "HTML Working Group work stream"
    ,   repository:     [
                            "w3c/html"
                        ,   "w3c/charter-html"
                        ,   "w3c/test-results"
                        ,   "w3c/dom"
                        ,   "w3c/aria-in-html"
                        ]
    }
,   wpt:  {
        origin:         "github"
    ,   name:           "WPT"
    ,   description:    "Web Platform Tests work stream"
    ,   repository:     [
                            "w3c/web-platform-tests"
                        ,   "w3c/wpt-runner"
                        ,   "w3c/test-results"
                        ,   "w3c/wpt-tools"
                        ,   "w3c/testharness.js"
                        ]
    }
,   "modern-tooling":   {
        origin:         "github"
    ,   name:           "Modern Tooling"
    ,   description:    "Work stream for the Modern Tooling project"
    ,   repository:     [
                            "w3c/echidna"
                        ,   "w3c/modern-tooling"
                        ,   "w3c/pheme"
                        ,   "w3c/midgard"
                        ,   "w3c/ash-nazg"
                        ,   "w3c/specberus"
                        ,   "w3c/respec"
                        ,   "w3c/respec-docs"
                        ,   "w3c/w3c-api"
                        ,   "w3c/developers"
                        ,   "w3c/third-party-resources-checker"
                        ,   "w3c/tr-design"
                        ]
    }
,   "html-future":   {
        origin:         "github"
    ,   name:           "Future of HTML"
    ,   description:    "Discussion on the future of HTML"
    ,   repository:     [
                            "w3c/charter-html"
                        ]
    }
,   "webrtc":   {
        origin:         "github"
    ,   name:           "WebRTC specs"
    ,   description:    "Github activity on WebRTC specs"
    ,   repository:     [
                            "w3c/webrtc-pc"
                        ,   "w3c/mediacapture-main"
                        ,   "w3c/mediacapture-record"
                        ,   "w3c/mediacapture-image"
                        ,   "w3c/mediacapture-depth"
                        ,   "w3c/mediacapture-fromelement"
                        ,   "w3c/mediacapture-output"
                        ,   "w3c/webrtc-stats"
                        ,   "w3c/webrtc-screen-share"
                        ,   "w3c/mediacapture-worker"
                        ,   "w3c/webrtc-charter"
                        ,   "w3c/webrtc-respec-ci"
                        ]
    }
,   "csvw":   {
        origin:         "github"
    ,   name:           "CSVW Specs"
    ,   description:    "Github activity on the CSV on the Web specs"
    ,   repository:     [
                            "w3c/csvw"
                        ]
    }
,   "dpub":   {
        origin:         "github"
    ,   name:           "DPUB documents"
    ,   description:    "Github activity around digital publishing"
    ,   repository:     [
                            "w3c/dpub",
                            "w3c/dpub-accessibility",
                            "w3c/dpub-annotation",
                            "w3c/dpub-content-and-markup",
                            "w3c/dpub-metadata",
                            "w3c/dpub-stem",
                            "w3c/dpub-validation",
                            "w3c/dpub-pwp",
                            "w3c/dpub-pwp-loc",
                            "w3c/dpub-pwp-arch",
                            "w3c/dpub-pwp-ucr"
                        ]
    }
,   "publ": {
        origin:      "github"
    ,   name:        "Publishing Working Group documents"
    ,   description: "Github activities around the Publishing on the Web WG specs"
    ,   repository:  [
                         "w3c/publ-wg",
                         "w3c/wpub",
                         "w3c/pwpub",
                         "w3c/epub4",
                         "w3c/dpub-aria-2.0",
                         "w3c/publ-a11y"
                     ]
    }
,   "poe": {
        origin:      "github"
    ,   name:        "POE Working Group documents"
    ,   description: "Github activity around the Permissions and Obligations Expression Working Group"
    ,   repository:  [
                         "w3c/poe"
                     ]
    }
,   "annotation":   {
        origin:         "github"
    ,   name:           "Web Annotations specs"
    ,   description:    "Github activity on Web Annotation specs"
    ,   repository:     [
                            "w3c/web-annotation",
                            "w3c/findtext"
                        ]
    }
,   "das":   {
        origin:         "github"
    ,   name:           "Device & Sensors specs"
    ,   description:    "Github activity on Device & Sensors Working Group specs"
    ,   repository:     [
                            "w3c/sensors"
                        ,   "w3c/ambient-light"
                        ,   "w3c/proximity"
                        ,   "w3c/vibration"
                        ,   "w3c/battery"
                        ,   "w3c/wake-lock"
                        ,   "w3c/html-media-capture"
                        ,   "w3c/devicesensors-wg"
                        ,   "w3c/gyroscope"
                        ,   "w3c/accelerometer"
                        ]
    }
};
<|endoftext|>


<commit_before>module.exports = (function () {
  var async = require('async');

  var PostsSeed = function (options) {
    this.logger = options.logger;
    this.Posts = options.db.qDefine('posts', {
      id: Number,
      author_id: Number,
      uuid: String,
      title: String,
      slug: String,
      markdown: String,
      html: String,
      featured: Number,
      page: Number,
      status: String,
      language: String,
      updated_by: Number,
      published_by: Number,
      created_by: Number,
      created_at: Number,
      updated_at: Number,
      published_at: Number
    });
    this.Users = options.db.qDefine('users', {
      uuid: Number,
      id: Number
    });
  };

  var defaultPosts = [
    {
      title: 'Texto principal',
      slug: 'texto-principal',
      markdown: '<< La innovación es lo que distingue a los ' +
      'líderes de los \nseguidores >>.- Steve Jobs',
      html: '
<< La innovación es lo que distingue a los ' +
      'líderes de los
seguidores >>.- Steve Jobs
',
      featured: false,
      page: false,
      status: 'published',
      language: 'en_US',
      created_at: Date.now(),
      updated_at: Date.now(),
      published_at: Date.now()
    }
  ];

  PostsSeed.prototype.firstUser = function (cb) {
    return this.Users.qOne().then(cb).fail(this.logger.onFatal);
  };

  PostsSeed.prototype.ifNonExistentPost = function (post,
                                                    existentCb,
                                                    successCb) {
    // do not override an existing post
    return this.Posts.qOne({
      slug: post.slug
    }).then(function (existingPost) {
      if (existingPost) {
        existentCb(post);
      }
      else {
        successCb(post);
      }
    });
  };

  PostsSeed.prototype.performQueries = function () {
    var self = this;

    return self.firstUser(function (user) {
      async.eachSeries(defaultPosts, function createPost(post, callback) {

        var postExists = function (post) {
          self.logger.info('post exists', post.title)
          return callback();
        };

        return self.ifNonExistentPost(post, postExists, function (post) {
          post.uuid = user.uuid;
          post.author_id = user.id;
          post.created_by = user.id;
          post.updated_by = user.id;
          post.published_by = user.id;
          return self.Posts.qCreate(post)
            .then(function (res) {
              self.logger.success('seeded post', res.title);
              callback();
            }).fail(callback);
        });
      }, function done(err) {
        if (err) {
          self.logger.onFatal(err);
        }
      });
    });
  };

  return PostsSeed;
})();
<commit_msg>Change data type for uuid<commit_after>module.exports = (function () {
  var async = require('async');

  var PostsSeed = function (options) {
    this.logger = options.logger;
    this.Posts = options.db.qDefine('posts', {
      id: Number,
      author_id: Number,
      uuid: String,
      title: String,
      slug: String,
      markdown: String,
      html: String,
      featured: Number,
      page: Number,
      status: String,
      language: String,
      updated_by: Number,
      published_by: Number,
      created_by: Number,
      created_at: Number,
      updated_at: Number,
      published_at: Number
    });
    this.Users = options.db.qDefine('users', {
      uuid: String,
      id: Number
    });
  };

  var defaultPosts = [
    {
      title: 'Texto principal',
      slug: 'texto-principal',
      markdown: '<< La innovación es lo que distingue a los ' +
      'líderes de los \nseguidores >>.- Steve Jobs',
      html: '
<< La innovación es lo que distingue a los ' +
      'líderes de los
seguidores >>.- Steve Jobs
',
      featured: false,
      page: false,
      status: 'published',
      language: 'en_US',
      created_at: Date.now(),
      updated_at: Date.now(),
      published_at: Date.now()
    }
  ];

  PostsSeed.prototype.firstUser = function (cb) {
    return this.Users.qOne().then(cb).fail(this.logger.onFatal);
  };

  PostsSeed.prototype.ifNonExistentPost = function (post,
                                                    existentCb,
                                                    successCb) {
    // do not override an existing post
    return this.Posts.qOne({
      slug: post.slug
    }).then(function (existingPost) {
      if (existingPost) {
        existentCb(post);
      }
      else {
        successCb(post);
      }
    });
  };

  PostsSeed.prototype.performQueries = function () {
    var self = this;

    return self.firstUser(function (user) {
      async.eachSeries(defaultPosts, function createPost(post, callback) {

        var postExists = function (post) {
          self.logger.info('post exists', post.title)
          return callback();
        };

        return self.ifNonExistentPost(post, postExists, function (post) {
          post.uuid = user.uuid;
          post.author_id = user.id;
          post.created_by = user.id;
          post.updated_by = user.id;
          post.published_by = user.id;
          return self.Posts.qCreate(post)
            .then(function (res) {
              self.logger.success('seeded post', res.title);
              callback();
            }).fail(callback);
        });
      }, function done(err) {
        if (err) {
          self.logger.onFatal(err);
        }
      });
    });
  };

  return PostsSeed;
})();
<|endoftext|>


<commit_before>'use strict'
import Koa from 'koa'
import middlewares from './middlewares'
import routes from './routes'
import connectDatabase from './utils/db'
import conf from './config'

/* eslint-disable */
require('manakin').global // output colors in Development
/* eslint-enable */
const app = new Koa()
const PORT = conf.get('port')

connectDatabase(conf.get('mongodb'))

app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.body = 'Protected resource, you need to authenticate the request'
    } else {
      throw err
    }
  })
})

app.use(middlewares())
app.use(routes())

// #### START APP ####
app.listen(PORT, () => {
  console.info(`App listening on localhost:${PORT}`)
})
<commit_msg>add status in protected resource handler<commit_after>'use strict'
import Koa from 'koa'
import middlewares from './middlewares'
import routes from './routes'
import connectDatabase from './utils/db'
import conf from './config'

/* eslint-disable */
require('manakin').global // output colors in Development
/* eslint-enable */
const app = new Koa()
const PORT = conf.get('port')

connectDatabase(conf.get('mongodb'))

app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401
      ctx.body = 'Protected resource, you need to authenticate the request'
    } else {
      throw err
    }
  })
})

app.use(middlewares())
app.use(routes())

// #### START APP ####
app.listen(PORT, () => {
  console.info(`App listening on localhost:${PORT}`)
})
<|endoftext|>


<commit_before>'use strict';

const CONFIG = require('./config');

const electron = require('electron');
const app = electron.app;

const YoutubeApi = require('./youtubeapi');
const Windows = require('./windows')(electron, CONFIG);
const server = require('./server');
const database = require('./database');

const isOnline = require('is-online');
const youtubeRegex = require('youtube-regex');

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
  Windows.openMainWindow();

  server.io.on('connection', (socket) => {
    socket.on('internet/reconnect', launchApp);

    let subscriptions = [];
    let playlist = require('./playlist');

    let videoPlaying = null;
    launchApp();

    socket.on('youtube/auth', () => {
      socket.emit('youtube/waiting');

      YoutubeApi.getAuthUrl((url) => {
        socket.emit('youtube/waitingforuser');
        Windows.openLogInWindow(url);
      });
    });

    socket.on('subscriptions/list', () => {
      if (subscriptions.length)
        return socket.emit('subscriptions/list', subscriptions);

      YoutubeApi.getSubscriptions((err, _subscriptions) => {
        if (err) {
          console.error(err);
        } else {
          subscriptions = _subscriptions;
          socket.emit('subscriptions/list', subscriptions);
        }
      });
    });

    // Video
    socket.on('video/start', (id) => {
      console.log('Video started: ', id);
      videoPlaying = id;
    });

    socket.on('video/pause', (id) => {
      console.log('Video paused: ', id);
    });

    socket.on('video/buffer', (id) => {
      console.log('Video buffering: ', id);
    });

    /* This method is called to play a video immediately */
    socket.on('video/play', playVideo);

    /* Put a video on the end of the playlist */
    socket.on('video/cue', (video) => {
      console.log('Cueing video: ', video.id);
      if (!playlist.length)
        socket.emit('video/cue', video.id);

      if (!playlist.contains(video.id)) {
        console.log('Pushing a video into the playlist (' + video.id + ')');
        playlist.push(video);
        socket.emit('playlist/update', playlist);
      }
    });

    /* Set a video as next to play */
    socket.on('video/next', (video) => {
      console.log('Set next video: ', video.id);
      if (!playlist.length)
        socket.emit('video/cue', video.id);

      if (!playlist.contains(video.id)) {
        playlist.setNext(video);
      }

      socket.emit('playlist/update', playlist);
    });

    /* When something is pasted, if it is a YouTube video, play it */
    socket.on('video/paste', (text) => {
      if (!youtubeRegex().test(text))
        return;

      let videoId = youtubeRegex().exec(text)[1];
      YoutubeApi.getVideo(videoId, function (err, theVideo) {
        if (err) return;
        playVideo(theVideo);
      });
    });

    socket.on('video/remove', (id) => {
      console.log('Remove video: ', id);
      removeVideo(id);
    })

    socket.on('video/end', (id) => {
      console.log('Video ended: ', id);
      removeVideo(id);
      playNextVideo();
    });

    function launchApp() {
      if (isOnline((err, online) => {
        if (err || !online) {
          return socket.emit('internet/notconnected');
        }

        YoutubeApi.tryStoredAccessToken((noValidAccessToken, token) => {
          if (noValidAccessToken) {
            socket.emit('youtube/notauthenticated');
          } else {
            socket.emit('youtube/callback', token);
          }
        });
      }));
    }

    function playVideo(video) {
      console.log('Play video: ', video.id);

      playlist.playNow(video);
      socket.emit('playlist/update', playlist);

      if (videoPlaying) {
        socket.emit('video/play', video.id);
      }
      else
        socket.emit('video/cue', video.id);
    }

    function playNextVideo() {
      if (!playlist.length) {
        videoPlaying = null;
        return;
      }

      if (videoPlaying === playlist[0].id) return;

      socket.emit('video/play', playlist[0].id);
      videoPlaying = playlist[0].id;
    }

    function removeVideo(id) {
      playlist.remove(id);
      socket.emit('video/remove');
      socket.emit('playlist/update', playlist);
    }
  });

  server.hapi.route({
    method: 'GET',
    path:'/youtube/callback',
    handler: function (request, reply) {
      server.io.emit('youtube/waiting');
      YoutubeApi.getToken(request.query.code, function (token) {
        server.io.emit('youtube/callback', token);

        Windows.closeLogInWindow();
      });
    }
  });
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    Windows.openMainWindow();
  }
});
<commit_msg>Fix a window issue<commit_after>'use strict';

const CONFIG = require('./config');

const electron = require('electron');
const app = electron.app;

const YoutubeApi = require('./youtubeapi');
const Windows = require('./windows')(electron, CONFIG);
const server = require('./server');
const database = require('./database');

const isOnline = require('is-online');
const youtubeRegex = require('youtube-regex');

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
  Windows.openMainWindow();

  server.io.on('connection', (socket) => {
    socket.on('internet/reconnect', launchApp);

    let subscriptions = [];
    let playlist = require('./playlist');

    let videoPlaying = null;
    launchApp();

    socket.on('youtube/auth', () => {
      socket.emit('youtube/waiting');

      YoutubeApi.getAuthUrl((url) => {
        socket.emit('youtube/waitingforuser');
        Windows.openLogInWindow(url);
      });
    });

    socket.on('subscriptions/list', () => {
      if (subscriptions.length)
        return socket.emit('subscriptions/list', subscriptions);

      YoutubeApi.getSubscriptions((err, _subscriptions) => {
        if (err) {
          console.error(err);
        } else {
          subscriptions = _subscriptions;
          socket.emit('subscriptions/list', subscriptions);
        }
      });
    });

    // Video
    socket.on('video/start', (id) => {
      console.log('Video started: ', id);
      videoPlaying = id;
    });

    socket.on('video/pause', (id) => {
      console.log('Video paused: ', id);
    });

    socket.on('video/buffer', (id) => {
      console.log('Video buffering: ', id);
    });

    /* This method is called to play a video immediately */
    socket.on('video/play', playVideo);

    /* Put a video on the end of the playlist */
    socket.on('video/cue', (video) => {
      console.log('Cueing video: ', video.id);
      if (!playlist.length)
        socket.emit('video/cue', video.id);

      if (!playlist.contains(video.id)) {
        console.log('Pushing a video into the playlist (' + video.id + ')');
        playlist.push(video);
        socket.emit('playlist/update', playlist);
      }
    });

    /* Set a video as next to play */
    socket.on('video/next', (video) => {
      console.log('Set next video: ', video.id);
      if (!playlist.length)
        socket.emit('video/cue', video.id);

      if (!playlist.contains(video.id)) {
        playlist.setNext(video);
      }

      socket.emit('playlist/update', playlist);
    });

    /* When something is pasted, if it is a YouTube video, play it */
    socket.on('video/paste', (text) => {
      if (!youtubeRegex().test(text))
        return;

      let videoId = youtubeRegex().exec(text)[1];
      YoutubeApi.getVideo(videoId, function (err, theVideo) {
        if (err) return;
        playVideo(theVideo);
      });
    });

    socket.on('video/remove', (id) => {
      console.log('Remove video: ', id);
      removeVideo(id);
    })

    socket.on('video/end', (id) => {
      console.log('Video ended: ', id);
      removeVideo(id);
      playNextVideo();
    });

    function launchApp() {
      if (isOnline((err, online) => {
        if (err || !online) {
          return socket.emit('internet/notconnected');
        }

        YoutubeApi.tryStoredAccessToken((noValidAccessToken, token) => {
          if (noValidAccessToken) {
            socket.emit('youtube/notauthenticated');
          } else {
            socket.emit('youtube/callback', token);
          }
        });
      }));
    }

    function playVideo(video) {
      console.log('Play video: ', video.id);

      playlist.playNow(video);
      socket.emit('playlist/update', playlist);

      if (videoPlaying) {
        socket.emit('video/play', video.id);
      }
      else
        socket.emit('video/cue', video.id);
    }

    function playNextVideo() {
      if (!playlist.length) {
        videoPlaying = null;
        return;
      }

      if (videoPlaying === playlist[0].id) return;

      socket.emit('video/play', playlist[0].id);
      videoPlaying = playlist[0].id;
    }

    function removeVideo(id) {
      playlist.remove(id);
      socket.emit('video/remove');
      socket.emit('playlist/update', playlist);
    }
  });

  server.hapi.route({
    method: 'GET',
    path:'/youtube/callback',
    handler: function (request, reply) {
      server.io.emit('youtube/waiting');
      YoutubeApi.getToken(request.query.code, function (token) {
        server.io.emit('youtube/callback', token);

        Windows.closeLogInWindow();
      });
    }
  });
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  Windows.activateWithNoOpenWindows();
});
<|endoftext|>


<commit_before>import THREE from 'three';
import 'three/examples/js/postprocessing/EffectComposer';
import 'three/examples/js/postprocessing/MaskPass';
import 'three/examples/js/postprocessing/ShaderPass';
import 'three/examples/js/postprocessing/RenderPass';
import 'three/examples/js/shaders/CopyShader';
import Stats from 'stats.js';
import dat from 'dat-gui';
import shaders from './shaders/fragment';
import vertexShaders from './shaders/vertex';
import textures from './textures';
import './styles/styles.less';

document.addEventListener('DOMContentLoaded', () => {
  const gui = new dat.GUI();
  const stats = new Stats();
  const container = document.createElement('div');
  const renderer = new THREE.WebGLRenderer();
  const composer = new THREE.EffectComposer(renderer);
  const scene = new THREE.Scene();
  let mesh;
  const shaderPasses = [];
  const guiModel = {
    shader1: null,
    shader2: null,
    shader3: null,
    param: new THREE.Vector3(1.0, 1.0, 0.0),
    shaders: ['none'],
    textures: textures,
    numberOfPasses: 1
  };

  container.classList.add('container');
  document.body.appendChild(container);
  const width = container.clientWidth;
  const height = container.clientHeight;
  const camera = new THREE.OrthographicCamera(
    width / -2,
    width / 2,
    height / 2,
    height / -2,
    1,
    100
  );

  function setupScene(textureId) {
    scene.remove(mesh);
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load('/textures/' + textureId, texture => {
      const plane = new THREE.PlaneGeometry(width, height);
      const shaderMaterial = new THREE.MeshBasicMaterial({
        map: texture
      });

      mesh = new THREE.Mesh(plane, shaderMaterial);
      scene.add(camera);
      scene.add(mesh);
    });
  }

  function refreshShaderPasses() {
    let shaderPass;

    composer.passes.splice(0, composer.passes.length);
    shaderPass = new THREE.RenderPass(scene, camera);
    composer.addPass(shaderPass);

    for (let i = 0; i < shaderPasses.length; i++) {
      if (!shaderPasses[i]) {
        continue;
      }

      for (let j = 0; j < guiModel.numberOfPasses; j++) {
        shaderPass = new THREE.ShaderPass(shaderPasses[i]);
        composer.addPass(shaderPass);
      }
    }

    shaderPass.renderToScreen = true;
  }

  function initGui() {
    [1, 2, 3].forEach((number) => {
      gui.add(guiModel, 'shader' + number, guiModel.shaders)
        .onChange(shaderName => {
          shaderPasses[number] = shaders[shaderName];
          refreshShaderPasses();
        });
    });

    gui.add(guiModel, 'textures', guiModel.textures).onChange(textureId => {
      setupScene(textureId);
    });

    gui.add(guiModel, 'numberOfPasses', 1, 5).step(1).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'x', -2, 2).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'y', -2, 2).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'z', 0, 5).step(1).onChange(refreshShaderPasses);

    stats.setMode(0);
    stats.domElement.classList.add('stats');
    container.appendChild(stats.domElement);
  }

  function loadShaders() {
    shaders.forEach((shader) => {
      guiModel.shaders.push(shader.key);
      shaders[shader.key] = createTHREEShader(
        vertexShaders[0].code,
        shader.code
      );
    });
  }

  function calcTextureOffsets(width, height, size) {
    const deltaX = 1.0 / width;
    const deltaY = 1.0 / height;
    const distance = Math.floor(size / 2);
    const offsets = [];

    for (let i = -distance; i <= distance; i++) {
      for (let j = -distance; j <= distance; j++) {
        offsets.push(new THREE.Vector2(i * deltaX, j * deltaY));
      }
    }

    return offsets;
  }

  function createTHREEShader(vertex, fragment) {
    return {
      vertexShader: vertex,
      fragmentShader: fragment,
      uniforms: {
        tDiffuse: {
          type: 't',
          value: null
        },
        offset3x3: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 3)
        },
        offset5x5: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 5)
        },
        offset7x7: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 7)
        },
        param: {
          type: 'v3',
          value: guiModel.param
        }
      }
    };
  }

  function render() {
    stats.begin();
    composer.render();
    stats.end();
    requestAnimationFrame(render);
  }

  camera.position.z = 10;
  renderer.setSize(width, height);
  container.appendChild(renderer.domElement);

  setupScene(textures[0]);
  loadShaders();
  initGui();
  refreshShaderPasses();
  render();
});
<commit_msg>Add default texture and shader<commit_after>import THREE from 'three';
import 'three/examples/js/postprocessing/EffectComposer';
import 'three/examples/js/postprocessing/MaskPass';
import 'three/examples/js/postprocessing/ShaderPass';
import 'three/examples/js/postprocessing/RenderPass';
import 'three/examples/js/shaders/CopyShader';
import Stats from 'stats.js';
import dat from 'dat-gui';
import shaders from './shaders/fragment';
import vertexShaders from './shaders/vertex';
import textures from './textures';
import './styles/styles.less';

document.addEventListener('DOMContentLoaded', () => {
  const gui = new dat.GUI();
  const stats = new Stats();
  const container = document.createElement('div');
  const renderer = new THREE.WebGLRenderer();
  const composer = new THREE.EffectComposer(renderer);
  const scene = new THREE.Scene();
  let mesh;
  const shaderPasses = [];
  const guiModel = {
    shader1: 'none',
    shader2: 'none',
    shader3: 'none',
    param: new THREE.Vector3(1.0, 1.0, 0.0),
    shaders: ['none'],
    texture: textures[0],
    textures: textures,
    numberOfPasses: 1
  };

  container.classList.add('container');
  document.body.appendChild(container);
  const width = container.clientWidth;
  const height = container.clientHeight;
  const camera = new THREE.OrthographicCamera(
    width / -2,
    width / 2,
    height / 2,
    height / -2,
    1,
    100
  );

  function setupScene(textureId) {
    scene.remove(mesh);
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load('/textures/' + textureId, texture => {
      const plane = new THREE.PlaneGeometry(width, height);
      const shaderMaterial = new THREE.MeshBasicMaterial({
        map: texture
      });

      mesh = new THREE.Mesh(plane, shaderMaterial);
      scene.add(camera);
      scene.add(mesh);
    });
  }

  function refreshShaderPasses() {
    let shaderPass;

    composer.passes.splice(0, composer.passes.length);
    shaderPass = new THREE.RenderPass(scene, camera);
    composer.addPass(shaderPass);

    for (let i = 0; i < shaderPasses.length; i++) {
      if (!shaderPasses[i]) {
        continue;
      }

      for (let j = 0; j < guiModel.numberOfPasses; j++) {
        shaderPass = new THREE.ShaderPass(shaderPasses[i]);
        composer.addPass(shaderPass);
      }
    }

    shaderPass.renderToScreen = true;
  }

  function initGui() {
    [1, 2, 3].forEach((number) => {
      gui.add(guiModel, 'shader' + number, guiModel.shaders)
        .onChange(shaderName => {
          shaderPasses[number] = shaders[shaderName];
          refreshShaderPasses();
        });
    });

    gui.add(guiModel, 'texture', guiModel.textures).onChange(textureId => {
      setupScene(textureId);
    });

    gui.add(guiModel, 'numberOfPasses', 1, 5).step(1).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'x', -2, 2).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'y', -2, 2).onChange(refreshShaderPasses);
    gui.add(guiModel.param, 'z', 0, 5).step(1).onChange(refreshShaderPasses);

    stats.setMode(0);
    stats.domElement.classList.add('stats');
    container.appendChild(stats.domElement);
  }

  function loadShaders() {
    shaders.forEach((shader) => {
      guiModel.shaders.push(shader.key);
      shaders[shader.key] = createTHREEShader(
        vertexShaders[0].code,
        shader.code
      );
    });
    guiModel.shader1 = './passthrough.gs';
    shaderPasses[0] = shaders['./passthrough.gs'];
  }

  function calcTextureOffsets(width, height, size) {
    const deltaX = 1.0 / width;
    const deltaY = 1.0 / height;
    const distance = Math.floor(size / 2);
    const offsets = [];

    for (let i = -distance; i <= distance; i++) {
      for (let j = -distance; j <= distance; j++) {
        offsets.push(new THREE.Vector2(i * deltaX, j * deltaY));
      }
    }

    return offsets;
  }

  function createTHREEShader(vertex, fragment) {
    return {
      vertexShader: vertex,
      fragmentShader: fragment,
      uniforms: {
        tDiffuse: {
          type: 't',
          value: null
        },
        offset3x3: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 3)
        },
        offset5x5: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 5)
        },
        offset7x7: {
          type: 'v2v',
          value: calcTextureOffsets(width, height, 7)
        },
        param: {
          type: 'v3',
          value: guiModel.param
        }
      }
    };
  }

  function render() {
    stats.begin();
    composer.render();
    stats.end();
    requestAnimationFrame(render);
  }

  camera.position.z = 10;
  renderer.setSize(width, height);
  container.appendChild(renderer.domElement);

  setupScene(textures[0]);
  loadShaders();
  initGui();
  refreshShaderPasses();
  render();
});
<|endoftext|>