<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Customer = mongoose.model('Customer'),
	_ = require('lodash'),
	Twitter = require('twitter'),
	config = require('../../config/config'),
	User = mongoose.model('User'),
	Country = mongoose.model('Country'),
	passport = require('passport');

/**
 * Create a Customer
 */
exports.create = function(req, res) {
	var customer = new Customer(req.body);
	customer.user = req.user;

	customer.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

exports.create2 = function(data, user) {

for (var i = data.items.length - 1; i >= 0; i--) {
		//Things[i]
	var customer = new Customer({videos: data.items[i], user: user});
	//customer.user = req.user;

	customer.save(function(err) {
		if (err) {
			console.log('pailas',err);

		} else {
			console.log('super');
		}
	}
	);

	}

};
/**
 * Show the current Customer
 */
exports.read = function(req, res) {
	res.jsonp(req.customer);
};

/**
 * Update a Customer
 */
exports.update = function(req, res) {
	var customer = req.customer ;

	customer = _.extend(customer , req.body);

	customer.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

/**
 * Delete an Customer
 */
exports.delete = function(req, res) {
	var customer = req.customer ;

	customer.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

/**
 * List of Customers
 */
 /*
exports.list = function(req, res) {
	Customer.find().sort('-created').populate('user', 'displayName').exec(function(err, customers) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customers);
		}
	});
};
*/

exports.list = function(req, res) {

	var sort;
	var sortObject = {};

	var count = req.query.count || 5;
	var page = req.query.page || 1;

	var filter = {
		filters : {
			mandatory : {
				contains: req.query.filter
			}
		}
	};

	var pagination = {
		start : (page - 1) * count,
		count: count
	};

	if(req.query.sorting){
		var sortKey = Object.keys(req.query.sorting)[0];
		var sortValue = req.query.sorting[sortKey];
		sortObject[sortValue] = sortKey;
	} else{
		sortObject['desc'] = '_id';
	}

	var sort = {
		sort: sortObject
	};

	Customer
		.find({user: req.user})
		.filter(filter)
		.order(sort)
		.page(pagination, function(err, customers){
				if(err){
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else{
					var country = [],
	tokens = [],
	videos = customers;

//User.find({provider: 'twitter'}, function(err, providerData){

        /*tokens = providerData;
        //console.dir(item);
        //console.log('que pasa ' + country[1].providerData.token);

        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: tokens[0].providerData.token,
  			access_token_secret: tokens[0].providerData.tokenSecret
			});

			client.get('/trends/available', function(err, payload){
			//console.log(payload);

			if(err){
				throw err;
			} */
		 	/*var b=0;
 	 		for (i = 0; i < payload.length; i++) {

    		if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){

       		country[b] = {'country': payload[i].country, 'woeid': payload[i].woeid};

      		b=b+1;
     		}

  			}*/

  			Country.find(function(err, country){
  				var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
            	console.log(country);
				socketio.sockets.emit('article.created', country); // emit an event for all connected clients
  			});

            //var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
            	//console.log(country);
			//	socketio.sockets.emit('article.created', country); // emit an event for all connected clients
					/*
				socketio.on('connection', function(socket) {
				console.log('esto llego');
				socket.on('countryenv', function(data) {
            		console.log('entro!!!' + data);

            	});
				});*/
				var item = { item1: 'Tweet dupiclate  or more than 140 characters',
							 item2: 'Tweet dupiclate  or more than 140 characters',
							 item3: 'Tweet dupiclate  or more than 140 characters'};
				for (var i = videos.results.length - 1; i >= 0; i--) {
					videos.results[i].videos.kind = (videos.results[i].videos.kind,item);
				}

				//customers.results = {};
				//customers.results = videos.results = customers.results[0].videos.items;

				//console.log(customers);
				//return customers;
				res.jsonp(videos);
				//return customers;

			//});
  			//});

						}
		});
};

/**
 * Customer middleware
 */
exports.customerByID = function(req, res, next, id) {
	Customer.findById(id).populate('user', 'displayName').exec(function(err, customer) {
		if (err) return next(err);
		if (! customer) return next(new Error('Failed to load Customer ' + id));
		req.customer = customer ;
		next();
	});
};

/**
 * Customer authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.customer.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};

//var country;

exports.countryTwitter = function(data, user, socket) {

	var country = '',
	params = '',
	tokens = [],
	i;

User.find({provider: 'twitter', _id: user}, function(err, providerData){

        tokens = providerData;
        //console.dir(item);
        //console.log(providerData.providerData.token);

        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});

        client.get('/trends/place',{id: data}, function(err, payload){
    	//console.log(payload[0].trends.length);
    	if(err){
				throw err;
			} else {
    	for (var i = 0 ; i < payload[0].trends.length; i++) {
                //mensaje.text(data[0].trends[i].name);

                country =  country + payload[0].trends[i].name + ' ';

              }
    		}
    	socket.emit('trendenv',country);
    	//country = payload;
    	//console.log(payload);
    	//console.log(country[0].trends);
    	//module.exports.myObj = country;

 		 });

    });

  //return tokens;
};

exports.sendTwitter = function(data, user, socket) {

	User.find({provider: 'twitter', _id: user}, function(err, providerData){
	var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});
     //console.log(providerData[1]+' data');
	client.post('statuses/update', {status: data },  function(error, data,response){

  				//if(error) throw error; h  º1GVGVGVGVGVGVGVBHGJHJKHJH
  				if(!error){
  					console.log('Tweet enviado',error);  // Tweet body.
  					socket.emit('mensagge','send');
  				}else{
  					socket.emit('mensagge',error);
  					console.log('error',error);
  					}
  				//console.log(response);
  				//console.log(response);  // Raw response object.

				});

  });

};

exports.twitterBucle = function (user){

	var trend = ' ';
	console.log(user);
	Country.find(function(err, country){

  		console.log(country[0].country[3].woeid);
  		User.find({provider: 'twitter', _id: user}, function(err, providerData){
  			//console.log('EMPEZO');
  			var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});

			var x = 0,
				y = 0,
				z = 0;
				//console.log(y);
			setInterval(function() {

				if (x < country[0].country.length) {
          client.get('/trends/place',{id: country[0].country[x].woeid}, function(err, payload){
          //client.get('/trends/place',{id: 23424757}, function(err, payload){
            //console.log(payload[0].trends[1].name);
            //console.log(payload[0]);
            if(!err){

            //console.log(payload[0].trends[1].name);  // Tweet body.
            for (var i = 0 ; i < 4; i++) {
                    //mensaje.text(data[0].trends[i].name);

                    trend =  trend + payload[0].trends[i].name + ' ';

                    }
              //client.post('statuses/update', {status: payload[0].trends[1].name },  function(error, data,response){
              //console.log(trend);

              Customer.find({user: user}, function(err, links){
              if (x<links.length){
                  trend = trend + ' http://youtu.be/' + links[x].videos.id.videoId;
                  }else{
                    //trend = trend + ' http://youtu.be/' + links[30].videos.id.videoId;
                    trend = trend + ' http://trendmedia.herokuapp.com';
                  }
                 // console.log(' post ', trend);
              client.post('statuses/update', {status: trend },  function(error, data,response){

                //if(error) throw error; h  º1GVGVGVGVGVGVGVBHGJHJKHJH
                if(!error){
                  //console.log('Tweet enviado',error);  // Tweet body.
                  y=0;
                  //continue
                }else{

                  console.log('error post',error);

                  //continue

                  }
                //console.log(response);
                //console.log(response);  // Raw response object.
                trend = '';

              });
              });
            //y = Math.floor(Math.random() * (35-30+1)) + 30;

          }else{

            //console.log('error get',err);
            y=0;

            }
          });
        }

        //else return;

	    		if(x===country[0].country.length){
	    			x=0;
	    		}

	    		x++;
    			//console.log(x);
			}, 5000 /* (Math.floor(Math.random() * (30-20+1)) + 20)*/);

		});
	});
};
/*
exports.countryTwitter = function(req, res) {
//console.info('XXXXX ' + TwitterStrategy);

//console.log('kkkkkk' + users);

//User.find({provider: 'twitter'}).limit(1);

var country = [],
	tokens = [],
	i;

User.find({provider: 'twitter'}, function(err, providerData){

        //console.log('Find: ' + providerData);
        tokens = providerData;
        //console.dir(item);
        //console.log('que pasa ' + country[1].providerData.token);
        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: tokens[1].providerData.token,
  			access_token_secret: tokens[1].providerData.tokenSecret
			});

			client.get('/trends/available', function(err, payload){

		 	var b=0;
 	 		for (i = 0; i < payload.length; i++) {

    		if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){

       		country[b] = {"country": payload[i].country, "woeid": payload[i].woeid};
    //country.country[i] = {'country' : payload[i].country, 'woeid' : payload[i].woeid};
    //country.woeid[i] = payload[i].woeid;
      		b=b+1;
     		}

  			}
            console.info(country);
  			res.jsonp(country);
			});
  			});

};*/<commit_msg>'minn'<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Customer = mongoose.model('Customer'),
	_ = require('lodash'),
	Twitter = require('twitter'),
	config = require('../../config/config'),
	User = mongoose.model('User'),
	Country = mongoose.model('Country'),
	passport = require('passport');

/**
 * Create a Customer
 */
exports.create = function(req, res) {
	var customer = new Customer(req.body);
	customer.user = req.user;

	customer.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

exports.create2 = function(data, user) {

for (var i = data.items.length - 1; i >= 0; i--) {
		//Things[i]
	var customer = new Customer({videos: data.items[i], user: user});
	//customer.user = req.user;

	customer.save(function(err) {
		if (err) {
			console.log('pailas',err);

		} else {
			console.log('super');
		}
	}
	);

	}

};
/**
 * Show the current Customer
 */
exports.read = function(req, res) {
	res.jsonp(req.customer);
};

/**
 * Update a Customer
 */
exports.update = function(req, res) {
	var customer = req.customer ;

	customer = _.extend(customer , req.body);

	customer.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

/**
 * Delete an Customer
 */
exports.delete = function(req, res) {
	var customer = req.customer ;

	customer.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customer);
		}
	});
};

/**
 * List of Customers
 */
 /*
exports.list = function(req, res) {
	Customer.find().sort('-created').populate('user', 'displayName').exec(function(err, customers) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(customers);
		}
	});
};
*/

exports.list = function(req, res) {

	var sort;
	var sortObject = {};

	var count = req.query.count || 5;
	var page = req.query.page || 1;

	var filter = {
		filters : {
			mandatory : {
				contains: req.query.filter
			}
		}
	};

	var pagination = {
		start : (page - 1) * count,
		count: count
	};

	if(req.query.sorting){
		var sortKey = Object.keys(req.query.sorting)[0];
		var sortValue = req.query.sorting[sortKey];
		sortObject[sortValue] = sortKey;
	} else{
		sortObject['desc'] = '_id';
	}

	var sort = {
		sort: sortObject
	};

	Customer
		.find({user: req.user})
		.filter(filter)
		.order(sort)
		.page(pagination, function(err, customers){
				if(err){
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else{
					var country = [],
	tokens = [],
	videos = customers;

//User.find({provider: 'twitter'}, function(err, providerData){

        /*tokens = providerData;
        //console.dir(item);
        //console.log('que pasa ' + country[1].providerData.token);

        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: tokens[0].providerData.token,
  			access_token_secret: tokens[0].providerData.tokenSecret
			});

			client.get('/trends/available', function(err, payload){
			//console.log(payload);

			if(err){
				throw err;
			} */
		 	/*var b=0;
 	 		for (i = 0; i < payload.length; i++) {

    		if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){

       		country[b] = {'country': payload[i].country, 'woeid': payload[i].woeid};

      		b=b+1;
     		}

  			}*/

  			Country.find(function(err, country){
  				var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
            	console.log(country);
				socketio.sockets.emit('article.created', country); // emit an event for all connected clients
  			});

            //var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
            	//console.log(country);
			//	socketio.sockets.emit('article.created', country); // emit an event for all connected clients
					/*
				socketio.on('connection', function(socket) {
				console.log('esto llego');
				socket.on('countryenv', function(data) {
            		console.log('entro!!!' + data);

            	});
				});*/
				var item = { item1: 'Tweet dupiclate  or more than 140 characters',
							 item2: 'Tweet dupiclate  or more than 140 characters',
							 item3: 'Tweet dupiclate  or more than 140 characters'};
				for (var i = videos.results.length - 1; i >= 0; i--) {
					videos.results[i].videos.kind = (videos.results[i].videos.kind,item);
				}

				//customers.results = {};
				//customers.results = videos.results = customers.results[0].videos.items;

				//console.log(customers);
				//return customers;
				res.jsonp(videos);
				//return customers;

			//});
  			//});

						}
		});
};

/**
 * Customer middleware
 */
exports.customerByID = function(req, res, next, id) {
	Customer.findById(id).populate('user', 'displayName').exec(function(err, customer) {
		if (err) return next(err);
		if (! customer) return next(new Error('Failed to load Customer ' + id));
		req.customer = customer ;
		next();
	});
};

/**
 * Customer authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.customer.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};

//var country;

exports.countryTwitter = function(data, user, socket) {

	var country = '',
	params = '',
	tokens = [],
	i;

User.find({provider: 'twitter', _id: user}, function(err, providerData){

        tokens = providerData;
        //console.dir(item);
        //console.log(providerData.providerData.token);

        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});

        client.get('/trends/place',{id: data}, function(err, payload){
    	//console.log(payload[0].trends.length);
    	if(err){
				throw err;
			} else {
    	for (var i = 0 ; i < payload[0].trends.length; i++) {
                //mensaje.text(data[0].trends[i].name);

                country =  country + payload[0].trends[i].name + ' ';

              }
    		}
    	socket.emit('trendenv',country);
    	//country = payload;
    	//console.log(payload);
    	//console.log(country[0].trends);
    	//module.exports.myObj = country;

 		 });

    });

  //return tokens;
};

exports.sendTwitter = function(data, user, socket) {

	User.find({provider: 'twitter', _id: user}, function(err, providerData){
	var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});
     //console.log(providerData[1]+' data');
	client.post('statuses/update', {status: data },  function(error, data,response){

  				//if(error) throw error; h  º1GVGVGVGVGVGVGVBHGJHJKHJH
  				if(!error){
  					console.log('Tweet enviado',error);  // Tweet body.
  					socket.emit('mensagge','send');
  				}else{
  					socket.emit('mensagge',error);
  					console.log('error',error);
  					}
  				//console.log(response);
  				//console.log(response);  // Raw response object.

				});

  });

};

exports.twitterBucle = function (user){

	var trend = ' ';
	console.log(user);
	Country.find(function(err, country){

  		console.log(country[0].country[3].woeid);
  		User.find({provider: 'twitter', _id: user}, function(err, providerData){
  			//console.log('EMPEZO');
  			var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: providerData[0].providerData.token,
  			access_token_secret: providerData[0].providerData.tokenSecret
			});

			var x = 0,
				y = 0,
				z = 0;
				//console.log(y);
			setInterval(function() {

				if (x < country[0].country.length) {
          client.get('/trends/place',{id: country[0].country[x].woeid}, function(err, payload){
          //client.get('/trends/place',{id: 23424757}, function(err, payload){
            //console.log(payload[0].trends[1].name);
            //console.log(payload[0]);
            if(!err){

            //console.log(payload[0].trends[1].name);  // Tweet body.
            for (var i = 0 ; i < 4; i++) {
                    //mensaje.text(data[0].trends[i].name);

                    trend =  trend + payload[0].trends[i].name + ' ';

                    }
              //client.post('statuses/update', {status: payload[0].trends[1].name },  function(error, data,response){
              //console.log(trend);

              Customer.find({user: user}, function(err, links){
              if (x<links.length){
                  trend = trend + ' http://trendmedia.herokuapp.com' + ' http://youtu.be/' + links[x].videos.id.videoId;
                  }else{
                    //trend = trend + ' http://youtu.be/' + links[30].videos.id.videoId;
                    trend = trend + ' http://trendmedia.herokuapp.com';
                  }
                 // console.log(' post ', trend);
              client.post('statuses/update', {status: trend },  function(error, data,response){

                //if(error) throw error; h  º1GVGVGVGVGVGVGVBHGJHJKHJH
                if(!error){
                  //console.log('Tweet enviado',error);  // Tweet body.
                  y=0;
                  //continue
                }else{

                  //console.log('error post',error);
                  y=0;
                  //continue

                  }

                //console.log(response);
                //console.log(response);  // Raw response object.
                trend = '';

              });

              client.post('statuses/update', {status: ' http://trendmedia.herokuapp.com' },  function(error, data,response){

                //if(error) throw error; h  º1GVGVGVGVGVGVGVBHGJHJKHJH
                if(!error){
                  //console.log('Tweet enviado',error);  // Tweet body.
                  y=0;
                  //continue
                }else{

                  //console.log('error post',error);
                  y=0;
                  //continue

                  }

                //console.log(response);
                //console.log(response);  // Raw response object.
                trend = '';

              });
              });
            //y = Math.floor(Math.random() * (35-30+1)) + 30;

          }else{

            //console.log('error get',err);
            y=0;

            }
          });
        }

        //else return;

	    		if(x===country[0].country.length){
	    			x=0;
	    		}

	    		x++;
    			//console.log(x);
			}, 5000 /* (Math.floor(Math.random() * (30-20+1)) + 20)*/);

		});
	});
};
/*
exports.countryTwitter = function(req, res) {
//console.info('XXXXX ' + TwitterStrategy);

//console.log('kkkkkk' + users);

//User.find({provider: 'twitter'}).limit(1);

var country = [],
	tokens = [],
	i;

User.find({provider: 'twitter'}, function(err, providerData){

        //console.log('Find: ' + providerData);
        tokens = providerData;
        //console.dir(item);
        //console.log('que pasa ' + country[1].providerData.token);
        var client = new Twitter({
  			consumer_key: config.twitter.clientID,
  			consumer_secret: config.twitter.clientSecret,
  			access_token_key: tokens[1].providerData.token,
  			access_token_secret: tokens[1].providerData.tokenSecret
			});

			client.get('/trends/available', function(err, payload){

		 	var b=0;
 	 		for (i = 0; i < payload.length; i++) {

    		if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){

       		country[b] = {"country": payload[i].country, "woeid": payload[i].woeid};
    //country.country[i] = {'country' : payload[i].country, 'woeid' : payload[i].woeid};
    //country.woeid[i] = payload[i].woeid;
      		b=b+1;
     		}

  			}
            console.info(country);
  			res.jsonp(country);
			});
  			});

};*/<|endoftext|>


<commit_before>import Controller from '@ember/controller';
export default Controller.extend({
  actions: {
    save() {
      this.set('isLoading', true);
      this.get('model.speaker.sessions').addObject(this.get('model.session'));
      this.get('model.session.speakers').addObject(this.get('model.speaker'));

      this.get('model.session').save()
        .then(() => {
          this.get('model.speaker').save()
            .then(() => {
              this.get('notify').success(this.get('l10n').t('Your session has been saved'));
              this.transitionToRoute('events.view.sessions', this.get('model.event.id'));
            });
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    }
  }
});
<commit_msg>fix: Show error message for speakers creation<commit_after>import Controller from '@ember/controller';
export default Controller.extend({
  actions: {
    save() {
      this.set('isLoading', true);
      this.get('model.speaker.sessions').addObject(this.get('model.session'));
      this.get('model.session.speakers').addObject(this.get('model.speaker'));

      this.get('model.session').save()
        .then(() => {
          this.get('model.speaker').save()
            .then(() => {
              this.get('notify').success(this.get('l10n').t('Your session has been saved'));
              this.transitionToRoute('events.view.sessions', this.get('model.event.id'));
            })
            .catch(() => {
              this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
            });
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    }
  }
});
<|endoftext|>


<commit_before>// @flow strict

import * as React from 'react';
import { View } from 'react-native';
import { createFragmentContainer, graphql } from '@kiwicom/mobile-relay';
import idx from 'idx';
import {
  withNavigation,
  type NavigationType,
} from '@kiwicom/mobile-navigation';
import {
  TouchableWithoutFeedback,
  Dimensions,
  Device,
} from '@kiwicom/mobile-shared';

import { type RoomConfigurationType } from '../../HotelsContext';
import SingleHotelContext from '../../navigation/singleHotel/SingleHotelContext';
import HotelDetailPreview from '../hotelDetailPreview/HotelDetailPreview';
import type { HotelSwipeItem as HotelSwipeItemData } from './__generated__/HotelSwipeItem.graphql';

type PropsWithContext = {|
  ...Props,
  +deviceWidth: number,
  +setHotelId: (hotelId: string) => void,
  +hotelId: string,
  +checkin: Date,
  +checkout: Date,
  +roomsConfiguration: RoomConfigurationType,
|};

export class HotelSwipeItemWithContext extends React.Component<
  PropsWithContext,
> {
  openSingleHotel = (hotelId: string) => {
    this.props.navigation.navigate('SingleHotel', {
      hotelId,
      checkin: this.props.checkin,
      checkout: this.props.checkout,
      roomsConfiguration: this.props.roomsConfiguration,
    });
  };

  isNarrowLayout = () => {
    return this.props.deviceWidth < Device.DEVICE_THRESHOLD;
  };

  handlePress = () => {
    const { data } = this.props;
    const id = idx(data, _ => _.hotelId);

    if (id != null) {
      this.isNarrowLayout()
        ? this.openSingleHotel(id)
        : this.props.setHotelId(id);
    }
  };

  render = () => {
    const { width, data } = this.props;
    const name = idx(data, _ => _.name);
    const price = idx(data, _ => _.price);
    const thumbnailUrl = idx(data, _ => _.mainPhoto.thumbnailUrl);
    const stars = idx(data, _ => _.rating.stars);
    const score = idx(data, _ => _.review.score);
    return (
      <TouchableWithoutFeedback onPress={this.handlePress}>
        <View style={{ width }}>
          <HotelDetailPreview
            name={name}
            price={price}
            thumbnailUrl={thumbnailUrl}
            stars={stars}
            score={score}
          />
        </View>
      </TouchableWithoutFeedback>
    );
  };
}

type Props = {|
  +width: number,
  +navigation: NavigationType,
  +data: ?HotelSwipeItemData,
|};

class HotelSwipeItem extends React.Component<Props> {
  renderDimensions = ({ width }) => (
    <SingleHotelContext.Consumer>
      {this.renderSingleHotelContext(width)}
    </SingleHotelContext.Consumer>
  );

  renderSingleHotelContext = (width: number) => ({
    setHotelId,
    hotelId,
    checkin,
    checkout,
    roomsConfiguration,
  }) => (
    <HotelSwipeItemWithContext
      {...this.props}
      setHotelId={setHotelId}
      hotelId={hotelId}
      checkin={checkin}
      checkout={checkout}
      roomsConfiguration={roomsConfiguration}
      deviceWidth={width}
    />
  );

  render() {
    return <Dimensions.Consumer>{this.renderDimensions}</Dimensions.Consumer>;
  }
}

export default createFragmentContainer(
  withNavigation(HotelSwipeItem),
  graphql`
    fragment HotelSwipeItem on AllHotelsInterface {
      hotelId
      name
      price {
        currency
        amount
      }
      mainPhoto {
        thumbnailUrl
      }
      rating {
        stars
      }
      review {
        score
      }
    }
  `,
);
<commit_msg>Hotels: Set hotel id to context in all hotel map<commit_after>// @flow strict

import * as React from 'react';
import { View } from 'react-native';
import { createFragmentContainer, graphql } from '@kiwicom/mobile-relay';
import idx from 'idx';
import {
  withNavigation,
  type NavigationType,
} from '@kiwicom/mobile-navigation';
import {
  TouchableWithoutFeedback,
  Dimensions,
  Device,
} from '@kiwicom/mobile-shared';

import { type RoomConfigurationType } from '../../HotelsContext';
import SingleHotelContext from '../../navigation/singleHotel/SingleHotelContext';
import HotelDetailPreview from '../hotelDetailPreview/HotelDetailPreview';
import type { HotelSwipeItem as HotelSwipeItemData } from './__generated__/HotelSwipeItem.graphql';

type PropsWithContext = {|
  ...Props,
  +deviceWidth: number,
  +setHotelId: (hotelId: string) => void,
  +hotelId: string,
  +checkin: Date,
  +checkout: Date,
  +roomsConfiguration: RoomConfigurationType,
|};

export class HotelSwipeItemWithContext extends React.Component<
  PropsWithContext,
> {
  openSingleHotel = (hotelId: string) => {
    this.props.setHotelId(hotelId);
    this.props.navigation.navigate('SingleHotel', {
      hotelId,
      checkin: this.props.checkin,
      checkout: this.props.checkout,
      roomsConfiguration: this.props.roomsConfiguration,
    });
  };

  isNarrowLayout = () => {
    return this.props.deviceWidth < Device.DEVICE_THRESHOLD;
  };

  handlePress = () => {
    const { data } = this.props;
    const id = idx(data, _ => _.hotelId);

    if (id != null) {
      this.isNarrowLayout()
        ? this.openSingleHotel(id)
        : this.props.setHotelId(id);
    }
  };

  render = () => {
    const { width, data } = this.props;
    const name = idx(data, _ => _.name);
    const price = idx(data, _ => _.price);
    const thumbnailUrl = idx(data, _ => _.mainPhoto.thumbnailUrl);
    const stars = idx(data, _ => _.rating.stars);
    const score = idx(data, _ => _.review.score);
    return (
      <TouchableWithoutFeedback onPress={this.handlePress}>
        <View style={{ width }}>
          <HotelDetailPreview
            name={name}
            price={price}
            thumbnailUrl={thumbnailUrl}
            stars={stars}
            score={score}
          />
        </View>
      </TouchableWithoutFeedback>
    );
  };
}

type Props = {|
  +width: number,
  +navigation: NavigationType,
  +data: ?HotelSwipeItemData,
|};

class HotelSwipeItem extends React.Component<Props> {
  renderDimensions = ({ width }) => (
    <SingleHotelContext.Consumer>
      {this.renderSingleHotelContext(width)}
    </SingleHotelContext.Consumer>
  );

  renderSingleHotelContext = (width: number) => ({
    setHotelId,
    hotelId,
    checkin,
    checkout,
    roomsConfiguration,
  }) => (
    <HotelSwipeItemWithContext
      {...this.props}
      setHotelId={setHotelId}
      hotelId={hotelId}
      checkin={checkin}
      checkout={checkout}
      roomsConfiguration={roomsConfiguration}
      deviceWidth={width}
    />
  );

  render() {
    return <Dimensions.Consumer>{this.renderDimensions}</Dimensions.Consumer>;
  }
}

export default createFragmentContainer(
  withNavigation(HotelSwipeItem),
  graphql`
    fragment HotelSwipeItem on AllHotelsInterface {
      hotelId
      name
      price {
        currency
        amount
      }
      mainPhoto {
        thumbnailUrl
      }
      rating {
        stars
      }
      review {
        score
      }
    }
  `,
);
<|endoftext|>


<commit_before>import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { showOnboardingOnce } from '../actions/onboarding';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';

const { localeData, messages } = getLocale();
addLocaleData(localeData);

export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);

// load custom emojis
store.dispatch(fetchCustomEmojis());

export default class Mastodon extends React.PureComponent {

  static propTypes = {
    locale: PropTypes.string.isRequired,
  };

  componentDidMount() {
    this.disconnect = store.dispatch(connectUserStream());

    // Desktop notifications
    // Ask after 1 minute
    if (typeof window.Notification !== 'undefined' && Notification.permission === 'default') {
      window.setTimeout(() => Notification.requestPermission(), 60 * 1000);
    }

    // Protocol handler
    // Ask after 5 minutes
    if (typeof navigator.registerProtocolHandler !== 'undefined') {
      const handlerUrl = window.location.protocol + '//' + window.location.host + '/intent?uri=%s';
      window.setTimeout(() => navigator.registerProtocolHandler('web+mastodon', handlerUrl, 'Mastodon'), 5 * 60 * 1000);
    }

    store.dispatch(showOnboardingOnce());
  }

  componentWillUnmount () {
    if (this.disconnect) {
      this.disconnect();
      this.disconnect = null;
    }
  }

  render () {
    const { locale } = this.props;

    return (
      <IntlProvider locale={locale} messages={messages}>
        <Provider store={store}>
          <BrowserRouter basename='/web'>
            <ScrollContext>
              <Route path='/' component={UI} />
            </ScrollContext>
          </BrowserRouter>
        </Provider>
      </IntlProvider>
    );
  }

}
<commit_msg>Remove protocol handler registration (#8127)<commit_after>import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { showOnboardingOnce } from '../actions/onboarding';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';

const { localeData, messages } = getLocale();
addLocaleData(localeData);

export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);

// load custom emojis
store.dispatch(fetchCustomEmojis());

export default class Mastodon extends React.PureComponent {

  static propTypes = {
    locale: PropTypes.string.isRequired,
  };

  componentDidMount() {
    this.disconnect = store.dispatch(connectUserStream());

    // Desktop notifications
    // Ask after 1 minute
    if (typeof window.Notification !== 'undefined' && Notification.permission === 'default') {
      window.setTimeout(() => Notification.requestPermission(), 60 * 1000);
    }

    store.dispatch(showOnboardingOnce());
  }

  componentWillUnmount () {
    if (this.disconnect) {
      this.disconnect();
      this.disconnect = null;
    }
  }

  render () {
    const { locale } = this.props;

    return (
      <IntlProvider locale={locale} messages={messages}>
        <Provider store={store}>
          <BrowserRouter basename='/web'>
            <ScrollContext>
              <Route path='/' component={UI} />
            </ScrollContext>
          </BrowserRouter>
        </Provider>
      </IntlProvider>
    );
  }

}
<|endoftext|>


<commit_before>const randomize = require('randomatic');
const { dbMiddleware } = require('~/database');
const { acceptValidator } = require('~/requestValidators');
const authenticator = require('~/authenticator');

module.exports = (router) => {
  router.post(
    '/devices/:id',
    acceptValidator('application/json'),
    // TODO bodySchemaValidator(putDeviceSchema, true),
    dbMiddleware(),
    authenticator(true),
    async (ctx) => {
      const [item] = await ctx.state.db.query(
        'SELECT userId FROM trackingDevice WHERE id = ?',
        [ctx.request.body.name, ctx.params.id],
      );

      if (!item) {
        ctx.status = 404;
      } else if (!ctx.state.user.isAdmin && item.userId !== ctx.state.user.id) {
        ctx.status = 403;
      } else {
        const { name, maxCount, maxAge, regenerateToken } = ctx.request.body;
        let token;

        if (regenerateToken) {
          token = randomize('Aa0', 8);
        }

        await ctx.state.db.query(
          `UPDATE trackingDevice SET name = ?, maxCount = ?, maxAge = ?${regenerateToken ? ', token = ?' : ''} WHERE id = ?`,
          [name, maxCount, maxAge, ...regenerateToken ? [token] : [], ctx.params.id],
        );

        if (maxAge) {
          await ctx.state.db.query(
            'DELETE FROM trackingPoint WHERE deviceId = ? AND TIMESTAMPDIFF(SECOND(createdAt, now())) > ?',
            [ctx.params.id, maxAge],
          );
        }

        if (maxCount) {
          await ctx.state.db.query(
            'DELETE t FROM trackingPoint AS t JOIN (SELECT id FROM trackingPoint WHERE deviceId = ? ORDER BY id DESC OFFSET ?) tlimit ON t.id = tlimit.id',
            [ctx.params.id, maxCount + 1],
          );
        }

        ctx.body = { token };
      }
    },
  );
};
<commit_msg>fixed device put<commit_after>const randomize = require('randomatic');
const { dbMiddleware } = require('~/database');
const { acceptValidator } = require('~/requestValidators');
const authenticator = require('~/authenticator');

module.exports = (router) => {
  router.put(
    '/devices/:id',
    acceptValidator('application/json'),
    // TODO bodySchemaValidator(putDeviceSchema, true),
    dbMiddleware(),
    authenticator(true),
    async (ctx) => {
      const [item] = await ctx.state.db.query(
        'SELECT userId FROM trackingDevice WHERE id = ?',
        [ctx.params.id],
      );

      if (!item) {
        ctx.status = 404;
      } else if (!ctx.state.user.isAdmin && item.userId !== ctx.state.user.id) {
        ctx.status = 403;
      } else {
        const { name, maxCount, maxAge, regenerateToken } = ctx.request.body;
        let token;

        if (regenerateToken) {
          token = randomize('Aa0', 8);
        }

        await ctx.state.db.query(
          `UPDATE trackingDevice SET name = ?, maxCount = ?, maxAge = ?${regenerateToken ? ', token = ?' : ''} WHERE id = ?`,
          [name, maxCount, maxAge, ...regenerateToken ? [token] : [], ctx.params.id],
        );

        if (maxAge) {
          await ctx.state.db.query(
            'DELETE FROM trackingPoint WHERE deviceId = ? AND TIMESTAMPDIFF(SECOND, createdAt, now()) > ?',
            [ctx.params.id, maxAge],
          );
        }

        if (maxCount) {
          await ctx.state.db.query(
            `DELETE t FROM trackingPoint AS t
              JOIN (SELECT id FROM trackingPoint WHERE deviceId = ? ORDER BY id DESC LIMIT 18446744073709551615, ?) tlimit
                ON t.id = tlimit.id`,
            [ctx.params.id, maxCount + 1],
          );
        }

        ctx.body = { token };
      }
    },
  );
};
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';

    angular
        .module('cogeoApp')
        .factory('cogeoWebRtc', cogeoWebRtc);

    cogeoWebRtc.$inject = [
        'CONFIG',
        '$window',
        'cozenEnhancedLogs',
        'directMessagesFactory',
        '$rootScope',
        'cozenFloatingFeedFactory',
        'statusFactory'
    ];

    function cogeoWebRtc(CONFIG, $window, cozenEnhancedLogs, directMessagesFactory, $rootScope, cozenFloatingFeedFactory,
                         statusFactory) {

        // Private data
        var peer;
        var peerId;
        var mediaConnection;
        var mediaStream;

        // Subscribe to current user status change
        $rootScope.$on('statusFactoryChanged', function ($event) {
            sendUpdateStatusMessage(statusFactory.getCurrentUserStatus().index);
        });

        // Listener called when the user wish to start a call with a friend
        $rootScope.$on('cogeoWebRtc:callFriend', function ($event, $eventData) {

            // Try to get the media stream
            getMediaStream(true, true, function () {
                makeCall($eventData);
            });
        });

        // Listener called when the user wish to start a call audio with a friend
        $rootScope.$on('cogeoWebRtc:callFriendAudio', function ($event, $eventData) {

            // Try to get the media stream
            getMediaStream(true, false, function () {
                makeCall($eventData);
            });
        });

        // Listener called when the user wish to stop the call for a friend
        $rootScope.$on('cogeoWebRtc:stopCallFriend', function ($event, $eventData) {
            var connection = searchConnection($eventData.friend);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'stopCallFriend',
                    username: $eventData.friend
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called stop for friend', $eventData.friend);
            }
        });

        // Listener called when the user accept the call
        $rootScope.$on('cogeoWebRtc:answerCall', function ($event, $eventData) {

            // Send a message to tell the other user to show his own stream
            var connection = searchConnection($eventData.username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'showFriendStream',
                    username: $eventData.username,
                    stream  : mediaStream
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called accepted for friend', $eventData.username);
            }

            // Start the media stream
            mediaConnection.answer(mediaStream);
            cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'Call answered');
        });

        // Listener called whe the user refuse the call
        $rootScope.$on('cogeoWebRtc:refuseCall', function ($event, $eventData) {
            var connection = searchConnection($eventData.username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'refuseCallFriend',
                    username: $eventData.username
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called refused for friend', $eventData.username);
            }
        });

        return {
            createPeer               : createPeer,
            createPeerBot            : createPeerBot,
            connectFriends           : connectFriends,
            connectionSend           : connectionSend,
            destroyPeer              : destroyPeer,
            searchConnection         : searchConnection,
            getMediaStream           : getMediaStream,
            listenData               : listenData,
            showStreamFriends        : showStreamFriends,
            makeCall                 : makeCall,
            sendUpdateStatusMessage  : sendUpdateStatusMessage,
            sendUpdateStatusMessageTo: sendUpdateStatusMessageTo
        };

        function createPeer(username) {
            peerId = username;
            createPeerBot(username + '-Friendybot');
            createPeerBot(username + '-Spamobot');

            // Create the peer
            peer = new Peer(username, {
                key  : CONFIG.internal.peer.key,
                debug: CONFIG.internal.peer.debug
            });

            // Listen for the creation
            peer.on('open', function (id) {
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'Peer connection is now open');
            });

            // When other users connect to you
            peer.on('connection', function (newConnection) {
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'User', newConnection.peer, 'as established a connection with you');
                listenData(newConnection, function () {
                    sendUpdateStatusMessageTo(newConnection.peer, statusFactory.getCurrentUserStatus().index);
                });
            });

            // Listen for video calls
            // Listen for video calls
            peer.on('call', function (newMediaConnection) {
                mediaConnection = newMediaConnection;
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'You received a call');

                // Open the popup to accept or refuse the call
                getMediaStream(true, true, function () {
                    $rootScope.methods.showPopup(null, 'onCall', {
                        mediaConnection: mediaConnection,
                        mediaStream    : mediaStream,
                        username       : mediaConnection.peer,
                        type           : 'purple'
                    });
                });

                // When the call is answer, the stream is triggered
                mediaConnection.on('stream', function (stream) {
                    showStreamFriends(stream);
                    cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'The stream is live');
                });
            });

            // Listen for close window or refresh
            $window.onbeforeunload = function () {
                statusFactory.setCurrentUserStatus(3);
                sendUpdateStatusMessage(3);
                destroyPeer();
            };
            return peer;
        }

        function createPeerBot(username) {
            new Peer(username, {
                key  : CONFIG.internal.peer.key,
                debug: 0
            });
        }

        function connectFriends(friends) {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'connectFriends');

            // For each friend
            friends.forEach(function (friend) {

                // Handle bots
                if (friend.username == 'Friendybot') {
                    friend.peerUsername = peerId + '-Friendybot';
                }
                else if (friend.username == 'Spamobot') {
                    friend.peerUsername = peerId + '-Spamobot';
                }
                else if (friend.username != peerId) {

                    // Default username if empty
                    if (Methods.isNullOrEmpty(friend.peerUsername)) {
                        friend.peerUsername = friend.username;
                    }

                    // Check if connection exist
                    var connected = false;
                    for (var user in peer.connections) {

                        // The connection exist
                        if (user == friend.peerUsername) {

                            // Check if at least one of the connection is still open
                            peer.connections[user].forEach(function (connection) {
                                if (connection.open) {
                                    cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'The connection with', friend.peerUsername, 'is still opened');
                                    connected = true;
                                }
                            });
                            break;
                        }
                    }

                    // The connection doesn't exist
                    if (!connected) {

                        // Create the connection
                        var newConnection = peer.connect(friend.peerUsername);
                        cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'The connection with', friend.peerUsername, 'has been requested');

                        if (!Methods.isNullOrEmpty(newConnection)) {
                            listenData(newConnection, function () {
                                sendUpdateStatusMessageTo(friend.peerUsername, statusFactory.getCurrentUserStatus().index);
                            });
                        }
                    }
                }
            });
        }

        function connectionSend(newMessage) {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'connectionSend');
            var connection = searchConnection(newMessage.message.targetedUsername);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send(newMessage);
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'New message sent');
            }
        }

        function destroyPeer() {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'destroyPeer');
            if (!Methods.isNullOrEmpty(peer)) {
                cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'Go offline and destroy peer');
                sendUpdateStatusMessage(3, function () {
                    peer.disconnect();
                    peer.destroy();
                });
            }
        }

        function searchConnection(username) {

            // Check if connection exist
            var searchedConnection = null;
            for (var user in peer.connections) {

                // The connection exist
                if (user == username) {

                    // Check if at least one of the connection is still open
                    peer.connections[user].forEach(function (connection) {
                        if (connection.open) {
                            searchedConnection = connection;
                        }
                    });
                }
            }
            return searchedConnection;
        }

        function getMediaStream(audio, video, successCallback) {

            // If the media stream wasn't set
            if (Methods.isNullOrEmpty(mediaStream)) {
                navigator.mediaDevices.getUserMedia({
                    audio: Methods.isBoolean(audio) ? audio : true,
                    video: Methods.isBoolean(video) ? video : true
                }).then(function (newMediaStream) {
                    mediaStream = newMediaStream;
                    cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'We can start a media stream');
                    successCallback();
                }).catch(function () {
                    cozenEnhancedLogs.error.customMessage('cogeoWebRtc', 'We can not start a media stream');
                    cozenFloatingFeedFactory.addAlert({
                        type : 'error',
                        label: 'alerts_error_get_mediaStream'
                    });
                });
            }

            // If we already have a media stream
            else {
                successCallback();
            }
        }

        function listenData(newConnection, callback) {
            if (!Methods.isNullOrEmpty(newConnection)) {

                // Wait for the open state of the connection
                newConnection.on('open', function () {

                    // Listen for new messages
                    newConnection.on('data', function (data) {
                        cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'New message received from', newConnection.peer, 'connection');

                        // Update the right factory
                        if (data.tag == 'friend') {
                            directMessagesFactory.addMessage(data.messageId, data.message);
                        }

                        // Stop the call
                        else if (data.tag == 'stopCallFriend') {

                            // Close the popup
                            $rootScope.methods.closePopup(null, 'onCall');

                            // Alert the user
                            cozenFloatingFeedFactory.addAlert({
                                type       : 'blue',
                                label      : 'alerts_info_call_stop',
                                labelValues: {
                                    username: data.username
                                }
                            });
                        }

                        // The call was refused
                        else if (data.tag == 'refuseCallFriend') {

                            // Alert the user
                            cozenFloatingFeedFactory.addAlert({
                                type : 'blue',
                                label: 'alerts_info_call_refused'
                            });
                            $rootScope.$broadcast('cogeoWebRtc:refusedCall');
                        }

                        // Display the view with the media
                        else if (data.tag == 'showFriendStream') {
                            showStreamFriends(data.stream);
                        }

                        // Update the status for the user
                        else if (data.tag == 'newStatus') {
                            cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'New status');
                            $rootScope.$broadcast('cogeoWebRtc:newStatus', {
                                statusIndex: data.statusIndex,
                                username   : data.username
                            });
                        }

                        else {
                            $rootScope.$broadcast('groupsFactory:newMessage', {
                                groupName  : data.groupName,
                                channelName: data.channelName,
                                newMessage : data.message
                            });
                        }
                    });

                    if (Methods.isFunction(callback)) {
                        callback();
                    }
                });
            }
        }

        function showStreamFriends(stream) {
            $rootScope.$broadcast('cogeoWebRtc:streamStarted');
            $('#user-stream').prop('src', URL.createObjectURL(mediaStream));
            $('#friend-stream').prop('src', URL.createObjectURL(stream));
        }

        function makeCall($eventData) {
            mediaConnection = peer.call($eventData.friend, mediaStream);
            cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called ask for friend', $eventData.friend);
        }

        function sendUpdateStatusMessage(statusIndex, callback) {
            if (!Methods.isNullOrEmpty(peer)) {
                for (var user in peer.connections) {
                    peer.connections[user].forEach(function (userConnection) {
                        if (userConnection.open) {
                            userConnection.send({
                                tag        : 'newStatus',
                                statusIndex: statusIndex, // Online
                                username   : peerId       // Current user username
                            });
                        }
                    });
                }
                if (Methods.isFunction(callback)) {
                    callback();
                }
            }
        }

        function sendUpdateStatusMessageTo(username, statusIndex) {
            var connection = searchConnection(username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag        : 'newStatus',
                    statusIndex: statusIndex, // Online
                    username   : peerId       // Current user username
                });
            }
        }
    }

})(window.angular);<commit_msg>Added logs<commit_after>(function (angular) {
    'use strict';

    angular
        .module('cogeoApp')
        .factory('cogeoWebRtc', cogeoWebRtc);

    cogeoWebRtc.$inject = [
        'CONFIG',
        '$window',
        'cozenEnhancedLogs',
        'directMessagesFactory',
        '$rootScope',
        'cozenFloatingFeedFactory',
        'statusFactory'
    ];

    function cogeoWebRtc(CONFIG, $window, cozenEnhancedLogs, directMessagesFactory, $rootScope, cozenFloatingFeedFactory,
                         statusFactory) {

        // Private data
        var peer;
        var peerId;
        var mediaConnection;
        var mediaStream;

        // Subscribe to current user status change
        $rootScope.$on('statusFactoryChanged', function ($event) {
            sendUpdateStatusMessage(statusFactory.getCurrentUserStatus().index);
        });

        // Listener called when the user wish to start a call with a friend
        $rootScope.$on('cogeoWebRtc:callFriend', function ($event, $eventData) {

            // Try to get the media stream
            getMediaStream(true, true, function () {
                makeCall($eventData);
            });
        });

        // Listener called when the user wish to start a call audio with a friend
        $rootScope.$on('cogeoWebRtc:callFriendAudio', function ($event, $eventData) {

            // Try to get the media stream
            getMediaStream(true, false, function () {
                makeCall($eventData);
            });
        });

        // Listener called when the user wish to stop the call for a friend
        $rootScope.$on('cogeoWebRtc:stopCallFriend', function ($event, $eventData) {
            var connection = searchConnection($eventData.friend);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'stopCallFriend',
                    username: $eventData.friend
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called stop for friend', $eventData.friend);
            }
        });

        // Listener called when the user accept the call
        $rootScope.$on('cogeoWebRtc:answerCall', function ($event, $eventData) {

            // Send a message to tell the other user to show his own stream
            var connection = searchConnection($eventData.username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'showFriendStream',
                    username: $eventData.username,
                    stream  : mediaStream
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called accepted for friend', $eventData.username);
            }

            // Start the media stream
            mediaConnection.answer(mediaStream);
            cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'Call answered');
        });

        // Listener called whe the user refuse the call
        $rootScope.$on('cogeoWebRtc:refuseCall', function ($event, $eventData) {
            var connection = searchConnection($eventData.username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag     : 'refuseCallFriend',
                    username: $eventData.username
                });
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called refused for friend', $eventData.username);
            }
        });

        return {
            createPeer               : createPeer,
            createPeerBot            : createPeerBot,
            connectFriends           : connectFriends,
            connectionSend           : connectionSend,
            destroyPeer              : destroyPeer,
            searchConnection         : searchConnection,
            getMediaStream           : getMediaStream,
            listenData               : listenData,
            showStreamFriends        : showStreamFriends,
            makeCall                 : makeCall,
            sendUpdateStatusMessage  : sendUpdateStatusMessage,
            sendUpdateStatusMessageTo: sendUpdateStatusMessageTo
        };

        function createPeer(username) {
            peerId = username;
            createPeerBot(username + '-Friendybot');
            createPeerBot(username + '-Spamobot');

            // Create the peer
            peer = new Peer(username, {
                key  : CONFIG.internal.peer.key,
                debug: CONFIG.internal.peer.debug
            });

            // Listen for the creation
            peer.on('open', function (id) {
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'Peer connection is now open');
            });

            // When other users connect to you
            peer.on('connection', function (newConnection) {
                cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'User', newConnection.peer, 'as established a connection with you');
                listenData(newConnection, function () {
                    sendUpdateStatusMessageTo(newConnection.peer, statusFactory.getCurrentUserStatus().index);
                });
            });

            // Listen for video calls
            peer.on('call', function (newMediaConnection) {
                mediaConnection = newMediaConnection;
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'You received a call');

                // Open the popup to accept or refuse the call
                getMediaStream(true, true, function () {
                    $rootScope.methods.showPopup(null, 'onCall', {
                        mediaConnection: mediaConnection,
                        mediaStream    : mediaStream,
                        username       : mediaConnection.peer,
                        type           : 'purple'
                    });
                    Methods.safeApply($rootScope);
                });

                // When the call is answer, the stream is triggered
                mediaConnection.on('stream', function (stream) {
                    showStreamFriends(stream);
                    cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'The stream is live');
                });
            });

            // Listen for close window or refresh
            $window.onbeforeunload = function () {
                statusFactory.setCurrentUserStatus(3);
                sendUpdateStatusMessage(3);
                destroyPeer();
            };
            return peer;
        }

        function createPeerBot(username) {
            new Peer(username, {
                key  : CONFIG.internal.peer.key,
                debug: 0
            });
        }

        function connectFriends(friends) {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'connectFriends');

            // For each friend
            friends.forEach(function (friend) {

                // Handle bots
                if (friend.username == 'Friendybot') {
                    friend.peerUsername = peerId + '-Friendybot';
                }
                else if (friend.username == 'Spamobot') {
                    friend.peerUsername = peerId + '-Spamobot';
                }
                else if (friend.username != peerId) {

                    // Default username if empty
                    if (Methods.isNullOrEmpty(friend.peerUsername)) {
                        friend.peerUsername = friend.username;
                    }

                    // Check if connection exist
                    var connected = false;
                    for (var user in peer.connections) {

                        // The connection exist
                        if (user == friend.peerUsername) {

                            // Check if at least one of the connection is still open
                            peer.connections[user].forEach(function (connection) {
                                if (connection.open) {
                                    cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'The connection with', friend.peerUsername, 'is still opened');
                                    connected = true;
                                }
                            });
                            break;
                        }
                    }

                    // The connection doesn't exist
                    if (!connected) {

                        // Create the connection
                        var newConnection = peer.connect(friend.peerUsername);
                        cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'The connection with', friend.peerUsername, 'has been requested');

                        if (!Methods.isNullOrEmpty(newConnection)) {
                            listenData(newConnection, function () {
                                sendUpdateStatusMessageTo(friend.peerUsername, statusFactory.getCurrentUserStatus().index);
                            });
                        }
                    }
                }
            });
        }

        function connectionSend(newMessage) {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'connectionSend');
            var connection = searchConnection(newMessage.message.targetedUsername);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send(newMessage);
                cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'New message sent');
            }
        }

        function destroyPeer() {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'destroyPeer');
            if (!Methods.isNullOrEmpty(peer)) {
                cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'Go offline and destroy peer');
                sendUpdateStatusMessage(3, function () {
                    peer.disconnect();
                    peer.destroy();
                });
            }
        }

        function searchConnection(username) {

            // Check if connection exist
            var searchedConnection = null;
            for (var user in peer.connections) {

                // The connection exist
                if (user == username) {

                    // Check if at least one of the connection is still open
                    peer.connections[user].forEach(function (connection) {
                        if (connection.open) {
                            searchedConnection = connection;
                        }
                    });
                }
            }
            return searchedConnection;
        }

        function getMediaStream(audio, video, successCallback) {
            cozenEnhancedLogs.info.functionCalled('cogeoWebRtc', 'getMediaStream');

            // If the media stream wasn't set
            if (Methods.isNullOrEmpty(mediaStream)) {
                var userMediaSettings = {
                    audio: Methods.isBoolean(audio) ? audio : true,
                    video: Methods.isBoolean(video) ? video : true
                };
                cozenEnhancedLogs.explodeObject(userMediaSettings, true);
                navigator.mediaDevices.getUserMedia(userMediaSettings).then(function (newMediaStream) {
                    mediaStream = newMediaStream;
                    cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'We can start a media stream');
                    successCallback();
                }).catch(function () {
                    cozenEnhancedLogs.error.customMessage('cogeoWebRtc', 'We can not start a media stream');
                    cozenFloatingFeedFactory.addAlert({
                        type : 'error',
                        label: 'alerts_error_get_mediaStream'
                    });
                });
            }

            // If we already have a media stream
            else {
                successCallback();
            }
        }

        function listenData(newConnection, callback) {
            if (!Methods.isNullOrEmpty(newConnection)) {

                // Wait for the open state of the connection
                newConnection.on('open', function () {

                    // Listen for new messages
                    newConnection.on('data', function (data) {
                        cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'New message received from', newConnection.peer, 'connection');

                        // Update the right factory
                        if (data.tag == 'friend') {
                            directMessagesFactory.addMessage(data.messageId, data.message);
                        }

                        // Stop the call
                        else if (data.tag == 'stopCallFriend') {

                            // Close the popup
                            $rootScope.methods.closePopup(null, 'onCall');

                            // Alert the user
                            cozenFloatingFeedFactory.addAlert({
                                type       : 'blue',
                                label      : 'alerts_info_call_stop',
                                labelValues: {
                                    username: data.username
                                }
                            });
                        }

                        // The call was refused
                        else if (data.tag == 'refuseCallFriend') {

                            // Alert the user
                            cozenFloatingFeedFactory.addAlert({
                                type : 'blue',
                                label: 'alerts_info_call_refused'
                            });
                            $rootScope.$broadcast('cogeoWebRtc:refusedCall');
                        }

                        // Display the view with the media
                        else if (data.tag == 'showFriendStream') {
                            showStreamFriends(data.stream);
                        }

                        // Update the status for the user
                        else if (data.tag == 'newStatus') {
                            cozenEnhancedLogs.info.customMessage('cogeoWebRtc', 'New status');
                            $rootScope.$broadcast('cogeoWebRtc:newStatus', {
                                statusIndex: data.statusIndex,
                                username   : data.username
                            });
                        }

                        else {
                            $rootScope.$broadcast('groupsFactory:newMessage', {
                                groupName  : data.groupName,
                                channelName: data.channelName,
                                newMessage : data.message
                            });
                        }
                    });

                    if (Methods.isFunction(callback)) {
                        callback();
                    }
                });
            }
        }

        function showStreamFriends(stream) {
            $rootScope.$broadcast('cogeoWebRtc:streamStarted');
            $('#user-stream').prop('src', URL.createObjectURL(mediaStream));
            $('#friend-stream').prop('src', URL.createObjectURL(stream));
        }

        function makeCall($eventData) {
            mediaConnection = peer.call($eventData.friend, mediaStream);
            cozenEnhancedLogs.info.customMessageEnhanced('cogeoWebRtc', 'Called ask for friend', $eventData.friend);
        }

        function sendUpdateStatusMessage(statusIndex, callback) {
            if (!Methods.isNullOrEmpty(peer)) {
                for (var user in peer.connections) {
                    peer.connections[user].forEach(function (userConnection) {
                        if (userConnection.open) {
                            userConnection.send({
                                tag        : 'newStatus',
                                statusIndex: statusIndex, // Online
                                username   : peerId       // Current user username
                            });
                        }
                    });
                }
                if (Methods.isFunction(callback)) {
                    callback();
                }
            }
        }

        function sendUpdateStatusMessageTo(username, statusIndex) {
            var connection = searchConnection(username);
            if (!Methods.isNullOrEmpty(connection)) {
                connection.send({
                    tag        : 'newStatus',
                    statusIndex: statusIndex, // Online
                    username   : peerId       // Current user username
                });
            }
        }
    }

})(window.angular);<|endoftext|>


<commit_before>/** OnboardingProgress view model.
    It tracks the onboarding information and methods
    to update views to that state
**/
var Model = require('../models/Model');
var ko = require('knockout');

/**
 * Definition of steps, in strict order, with settings from available:
 * - serviceProfessionalOnly:boolean Whether is display to professional users only
 * - jobTitleSpecific:boolean Whether the step needs a jobTitleID in order to work,
 * and accepts that as the first URL segment
 */
var STEPS = {
    welcome: {
        userFlags: ['isClient', 'isServiceProfessional']
    },
    publicContactInfo: {
        userFlags: ['isClient', 'isServiceProfessional']
    },
    addJobTitle: {
        userFlags: ['isServiceProfessional']
    },
    serviceAddresses: {
        userFlags: ['isServiceProfessional'],
        jobTitleSpecific: true
    }
};
var PROFESSIONAL_FINISH_STEP = 'listingEditor';
var CLIENT_FINISH_STEP = 'home';

function getUserSteps(user) {
    return Object.keys(STEPS)
    .filter(function(stepName) {
        const step = STEPS[stepName];
        return !!step.userFlags.some((flag) => user[flag]());
    });
}

function OnboardingProgress(values) {
    var stepNumberFinished = -1;

    Model(this);

    this.model.defProperties({
        isServiceProfessional: false,
        stepNumber: stepNumberFinished,
        // Let's set a job title to pass in to jobTitleSpecific steps as URL segment
        selectedJobTitleID: null
    }, values);

    this.stepNames = ko.pureComputed(function() {
        return getUserSteps(this);
    }, this);
    /**
     * Gives the name of the step (activity) that should be navigated after finishing
     * the onboarding.
     * @member {KnockoutComputed<string>}
     */
    this.stepAfterFinish = ko.pureComputed(function() {
        return this.isServiceProfessional() ? PROFESSIONAL_FINISH_STEP : CLIENT_FINISH_STEP;
    }, this);

    this.totalSteps = ko.pureComputed(function() {
        // 'Zero' step is a welcome, not accounted:
        return this.stepNames().length - 1;
    }, this);

    this.incrementStep = function() {
        var currentStep = this.stepNumber();

        if(this.isFinished()) {
            return;
        }
        else if(currentStep == (this.stepNames().length - 1)){
            this.finish();
        }
        else {
            this.stepNumber(currentStep + 1);
        }
    };

    this.stepAfter = function(stepName) {
        var nextStep = new OnboardingProgress({
            selectedJobTitleID: this.selectedJobTitleID(),
            isServiceProfessional: this.isServiceProfessional()
        });
        nextStep.setStepByName(stepName);
        nextStep.incrementStep();

        return nextStep;
    };

    this.stepName = ko.pureComputed(function() {
        return this.stepNames()[this.stepNumber()] || null;
    }, this);

    this.stepUrl = ko.pureComputed(function() {
        var name = this.stepName();
        if (!name) return null;
        var url = '/' + name;

        // Check if there is need for a jobTitleID in the URL
        var def = STEPS[name];
        var jobID = this.selectedJobTitleID();
        if (jobID && def && def.jobTitleSpecific) {
            url += '/' + jobID;
        }

        return url;
    }, this);

    this.progressText = ko.pureComputed(function() {
        // TODO L18N
        return this.stepNumber() + ' of ' + this.totalSteps();
    }, this);

    this.inProgress = ko.pureComputed(function() {
        return !this.isFinished();
    }, this);

    this.finish = function() {
        this.stepNumber(stepNumberFinished);
    };

    this.isFinished = ko.pureComputed(function() {
        return this.stepNumber() === stepNumberFinished;
    }, this);
}

module.exports = OnboardingProgress;

OnboardingProgress.prototype.setStepByName = function setStepByName(name) {
    var stepIndex = this.stepNames().indexOf(name);
    if (stepIndex > -1) {
        this.stepNumber(stepIndex);
        return true;
    }
    return false;
};
<commit_msg>Updated onboarding with 'organization' user flag specifics #820<commit_after>/** OnboardingProgress view model.
    It tracks the onboarding information and methods
    to update views to that state
**/
var Model = require('../models/Model');
var ko = require('knockout');

/**
 * Definition of steps, in strict order, with settings from available:
 * - serviceProfessionalOnly:boolean Whether is display to professional users only
 * - jobTitleSpecific:boolean Whether the step needs a jobTitleID in order to work,
 * and accepts that as the first URL segment
 */
var STEPS = {
    welcome: {
        userFlags: ['isClient', 'isServiceProfessional']
    },
    publicContactInfo: {
        userFlags: ['isClient', 'isServiceProfessional']
    },
    organizationInfo: {
        userFlags: ['isOrganization']
    },
    addJobTitle: {
        userFlags: ['isServiceProfessional']
    },
    serviceAddresses: {
        userFlags: ['isServiceProfessional'],
        jobTitleSpecific: true
    }
};
var PROFESSIONAL_FINISH_STEP = 'listingEditor';
var CLIENT_FINISH_STEP = 'home';
var ORGANIZATION_FINISH_STEP = 'posting';

function getUserSteps(user) {
    return Object.keys(STEPS)
    .filter(function(stepName) {
        const step = STEPS[stepName];
        return !!step.userFlags.some((flag) => user[flag]());
    });
}

function OnboardingProgress(values) {
    var stepNumberFinished = -1;

    Model(this);

    this.model.defProperties({
        isServiceProfessional: false,
        stepNumber: stepNumberFinished,
        // Let's set a job title to pass in to jobTitleSpecific steps as URL segment
        selectedJobTitleID: null
    }, values);

    this.stepNames = ko.pureComputed(function() {
        return getUserSteps(this);
    }, this);
    /**
     * Gives the name of the step (activity) that should be navigated after finishing
     * the onboarding.
     * @member {KnockoutComputed<string>}
     */
    this.stepAfterFinish = ko.pureComputed(function() {
        return this.isOrganization() ?
            ORGANIZATION_FINISH_STEP :
            this.isServiceProfessional() ?
            PROFESSIONAL_FINISH_STEP :
            CLIENT_FINISH_STEP;
    }, this);

    this.totalSteps = ko.pureComputed(function() {
        // 'Zero' step is a welcome, not accounted:
        return this.stepNames().length - 1;
    }, this);

    this.incrementStep = function() {
        var currentStep = this.stepNumber();

        if(this.isFinished()) {
            return;
        }
        else if(currentStep == (this.stepNames().length - 1)){
            this.finish();
        }
        else {
            this.stepNumber(currentStep + 1);
        }
    };

    this.stepAfter = function(stepName) {
        var nextStep = new OnboardingProgress({
            selectedJobTitleID: this.selectedJobTitleID(),
            isServiceProfessional: this.isServiceProfessional()
        });
        nextStep.setStepByName(stepName);
        nextStep.incrementStep();

        return nextStep;
    };

    this.stepName = ko.pureComputed(function() {
        return this.stepNames()[this.stepNumber()] || null;
    }, this);

    this.stepUrl = ko.pureComputed(function() {
        var name = this.stepName();
        if (!name) return null;
        var url = '/' + name;

        // Check if there is need for a jobTitleID in the URL
        var def = STEPS[name];
        var jobID = this.selectedJobTitleID();
        if (jobID && def && def.jobTitleSpecific) {
            url += '/' + jobID;
        }

        return url;
    }, this);

    this.progressText = ko.pureComputed(function() {
        // TODO L18N
        return this.stepNumber() + ' of ' + this.totalSteps();
    }, this);

    this.inProgress = ko.pureComputed(function() {
        return !this.isFinished();
    }, this);

    this.finish = function() {
        this.stepNumber(stepNumberFinished);
    };

    this.isFinished = ko.pureComputed(function() {
        return this.stepNumber() === stepNumberFinished;
    }, this);
}

module.exports = OnboardingProgress;

OnboardingProgress.prototype.setStepByName = function setStepByName(name) {
    var stepIndex = this.stepNames().indexOf(name);
    if (stepIndex > -1) {
        this.stepNumber(stepIndex);
        return true;
    }
    return false;
};
<|endoftext|>


<commit_before>import {APIService} from './services/API.service';
import {DialogService} from './services/dialog.service';
import {ToastService} from './services/toast.service';

angular.module('app.services')
	.factory('API', APIService)
	.factory('DialogService', DialogService)
	.factory('ToastService', ToastService)
<commit_msg>Change .factory to .service to be able to use class for the services<commit_after>import {APIService} from './services/API.service';
import {DialogService} from './services/dialog.service';
import {ToastService} from './services/toast.service';

angular.module('app.services')
	.service('API', APIService)
	.service('DialogService', DialogService)
	.service('ToastService', ToastService)
<|endoftext|>