<commit_before>/*global $ */
(function () {
	'use strict';

	var date = new Date();
	if (date.getDate() === 1 && date.getMonth() === 3) {
		['', '-webkit-', '-moz-'].forEach(function (prefix) {
			document.body.style[prefix + 'filter'] = 'blur(1px)';
		});
	}

	$.fn.persistantPopover = function () {
		var popoverTimeout;

		function delay() {
			popoverTimeout = setTimeout(function () {
				$('.popover').hide();
			}, 100);
		}

		return this.each(function () {
			var $this = $(this);
			$this.popover({
				trigger: 'manual',
				placement: 'right',
				animation: false,
				html: true,
				title: this.firstChild.textContent + 'Website'
			});
		})
		.mouseenter(function () {
			clearTimeout(popoverTimeout);
			$('.popover').remove();
			$(this).popover('show');
		})
		.mouseleave(function () {
			delay();
			$('.popover').mouseenter(function () {
				clearTimeout(popoverTimeout);
			}).mouseleave(function () {
				delay();
			});
		});
	};

	var Quotes = {};
	Quotes.build = function (quotes, template) {
		var quoteContainer = document.createElement('q');
		var quoteElemCount = 0;
		var quoteCount = quotes.length;

		var createQuoteElems = function () {
			var quote = quotes[quoteElemCount];
			var el = $(template).hide();

			el.children('p').text(quote.quote);
			el.find('a').text(quote.person.name).attr('href', quote.person.link);
			el.find('img').attr('src', quote.person.gravatar);

			quoteContainer.appendChild(el[0]);

			if (quoteCount > ++quoteElemCount) {
				createQuoteElems();
			}

			return quoteContainer.innerHTML;
		};
		return createQuoteElems();
	};

	Quotes.random = function (quotes) {
		var quoteCount = quotes.length;
		var randomQuotes = [];

		var randomQuote = function () {
			var randomQuoteIndex = Math.floor(Math.random() * quoteCount);

			if ($.inArray(randomQuoteIndex, randomQuotes) > -1) {
				return randomQuote();
			}

			if (randomQuotes.length === quoteCount - 1) {
				randomQuotes = [];
			}

			randomQuotes.push(randomQuoteIndex);

			return randomQuoteIndex;
		};
		return randomQuote;
	};

	Quotes.animate = function (container, animSpeed) {
		var fader = function (fadeOut, fadeIn) {
			var fadeOutCallback = function () {
				fadeIn.fadeIn(500, fadeInCallback);
			};

			var fadeInCallback = function () {
				window.setTimeout(swap, animSpeed);
			};

			fadeOut.fadeOut(500, fadeOutCallback);
		};

		var quotes = container.children();
		var selectRandomQuoteIndex = Quotes.random(quotes);
		var quoteElems = {};
		var activeQuoteIndex = selectRandomQuoteIndex();
		var prevQuoteElem = $(quotes[activeQuoteIndex]);

		var swap = function () {
			if (!quoteElems[activeQuoteIndex]) {
				quoteElems[activeQuoteIndex] = $(quotes[activeQuoteIndex]);
			}

			var activeQuoteElem = quoteElems[activeQuoteIndex];

			fader(prevQuoteElem, activeQuoteElem);

			activeQuoteIndex = selectRandomQuoteIndex();
			prevQuoteElem = activeQuoteElem;
		};
		return swap();
	};

	Quotes.init = function (quotes) {
		var container = $(this);
		var template = $(this).html();
		var quotesHTML = Quotes.build(quotes, template);

		container.html(quotesHTML);

		Quotes.animate(container, 25000);
	};

	$.fn.quote = function (quotes) {
		return this.each(function () {
			Quotes.init.call(this, quotes);
		});
	};

	// Apps popover
	$('.applist a').persistantPopover();

	// Quotes
	$('.quotes').quote([{
		quote: 'TodoMVC is a godsend for helping developers find what well-developed frameworks match their mental model of application architecture.',
		person: {
			name: 'Paul Irish',
			gravatar: 'http://gravatar.com/avatar/ffe68d6f71b225f7661d33f2a8908281?s=40',
			link: 'https://github.com/paulirish'
		}
	}, {
		quote: 'Modern JavaScript developers realise an MVC framework is essential for managing the complexity of their apps. TodoMVC is a fabulous community contribution that helps developers compare frameworks on the basis of actual project code, not just claims and anecdotes.',
		person: {
			name: 'Michael Mahemoff',
			gravatar: 'http://gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=40',
			link: 'https://github.com/mahemoff'
		}
	}, {
		quote: 'TodoMVC is an immensely valuable attempt at a difficult problem - providing a structured way of comparing JS libraries and frameworks. TodoMVC is a lone data point in a sea of conjecture and opinion.',
		person: {
			name: 'Justin Meyer',
			gravatar: 'http://gravatar.com/avatar/70ee60f32937b52758869488d5753259?s=40',
			link: 'https://github.com/justinbmeyer'
		}
	}, {
		quote: 'It can be hard to make the leap from hacking together code that works to writing code that`s organized, maintainable, reusable, and a joy to work on. The TodoMVC project does a great job of introducing developers to different approaches to code organization, and to the various libraries that can help them along the way. If you`re trying to get your bearings in the world of client-side application development, the TodoMVC project is a great place to get started.',
		person: {
			name: 'Rebecca Murphey',
			gravatar: 'http://gravatar.com/avatar/0177cdce6af15e10db15b6bf5dc4e0b0?s=40',
			link: 'https://github.com/rmurphey'
		}
	}]);

	function AppTabs() {
		document.querySelector(AppTabs.selectors.tabs).addEventListener(
			'core-select', this.onSelect.bind(this));
		this.listHeight = 0;
	}

	AppTabs.selectors = {
		tabs: '.js-app-tabs',
		list: '.js-app-list',
		innerList: '.js-app-list-inner'
	};

	AppTabs.prototype.onSelect = function (e) {
		var selected = e.target.selected;
		[].slice.call(document.querySelectorAll(AppTabs.selectors.list)).forEach(
			function (el) {
				if (!e.detail.isSelected) {
					// Don't handle unselection events.
					return;
				}

				var isSelected = el.dataset.appList === selected;
				el.style.display = isSelected ? 'block' : 'none';
				if (isSelected) {
					this.switchTab(el);
				}
			}.bind(this)
		);
	};

	AppTabs.prototype.switchTab = function (e) {
		var list = e.querySelector(AppTabs.selectors.innerList);
		var $clone = $(list)
			.clone()
			.css({ visibility: 'hidden' })
			.height('auto')
			.appendTo(list.parentElement);

		window.requestAnimationFrame(function () {
			$clone.remove();
		}.bind(this));
	};

	new AppTabs();

}());
<commit_msg>Eliminating tabs and tabs-related js error<commit_after>/*global $ */
(function () {
	'use strict';

	var date = new Date();
	if (date.getDate() === 1 && date.getMonth() === 3) {
		['', '-webkit-', '-moz-'].forEach(function (prefix) {
			document.body.style[prefix + 'filter'] = 'blur(1px)';
		});
	}

	$.fn.persistantPopover = function () {
		var popoverTimeout;

		function delay() {
			popoverTimeout = setTimeout(function () {
				$('.popover').hide();
			}, 100);
		}

		return this.each(function () {
			var $this = $(this);
			$this.popover({
				trigger: 'manual',
				placement: 'right',
				animation: false,
				html: true,
				title: this.firstChild.textContent + 'Website'
			});
		})
		.mouseenter(function () {
			clearTimeout(popoverTimeout);
			$('.popover').remove();
			$(this).popover('show');
		})
		.mouseleave(function () {
			delay();
			$('.popover').mouseenter(function () {
				clearTimeout(popoverTimeout);
			}).mouseleave(function () {
				delay();
			});
		});
	};

	var Quotes = {};
	Quotes.build = function (quotes, template) {
		var quoteContainer = document.createElement('q');
		var quoteElemCount = 0;
		var quoteCount = quotes.length;

		var createQuoteElems = function () {
			var quote = quotes[quoteElemCount];
			var el = $(template).hide();

			el.children('p').text(quote.quote);
			el.find('a').text(quote.person.name).attr('href', quote.person.link);
			el.find('img').attr('src', quote.person.gravatar);

			quoteContainer.appendChild(el[0]);

			if (quoteCount > ++quoteElemCount) {
				createQuoteElems();
			}

			return quoteContainer.innerHTML;
		};
		return createQuoteElems();
	};

	Quotes.random = function (quotes) {
		var quoteCount = quotes.length;
		var randomQuotes = [];

		var randomQuote = function () {
			var randomQuoteIndex = Math.floor(Math.random() * quoteCount);

			if ($.inArray(randomQuoteIndex, randomQuotes) > -1) {
				return randomQuote();
			}

			if (randomQuotes.length === quoteCount - 1) {
				randomQuotes = [];
			}

			randomQuotes.push(randomQuoteIndex);

			return randomQuoteIndex;
		};
		return randomQuote;
	};

	Quotes.animate = function (container, animSpeed) {
		var fader = function (fadeOut, fadeIn) {
			var fadeOutCallback = function () {
				fadeIn.fadeIn(500, fadeInCallback);
			};

			var fadeInCallback = function () {
				window.setTimeout(swap, animSpeed);
			};

			fadeOut.fadeOut(500, fadeOutCallback);
		};

		var quotes = container.children();
		var selectRandomQuoteIndex = Quotes.random(quotes);
		var quoteElems = {};
		var activeQuoteIndex = selectRandomQuoteIndex();
		var prevQuoteElem = $(quotes[activeQuoteIndex]);

		var swap = function () {
			if (!quoteElems[activeQuoteIndex]) {
				quoteElems[activeQuoteIndex] = $(quotes[activeQuoteIndex]);
			}

			var activeQuoteElem = quoteElems[activeQuoteIndex];

			fader(prevQuoteElem, activeQuoteElem);

			activeQuoteIndex = selectRandomQuoteIndex();
			prevQuoteElem = activeQuoteElem;
		};
		return swap();
	};

	Quotes.init = function (quotes) {
		var container = $(this);
		var template = $(this).html();
		var quotesHTML = Quotes.build(quotes, template);

		container.html(quotesHTML);

		Quotes.animate(container, 25000);
	};

	$.fn.quote = function (quotes) {
		return this.each(function () {
			Quotes.init.call(this, quotes);
		});
	};

	// Apps popover
	$('.applist a').persistantPopover();

	// Quotes
	$('.quotes').quote([{
		quote: 'TodoMVC is a godsend for helping developers find what well-developed frameworks match their mental model of application architecture.',
		person: {
			name: 'Paul Irish',
			gravatar: 'http://gravatar.com/avatar/ffe68d6f71b225f7661d33f2a8908281?s=40',
			link: 'https://github.com/paulirish'
		}
	}, {
		quote: 'Modern JavaScript developers realise an MVC framework is essential for managing the complexity of their apps. TodoMVC is a fabulous community contribution that helps developers compare frameworks on the basis of actual project code, not just claims and anecdotes.',
		person: {
			name: 'Michael Mahemoff',
			gravatar: 'http://gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=40',
			link: 'https://github.com/mahemoff'
		}
	}, {
		quote: 'TodoMVC is an immensely valuable attempt at a difficult problem - providing a structured way of comparing JS libraries and frameworks. TodoMVC is a lone data point in a sea of conjecture and opinion.',
		person: {
			name: 'Justin Meyer',
			gravatar: 'http://gravatar.com/avatar/70ee60f32937b52758869488d5753259?s=40',
			link: 'https://github.com/justinbmeyer'
		}
	}, {
		quote: 'It can be hard to make the leap from hacking together code that works to writing code that`s organized, maintainable, reusable, and a joy to work on. The TodoMVC project does a great job of introducing developers to different approaches to code organization, and to the various libraries that can help them along the way. If you`re trying to get your bearings in the world of client-side application development, the TodoMVC project is a great place to get started.',
		person: {
			name: 'Rebecca Murphey',
			gravatar: 'http://gravatar.com/avatar/0177cdce6af15e10db15b6bf5dc4e0b0?s=40',
			link: 'https://github.com/rmurphey'
		}
	}]);

	function AppTabs() {
		document.querySelector(AppTabs.selectors.tabs).addEventListener(
			'core-select', this.onSelect.bind(this));
		this.listHeight = 0;
	}

	AppTabs.selectors = {
		tabs: '.js-app-tabs',
		list: '.js-app-list',
		innerList: '.js-app-list-inner'
	};

	AppTabs.prototype.onSelect = function (e) {
		var selected = e.target.selected;
		[].slice.call(document.querySelectorAll(AppTabs.selectors.list)).forEach(
			function (el) {
				if (!e.detail.isSelected) {
					// Don't handle unselection events.
					return;
				}

				var isSelected = el.dataset.appList === selected;
				el.style.display = isSelected ? 'block' : 'none';
				if (isSelected) {
					this.switchTab(el);
				}
			}.bind(this)
		);
	};

	AppTabs.prototype.switchTab = function (e) {
		var list = e.querySelector(AppTabs.selectors.innerList);
		var $clone = $(list)
			.clone()
			.css({ visibility: 'hidden' })
			.height('auto')
			.appendTo(list.parentElement);

		window.requestAnimationFrame(function () {
			$clone.remove();
		}.bind(this));
	};

	//new AppTabs();

}());
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var db = require('../database/index.js');
var request = require('request');
var pgp = require('pg-promise')();
let path = require('path');
var cookieParser = require('cookie-parser');

let app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(__dirname + '/../client/dist'));

// routes
let routeHandlers = require('./lib/route-handlers');
let authRoutes = require('./lib/auth.js');
app.use('/auth', authRoutes);

app.post('/inventory', function(req, res) {
  db.query('SELECT houses_items.id AS id, houses_items.need_to_restock AS needToRestock, houses_items.notes AS notes, users.username AS username, items.itemname AS name FROM houses_items LEFT JOIN users ON houses_items.user_id = users.id LEFT JOIN items ON houses_items.item_id = items.id WHERE houses_items.house_id = ${houseId#};',
    { houseId: req.body.houseId })
    .then(data => {
      console.log('Successful DB query: ', data);
      res.send(data);
    })
    .catch(err => console.log('Bad DB query: ', err));
});

app.post('/restock', function(req, res) {
  db.query('UPDATE houses_items SET need_to_restock = TRUE WHERE id = ${itemId#}',
    { itemId: req.body.itemId })
    .then(() => {
      console.log('Item successfully updated to need_to_restock = TRUE in houses_items table');
      res.sendStatus(201);
    })
    .catch(err => console.log('Item need_to_restock value unable to be updated in houses_items: ', err));
});

app.post('/claim', function(req, res) {
  db.query('UPDATE houses_items SET user_id = ${userId#} WHERE id = ${itemId#}',
    { itemId: req.body.itemId, userId: req.body.userId })
    .then(() => {
      console.log(`Item successfully updated to user_id = ${req.body.userId} in houses_items table`);
      res.sendStatus(201);
    })
    .catch(err => console.log('Item user_id value unable to be updated in houses_items: ', err));
});

app.post('/delete', function(req, res) {
  db.query('DELETE FROM houses_items WHERE id = ${itemId#}',
    { itemId: req.body.itemId })
    .then(() => {
      console.log('Item successfully deleted from houses_items table');
      res.sendStatus(201);
    })
    .catch(err => console.log('Item unable to be removed from houses_items: ', err));
});

app.post('/createUser', function(req, res) {
  db.query('INSERT INTO users (id, username, house_id) VALUES (6, ${userName}, ${houseId#})', { userName: req.body.userName, houseId: req.body.houseId} )
    .then(() => {
      console.log('done creating user');
      res.sendStatus(201);
    })
    .catch (err => console.log('unable to create user', err));
});

app.post('/users', function(req, res) {
  db.query('SELECT * FROM users WHERE house_id=${houseId#}', { houseId: req.body.houseId })
  .then( (data)=> {
    res.send(data);
  })
  .catch(err => console.log('unable to get users', err));
});

app.get('/api/shop', routeHandlers.getShoppingList);
app.post('/api/shop', routeHandlers.updateWithPurchases);

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname + '/../client/dist/index.html'));
});

app.listen(process.env.PORT || 1337, function() {
  console.log('Listening on 1337...');
});
<commit_msg>Resolve rebase conflicts<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var db = require('../database/index.js');
var request = require('request');
var pgp = require('pg-promise')();
let path = require('path');
var cookieParser = require('cookie-parser');

let app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(__dirname + '/../client/dist'));

// routes
let routeHandlers = require('./lib/route-handlers');
let authRoutes = require('./lib/auth.js');
app.use('/auth', authRoutes);

app.post('/inventory', (req, res) => {
  db.query('SELECT houses_items.id AS id, houses_items.need_to_restock AS needToRestock, houses_items.notes AS notes, users.username AS username, items.itemname AS name FROM houses_items LEFT JOIN users ON houses_items.user_id = users.id LEFT JOIN items ON houses_items.item_id = items.id WHERE houses_items.house_id = ${houseId#};',
    { houseId: req.body.houseId })
    .then(data => {
      console.log('Successful DB query: ', data);
      res.send(data);
    })
    .catch(err => console.log('Bad DB query: ', err));
});

app.post('/restock', (req, res) => {
  db.query('UPDATE houses_items SET need_to_restock = TRUE WHERE id = ${itemId#}',
    { itemId: req.body.itemId })
    .then(() => {
      console.log('Item successfully updated to need_to_restock = TRUE in houses_items table');
      res.sendStatus(201);
    })
    .catch(err => console.log('Item need_to_restock value unable to be updated in houses_items: ', err));
});

app.post('/claim', (req, res) => {
  db.query('UPDATE houses_items SET user_id = ${userId#} WHERE id = ${itemId#}',
    { itemId: req.body.itemId, userId: req.body.userId })
    .then(() => {
      console.log(`Item successfully updated to user_id = ${req.body.userId} in houses_items table`);
      res.sendStatus(201);
    })
    .catch(err => console.log('Items user_id value unable to be updated in houses_items: ', err));

  db.query('INSERT INTO users_houses_items (user_id, houses_items_id) VALUES (${userId#}, ${itemId#})',
    { itemId: req.body.itemId, userId: req.body.userId })
    .then(() => {
      console.log('Item successfully inserted item into users_houses_items table');
      // res.sendStatus(201);
    })
    .catch(err => console.log('Item unable to be inserted in users_houses_items: ', err));
});

app.post('/delete', (req, res) => {
  db.query('DELETE FROM houses_items WHERE id = ${itemId#}',
    { itemId: req.body.itemId })
    .then(() => {
      console.log('Item successfully deleted from houses_items table');
      res.sendStatus(201);
    })
    .catch(err => console.log('Item unable to be removed from houses_items: ', err));
});

app.post('/createUser', function(req, res) {
  db.query('INSERT INTO users (id, username, house_id) VALUES (6, ${userName}, ${houseId#})', { userName: req.body.userName, houseId: req.body.houseId} )
    .then(() => {
      console.log('done creating user');
      res.sendStatus(201);
    })
    .catch (err => console.log('unable to create user', err));
});

app.post('/users', function(req, res) {
  db.query('SELECT * FROM users WHERE house_id=${houseId#}', { houseId: req.body.houseId })
  .then( (data)=> {
    res.send(data);
  })
  .catch(err => console.log('unable to get users', err));
});

app.post('/add', (req, res) => {
  // query if item is in items table
  db.query('SELECT id FROM items WHERE itemname = ${itemname~}', { itemname: req.body.name })
    .then(id => {
      if (!id) {
        db.query('INSERT INTO items (itemname) VALUE ($(itemname~))', { itemname: req.body.name })
          .then()
          .catch();
        // add to db
      }
      throw 'id exists';
    })
    // this should be a then, as all items should have id's at this points
    // query for id
    // insert into houses_items table
    .catch(err => {
      if (err = 'id exists') {
        db.query('INSERT INTO houses_items (house_id, item_id, need_to_restock, notes) VALUES (${houseId#}, ${itemId#}, ${needToRestock^}, ${notes~})',
          { houseId: req.body.houseId, itemId: id, needToRestock: FALSE, notes: req.body.notes })
          .then(() => res.send(201))
          .catch(err => console.log('Unable to add to houses_items table: ', err));
      }
    });
  // if yes
    // get item id
  // if not
    // add to items table
    // get item id
  // insert item_id and notes into houses_items table
  // add to db
  console.log('ADDING TO DB: ', req.body);
  res.send('Add to db...');
});

app.get('/api/shop', routeHandlers.getShoppingList);
app.post('/api/shop', routeHandlers.updateWithPurchases);

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname + '/../client/dist/index.html'));
});

app.listen(process.env.PORT || 1337, function() {
  console.log('Listening on 1337...');
});
<|endoftext|>


<commit_before>const 		express 											= require('express');
const 		app 															= express();
const 		path 														= require('path');
const 		bodyParser 								= require('body-parser');
const 		jwt 															= require('jsonwebtoken');
const { checkAuth,
								happyHourParams,
								statusTypeParams } = require('./serverMiddleware');
																													require('dotenv').config();

const PORT 																= process.env.PORT || 5000;
const environment 									= process.env.NODE_ENV || 'development';
const configuration 							= require('../knexfile')[environment];
const db 																		= require('knex')(configuration);

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
app.use(bodyParser.json());

// app.set('secretKey', process.env.SECRET_KEY);
app.set('secretKey', 'FAKE-process.env.SECRET_KEY');

// All remaining requests return the React app, so it can handle routing.
app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
})

app.post('/api/v1/admin/', (req, res) => {
	const payload = req.body;

	for (let requiredParams of ['businessID', "email"]) {
		if (!req.body[requiredParams]) {
			return res.status(422).json({ error: `Mising required parameter "${requiredParams}"`})
		}
	}

	if (payload.email.endsWith('@controllerAdmin.com')) {
		Object.assign(payload, { admin:true }, { businessID:req.body.businessID })
	} else { Object.assign(payload, { admin:false }) }

	const token = jwt.sign(payload, app.get('secretKey'), {expiresIn: '7d'})
	return res.status(200).json({ token })
})

app.route('/api/v1/location/')
.get((req, res) => {
	db('location').select()
	.then(allLocations =>  res.status(200).json({ allLocations }) )
	.catch(error => res.status(500).json({ ERROR: 'GET /api/v1/location/', error }))
})
.post(checkAuth, (req, res) => {
	const locationType 			= req.body.locationType;
	const newSocialMedia 	= req.body.socialMedia;
	const newLocation 				= req.body.location;
	const statusType 					= req.body.statusType;
	const newHappyHour 			= req.body.happyHour;

	for (let requiredParams of ["name","latitude","longitude"]) {
		if (!newLocation[requiredParams]) {
			return res.status(422).json({
				error: `missing required parameter ${requiredParams}`
			})
		}
	}

	db('location').where('name', newLocation.name).select()
	.then(data => {
		if (data.length > 0) {
			let ids = []
			for (let i=0;i<data.length;i++) { ids.push(data[i].id) }
			return res.status(300).json({
				message:`Warning, ${data.length} business(s) with the name ${newLocation.name} already exists in our database`,
				businessID: ids
			 })
			}
	})
	.catch(error => res.status(500).json({ error }))

		db('location_type').insert(locationType, 'id')
		.then(locTypeID => {
				Object.assign(newLocation, { location_type_id:locTypeID[0] })
				db('social_media').insert(newSocialMedia, 'id')
				.then(socialMediaID => {
					Object.assign(newLocation, { social_media_id:socialMediaID[0] })
					db('location').insert(newLocation, ['id'])
					.then(newLocID => {
						db('status_type').insert(statusType, 'id')
						.then(statusID => {
							Object.assign(newHappyHour, { status_type_id:statusID[0] }, { location_id:newLocID[0].id })
							db('happy_hour').insert(newHappyHour, ['location_id'])
							.then(locID => {
								db('location').where('id', locID[0].location_id).select()
								.then(data => res.status(200).json({ data }))
							})
							.catch(error => res.status(500).json({ error }))
						})
						.catch(error => res.status(500).json({ error }))
					})
					.catch(error => res.status(500).json({ error }))
				})
				.catch(error => res.status(500).json({ error }))
			})
		.catch(error => res.status(500).json({ error }))
})

app.route('/api/v1/happyhour/update')
.put(checkAuth, (req, res) => {
	const id 														= req.headers.businessID;
	const newHappyHourData = req.body;

	if (req.headers.statusType !== 'controller') {
		res.status(500).json({
			message:"You are not qualified to modify this business"
		})
	}

	for (let requiredParams of ['timeslot','drink_specials','food_specials','menu_pictures']) {
		if (!newHappyHourData[requiredParams]) {
			return res.status(422).json({
				error: `Missing required parameter ${requiredParams}`
			})
		}
	}

	db('happy_hour').where('id', id).select()
	.update(newHappyHourData, '*')
	.then(data => res.status(200).json({ data }))
	.catch(error => res.status(500).json({ error }))
	})
.patch(happyHourParams, checkAuth, (req, res) => {
	const id 					= req.headers.businessID;
	const newData = req.body;

	db('happy_hour').where('id', id).select(`${ newData }`)
	.update(newData, '*')
	.then(data => res.status(200).json({ data }))
	.catch(error => res.status(500).json({ error }))
})

app.delete('/api/v1/location/destroy/', checkAuth, (req, res) => {
	const id 										= req.headers.businessID;
	const businessName = req.body.businessName;

	if (req.headers.statusType !== 'controller') {
		return res.status(401).json({
			message:"You are not qualified to remove this business from the database"
		})
	}

	db('happy_hour').where("id", id).del()
	.then(id => {
		db('location').where('id', id).del()
		.then(id => {
			db('social_media').where('id', id).del()
			.then(id => {
				db('location_type').where('id', id).del()
				.then(id => {
					db('status_type').where('id', id).del()
					.then(id => {
						res.status(200).json({ message:`All data pertaining to ${businessName} has been permanantly destroyed` })
					})
					.catch(error => res.status(500).json({ error }))
				})
				.catch(error => res.status(500).json({ error }))
			})
			.catch(error => res.status(500).json({ error }))
		})
		.catch(error => res.status(500).json({ error }))
	})
	.catch(error => res.status(500).json({ error }))
});

//---> NOT WORKING AND I DON'T KNOW WHY <---//
app.route('/api/v1/locationtype/update/')
.patch(checkAuth, (req, res) => {
	const id 													= req.headers.businessID;
	const newLocationType = req.body;

	if (req.headers.statusType !== 'controller') {
		return res.status(401).json({
			message:'you are not qualified to modify this business'
		})
	}

		for (let requiredParams of ['location_type']) {
		if (!newLocationType[requiredParams]) {
			return res.status(422).json({
				error:`Missing required parameter ${requiredParams}`
			})
		}
	}

		db('location_type').where('id', id).select('type')
	.update(newLocationType, 'type')
	.then(replacementType => res.status(200).json({ replacementType }))
	.catch(error => res.status(500).json({ error }))
})

app.route('/api/v1/statustype/update/')
.put(checkAuth, (req, res) => {
	const id 							= req.headers.businessID
	const newStatus = req.body;

	for (let requiredParams of ['type']) {
		if (!newStatus[requiredParams]) {
			return res.status(422).json({
				error: `Missing required parameter ${requiredParams}`
			})
		}
	}

	db('status_type').where('id', id)
	.update(newStatus)
	.then(statusID => {
		db('location').where('id', id).select('*')
		.then(updatedLocation => {
			res.status(200).json({ updatedLocation })
		})
		.catch(error => res.status(500).json({ error }))
	})
	.catch(error => res.status(500).json({ error }))
})

app.get('/api/v1/statustype/:type', (req, res) => {
	const newType = req.params.type;

	db('status_type').where('type', newType).select('id')
	.then(data => {
		res.status(200).json({ data })
	})
})

app.get('/api/v1/statustype', (req, res) => {
	db('status_type').select('*')
	.then(data => {
		res.status(200).json({ data })
	})
})

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

module.exports = app;
<commit_msg>GET location type by type<commit_after>const 		express 											= require('express');
const 		app 															= express();
const 		path 														= require('path');
const 		bodyParser 								= require('body-parser');
const 		jwt 															= require('jsonwebtoken');
const { checkAuth,
								happyHourParams,
								statusTypeParams } = require('./serverMiddleware');
																													require('dotenv').config();

const PORT 																= process.env.PORT || 5000;
const environment 									= process.env.NODE_ENV || 'development';
const configuration 							= require('../knexfile')[environment];
const db 																		= require('knex')(configuration);

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
app.use(bodyParser.json());

// app.set('secretKey', process.env.SECRET_KEY);
app.set('secretKey', 'FAKE-process.env.SECRET_KEY');

// All remaining requests return the React app, so it can handle routing.
app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
})

app.post('/api/v1/admin/', (req, res) => {
	const payload = req.body;

	for (let requiredParams of ['businessID', "email"]) {
		if (!req.body[requiredParams]) {
			return res.status(422).json({ error: `Mising required parameter "${requiredParams}"`})
		}
	}

	if (payload.email.endsWith('@controllerAdmin.com')) {
		Object.assign(payload, { admin:true }, { businessID:req.body.businessID })
	} else { Object.assign(payload, { admin:false }) }

	const token = jwt.sign(payload, app.get('secretKey'), {expiresIn: '7d'})
	return res.status(200).json({ token })
})

app.route('/api/v1/location/')
.get((req, res) => {
	db('location').select()
	.then(allLocations =>  res.status(200).json({ allLocations }) )
	.catch(error => res.status(500).json({ ERROR: 'GET /api/v1/location/', error }))
})
.post(checkAuth, (req, res) => {
	const locationType 			= req.body.locationType;
	const newSocialMedia 	= req.body.socialMedia;
	const newLocation 				= req.body.location;
	const statusType 					= req.body.statusType;
	const newHappyHour 			= req.body.happyHour;

	for (let requiredParams of ["name","latitude","longitude"]) {
		if (!newLocation[requiredParams]) {
			return res.status(422).json({
				error: `missing required parameter ${requiredParams}`
			})
		}
	}

	db('location').where('name', newLocation.name).select()
	.then(data => {
		if (data.length > 0) {
			let ids = []
			for (let i=0;i<data.length;i++) { ids.push(data[i].id) }
			return res.status(300).json({
				message:`Warning, ${data.length} business(s) with the name ${newLocation.name} already exists in our database`,
				businessID: ids
			 })
			}
	})
	.catch(error => res.status(500).json({ error }))

		db('location_type').insert(locationType, 'id')
		.then(locTypeID => {
				Object.assign(newLocation, { location_type_id:locTypeID[0] })
				db('social_media').insert(newSocialMedia, 'id')
				.then(socialMediaID => {
					Object.assign(newLocation, { social_media_id:socialMediaID[0] })
					db('location').insert(newLocation, ['id'])
					.then(newLocID => {
						db('status_type').insert(statusType, 'id')
						.then(statusID => {
							Object.assign(newHappyHour, { status_type_id:statusID[0] }, { location_id:newLocID[0].id })
							db('happy_hour').insert(newHappyHour, ['location_id'])
							.then(locID => {
								db('location').where('id', locID[0].location_id).select()
								.then(data => res.status(200).json({ data }))
							})
							.catch(error => res.status(500).json({ error }))
						})
						.catch(error => res.status(500).json({ error }))
					})
					.catch(error => res.status(500).json({ error }))
				})
				.catch(error => res.status(500).json({ error }))
			})
		.catch(error => res.status(500).json({ error }))
})

app.route('/api/v1/happyhour/update')
.put(checkAuth, (req, res) => {
	const id 														= req.headers.businessID;
	const newHappyHourData = req.body;

	if (req.headers.statusType !== 'controller') {
		res.status(500).json({
			message:"You are not qualified to modify this business"
		})
	}

	for (let requiredParams of ['timeslot','drink_specials','food_specials','menu_pictures']) {
		if (!newHappyHourData[requiredParams]) {
			return res.status(422).json({
				error: `Missing required parameter ${requiredParams}`
			})
		}
	}

	db('happy_hour').where('id', id).select()
	.update(newHappyHourData, '*')
	.then(data => res.status(200).json({ data }))
	.catch(error => res.status(500).json({ error }))
	})
.patch(happyHourParams, checkAuth, (req, res) => {
	const id 					= req.headers.businessID;
	const newData = req.body;

	db('happy_hour').where('id', id).select(`${ newData }`)
	.update(newData, '*')
	.then(data => res.status(200).json({ data }))
	.catch(error => res.status(500).json({ error }))
})

app.delete('/api/v1/location/destroy/', checkAuth, (req, res) => {
	const id 										= req.headers.businessID;
	const businessName = req.body.businessName;

	if (req.headers.statusType !== 'controller') {
		return res.status(401).json({
			message:"You are not qualified to remove this business from the database"
		})
	}

	db('happy_hour').where("id", id).del()
	.then(id => {
		db('location').where('id', id).del()
		.then(id => {
			db('social_media').where('id', id).del()
			.then(id => {
				db('location_type').where('id', id).del()
				.then(id => {
					db('status_type').where('id', id).del()
					.then(id => {
						res.status(200).json({ message:`All data pertaining to ${businessName} has been permanantly destroyed` })
					})
					.catch(error => res.status(500).json({ error }))
				})
				.catch(error => res.status(500).json({ error }))
			})
			.catch(error => res.status(500).json({ error }))
		})
		.catch(error => res.status(500).json({ error }))
	})
	.catch(error => res.status(500).json({ error }))
});

//---> NOT WORKING AND I DON'T KNOW WHY <---//
app.route('/api/v1/locationtype/update/')
.patch(checkAuth, (req, res) => {
	const id 													= req.headers.businessID;
	const newLocationType = req.body;

	if (req.headers.statusType !== 'controller') {
		return res.status(401).json({
			message:'you are not qualified to modify this business'
		})
	}

		for (let requiredParams of ['location_type']) {
		if (!newLocationType[requiredParams]) {
			return res.status(422).json({
				error:`Missing required parameter ${requiredParams}`
			})
		}
	}

	db('location_type').where('id', id).select('type')
	.update(newLocationType, 'type')
	.then(replacementType => res.status(200).json({ replacementType }))
	.catch(error => res.status(500).json({ error }))
})

app.get('/api/v1/locationtype/:type', (req,res) => {
	const newType = req.params.type;

	db('location_type').where('type', newType).select('*')
	.then(data => {
		res.status(200).json({ data })
	})
	.catch(error => res.status(400).json({ error }))
})

app.route('/api/v1/statustype/update/')
.put(checkAuth, (req, res) => {
	const id 							= req.headers.businessID
	const newStatus = req.body;

	for (let requiredParams of ['type']) {
		if (!newStatus[requiredParams]) {
			return res.status(422).json({
				error: `Missing required parameter ${requiredParams}`
			})
		}
	}

	db('status_type').where('id', id)
	.update(newStatus)
	.then(statusID => {
		db('location').where('id', id).select('*')
		.then(updatedLocation => {
			res.status(200).json({ updatedLocation })
		})
		.catch(error => res.status(500).json({ error }))
	})
	.catch(error => res.status(500).json({ error }))
})

app.get('/api/v1/statustype/:type', (req, res) => {
	const newType = req.params.type;

	db('status_type').where('type', newType).select('id')
	.then(data => res.status(200).json({ data }))
	.catch(error => res.status(400).json({ error }))
})

app.get('/api/v1/statustype', (req,res) => {
	db('status_type').select('*')
	.then(data => {
		res.status(200).json({ data })
	})
})

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

module.exports = app;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014 and beyond Dwayne Charrington
 * Email: dwaynecharrington (at) gmail (dot) com
 * Twitter: abolitionof_
 * Licensed under MIT
 * @author Dwayne Charrington
 * @version 1.0
 */

;(function($, window, document, History, undefined) {

    // Events trigger

    // While loading: wpAjax.loading: (event, url)
    // If failed: wpAjax.failed: (event, url)
    // Content loaded: wpAjax.loaded: (event, data, url)
    // Content loaded and populated: wpAjax.complete: (event, contentEl)

    /*
        Example:

        // Call this from within a click event
        wpAjax.trigger("http://www.someurl.com");

        $(document).on("wpAjax.loaded", function(event, url) {

        });

        $(document).on("wpAjax.failed", function(event, url) {

        });

        // All data has loaded
        $(document).on("wpAjax.loaded", function(event, data, url) {

        });

        // All data has been populated the content element returned
        $(document).on("wpAjax.complete", function(event, contentEl) {

        });
    */

    // Are we already performing a request?
    var isLoading = false;

    // Main WP Ajax object
    var wpAjax = {};

    // Options
    var settings = {
            content: '#content',      // This is our container
            cacheRequests: true,  // Use HTML5 localStorage to cache pages?
            cacheExpiry: 1,          // Time in hours cached items should be cached for
            waitForImages: true,   // Wait for images to load before loading a page?
            debug: false               // Debug mode shows console messages if true
        },
        o = settings;

    // These two elements never disappear and are always consistent
    var $body    = $("body");
    var $content = $(o.content);

    // Statechange when the URL changes, we roll
    $(window).on("statechange", function() {
        var State = History.getState();

        log("HTML5 History statechange event trigger with URL: "+State.url);

        // Load the page if we're not already on it
        if (State.url !== wpAjax.getCurrentUrl()) {
            log("Calling the wpAjax.loadPage function with State.url as its parameter");
            wpAjax.loadPage(State.url);
        } else {
            log("AJAX request not performed as user is already on the requested page");
        }
    });

    // Allows us to configure wpAjax
    wpAjax.configure = function(options) {
        $.extend(settings, options);
        return this;
    };

    // Helper function for checking the current URL
    wpAjax.getCurrentUrl = function() {
        log("Method wpAjax.getCurrentUrl called");
        return window.location.href;
    };

    // Trigger a page load
    wpAjax.trigger = function(url) {
        log("Method wpAjax.trigger called which will call History.pushState and trigger a statechange");
        History.pushState({}, wpAjax.getTitle(), url);
    };

    // Load page function
    wpAjax.loadPage = function(url) {

        if (isLoading == false) {

            log("Method wpAjax.loadPage called and no other request taking place");

            // Apply a loading class to the body
            $body.addClass("loading-page");

            // Trigger loading event
            $(document).trigger("wpAjax.loading", [url]);

            // Before content is loaded in, fade out the old content
            wpAjax.fadeOutContent();

            // Perform our AJAX request
            wpAjax.doRequest(url, function() {
                wpAjax.processRequest(data, url);
            }, function() {
                isLoading = false;

                wpAjax.fadeInContent();

                // Trigger failed event
                $(document).trigger("wpAjax.failed", [url]);
            });

        } else {
            return false;
        }

    };

    // Fade out the content area
    wpAjax.fadeOutContent = function() {
        log("fadeOutContent method called");
        $content.animate({opacity:0}, 800);
    };

    // Fade in the content area
    wpAjax.fadeInContent = function() {
        log("fadeInContent method called");
        $content.animate({opacity:1}, 800);
    };

    // Performs an AJAX request to get the page title
    // Also has the advantage of pre-fetching the page
    // for us as well.
    wpAjax.getTitle = function(url) {
        var title = "";

        log("wpAjax.getTitle method called");

        wpAjax.doRequest(url, function(data) {
            title = $(data).filter("title").text();
        });

        return title;
    };

    // Handles performing the page load request
    // Leaves checking for other requests and validity to other functions
    wpAjax.doRequest = function(url, success, error) {

        // Do the fetching and stuff...
        $.ajax({
            url: url,
            localCache: o.cacheRequests,
            cacheTTL: o.cacheExpiry,
            type: 'GET',
            dataType: 'html',
            success: function(response) {
                log("AJAX request called and successful");
                success(response);
            },
            error: function() {
                log("AJAX request called and failed");
                if ($.isFunction(error)) {
                    error();
                }
            }
        });

    };

    // Once our AJAX request is done, this function is called
    // Which allows us to process the response
    wpAjax.processRequest = function(data, url) {
        var _html      = $(data);
        var _content = _html.find(o.content).html();

        // AJAX request is finished
        isLoading = false;

        log("Processing the data returned by the successful AJAX call");

        // Do we have content?
        if (_content && _content.length) {

             // AJAX load finished fire a loaded event with the data
             $(document).trigger("wpAjax.loaded", [data, url]);

            log("Content found from the AJAX request, determining what to do with it");

            // We want to wait for images to load before proceeding
            if (waitForImages) {

                // We have images to preload
                if ($(_content).find("img").length) {

                    log("Waiting for all images in the returned data to preload");

                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("Populated the content element");

                        // Wait for any newly populated images to load
                        contentEl.imagesLoaded().then(function() {

                            log("All images in AJAX loaded content have preloaded");

                            // Replace body classes with those of the loaded body classes
                            $body.attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(data.substring(data.indexOf("<body"), data.indexOf("") + 7))[3]);

                            // All content has been populated, assume we've succeeded
                            $(document).trigger("wpAjax.complete", [contentEl]);

                        });

                    });

                }

            } else {

                // Populate the content element
                wpAjax.populateContent(_content, function(contentEl) {

                    log("Requested AJAX content has been added to the content element and classes changed");

                    // Replace body classes with those of the loaded body classes
                    $body.attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(data.substring(data.indexOf("<body"), data.indexOf("") + 7))[3]);

                    // All content has been populated, assume we've succeeded
                    $(document).trigger("wpAjax.complete", [contentEl]);

                }
            }

            // Fade in the content DIV now we've done what we've wanted with it
            wpAjax.fadeInContent();

        } else {
            log("Returned AJAX content is empty. Could be a problem server-side.");
        }
    };

    // Populates the appropriate content DIV with our
    // load content from the AJAX request (if successful)
    wpAjax.populateContent = function(content, callback) {
        // Populate the content element
        $content.html(content);

        // If we have a callback function
        if ($.isFunction(callback)) {
            callback($content);
        }
    };

    // Console log wrapper checks if debugging is on
    function log(msg) {
        if (o.debug) {
            console.log(msg);
        }
    }

    // Expose our method to the world
    return wpAjax;

})(jQuery, window, document, window.History);

// github.com/paulirish/jquery-ajax-localstorage-cache
// dependent on Modernizr's localStorage test

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

  // Modernizr.localstorage, version 3 12/12/13
  function hasLocalStorage() {
    var mod = 'modernizr';
    try {
      localStorage.setItem(mod, mod);
      localStorage.removeItem(mod);
      return true;
    } catch(e) {
      return false;
    }
  }

  // Cache it ?
  if ( !hasLocalStorage() || !options.localCache ) return;

  var hourstl = options.cacheTTL || 5;

  var cacheKey = options.cacheKey ||
                 options.url.replace( /jQuery.*/,'' ) + options.type + (options.data || '');

  // isCacheValid is a function to validate cache
  if ( options.isCacheValid &&  ! options.isCacheValid() ){
    localStorage.removeItem( cacheKey );
  }
  // if there's a TTL that's expired, flush this item
  var ttl = localStorage.getItem(cacheKey + 'cachettl');
  if ( ttl && ttl < +new Date() ){
    localStorage.removeItem( cacheKey );
    localStorage.removeItem( cacheKey  + 'cachettl' );
    ttl = 'expired';
  }

  var value = localStorage.getItem( cacheKey );
  if ( value ){
    //In the cache? So get it, apply success callback & abort the XHR request
    // parse back to JSON if we can.
    if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
    options.success( value );
    // Abort is broken on JQ 1.5 :(
    jqXHR.abort();
  } else {

    //If it not in the cache, we change the success callback, just put data on localstorage and after that apply the initial callback
    if ( options.success ) {
      options.realsuccess = options.success;
    }
    options.success = function( data ) {
      var strdata = data;
      if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );

      // Save the data to localStorage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
      try {
        localStorage.setItem( cacheKey, strdata );
      } catch (e) {
        // Remove any incomplete data that may have been saved before the exception was caught
        localStorage.removeItem( cacheKey );
        localStorage.removeItem( cacheKey + 'cachettl' );
        if ( options.cacheError ) options.cacheError( e, cacheKey, strdata );
      }

      if ( options.realsuccess ) options.realsuccess( data );
    };

    // store timestamp
    if ( ! ttl || ttl === 'expired' ) {
      localStorage.setItem( cacheKey  + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl );
    }

  }
});
<commit_msg>Cleaning up debug calls to be prefixed with method name and a colon<commit_after>/**
 * Copyright (c) 2014 and beyond Dwayne Charrington
 * Email: dwaynecharrington (at) gmail (dot) com
 * Twitter: abolitionof_
 * Licensed under MIT
 * @author Dwayne Charrington
 * @version 1.0
 */

;(function($, window, document, History, undefined) {

    // Events trigger

    // While loading: wpAjax.loading: (event, url)
    // If failed: wpAjax.failed: (event, url)
    // Content loaded: wpAjax.loaded: (event, data, url)
    // Content loaded and populated: wpAjax.complete: (event, contentEl)

    /*
        Example:

        // Call this from within a click event
        wpAjax.trigger("http://www.someurl.com");

        $(document).on("wpAjax.loaded", function(event, url) {

        });

        $(document).on("wpAjax.failed", function(event, url) {

        });

        // All data has loaded
        $(document).on("wpAjax.loaded", function(event, data, url) {

        });

        // All data has been populated the content element returned
        $(document).on("wpAjax.complete", function(event, contentEl) {

        });
    */

    // Are we already performing a request?
    var isLoading = false;

    // Main WP Ajax object
    var wpAjax = {};

    // Options
    var settings = {
            content: '#content',      // This is our container
            cacheRequests: true,  // Use HTML5 localStorage to cache pages?
            cacheExpiry: 1,          // Time in hours cached items should be cached for
            waitForImages: true,   // Wait for images to load before loading a page?
            debug: false               // Debug mode shows console messages if true
        },
        o = settings;

    // These two elements never disappear and are always consistent
    var $body    = $("body");
    var $content = $(o.content);

    // Statechange when the URL changes, we roll
    $(window).on("statechange", function() {
        var State = History.getState();

        log("Event.statechange: HTML5 History statechange event trigger with URL: "+State.url);

        // Load the page if we're not already on it
        if (State.url !== wpAjax.getCurrentUrl()) {
            log("Event.statechange: Calling the wpAjax.loadPage function with State.url as its parameter");
            wpAjax.loadPage(State.url);
        } else {
            log("Event.statechange: AJAX request not performed as user is already on the requested page");
        }
    });

    // Allows us to configure wpAjax
    wpAjax.configure = function(options) {
        log("configure: Setting options for Wpajax");
        $.extend(settings, options);
        return this;
    };

    // Returns whether or not we are currently in the middle of an AJAX request
    wpAjax.requestStatus = function() {
        log("requestStatus: Return current loading state");
        return isLoading;
    };

    // Helper function for checking the current URL
    wpAjax.getCurrentUrl = function() {
        log("getCurrentUrl: Getting the current browser address URL");
        return window.location.href;
    };

    // Trigger a page load
    wpAjax.trigger = function(url) {
        log("trigger:  Calling History.pushState which will trigger a statechange");
        History.pushState({}, wpAjax.getTitle(url), url);
    };

    // Load page function
    wpAjax.loadPage = function(url) {

        if (isLoading == false) {

            log("Method wpAjax.loadPage called and no other request taking place");

            // Apply a loading class to the body
            $body.addClass("loading-page");

            // Trigger loading event
            $(document).trigger("wpAjax.loading", [url]);

            // Before content is loaded in, fade out the old content
            wpAjax.fadeOutContent();

            // Perform our AJAX request
            wpAjax.doRequest(url, function() {
                wpAjax.processRequest(data, url);
            }, function() {
                isLoading = false;

                wpAjax.fadeInContent();

                // Trigger failed event
                $(document).trigger("wpAjax.failed", [url]);
            });

        } else {
            return false;
        }

    };

    // Fade out the content area
    wpAjax.fadeOutContent = function() {
        log("fadeOutContent: Animating content element out");
        $content.animate({opacity:0}, 800);
    };

    // Fade in the content area
    wpAjax.fadeInContent = function() {
        log("fadeInContent: Animating content element in");
        $content.animate({opacity:1}, 800);
    };

    // Performs an AJAX request to get the page title
    // Also has the advantage of pre-fetching the page
    // for us as well.
    wpAjax.getTitle = function(url) {
        var title = "";

        log("getTitle: Calling wpAjax.doRequest now to get the title");

        wpAjax.doRequest(url, function(data) {
            title = $(data).filter("title").text();
            log("getTitle: doRequest AJAX call successful. Title returned: "+title+" ");
        });

        return title;
    };

    // Handles performing the page load request
    // Leaves checking for other requests and validity to other functions
    wpAjax.doRequest = function(url, success, error) {

        log("doRequest: About to perform an AJAX call");

        // Do the fetching and stuff...
        $.ajax({
            url: url,
            localCache: o.cacheRequests,
            cacheTTL: o.cacheExpiry,
            type: 'GET',
            dataType: 'html',
            success: function(response) {
                log("doRequest: AJAX success callback");
                success(response);
            },
            error: function() {
                log("doRequest: AJAX error callback");
                if ($.isFunction(error)) {
                    error();
                }
            }
        });

    };

    // Once our AJAX request is done, this function is called
    // Which allows us to process the response
    wpAjax.processRequest = function(data, url) {
        var _html      = $(data);
        var _content = _html.find(o.content).html();

        // AJAX request is finished
        isLoading = false;

        log("processRequest: Processing the data returned by a successful AJAX call");

        // Do we have content?
        if (_content && _content.length) {

             // AJAX load finished fire a loaded event with the data
             $(document).trigger("wpAjax.loaded", [data, url]);

            log("processRequest: Content found from the AJAX request, determining what to do with it");

            // We want to wait for images to load before proceeding
            if (waitForImages) {

                log("processRequest Wait for images option is enabled, finding images");

                // We have images to preload
                if ($(_content).find("img").length) {

                    log("processRequest: We found images. Waiting for all images in the returned data to preload");

                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("processRequest: Populated the content element with content, about to preload iamges");

                        // Wait for any newly populated images to load
                        contentEl.imagesLoaded().then(function() {

                            log("processRequest: All images in AJAX loaded content have preloaded");

                            // Replace body classes with those of the loaded body classes
                            $body.attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(data.substring(data.indexOf("<body"), data.indexOf("") + 7))[3]);

                            // All content has been populated, assume we've succeeded
                            $(document).trigger("wpAjax.complete", [contentEl]);

                        });

                    });

                }

            } else {

                // Populate the content element
                wpAjax.populateContent(_content, function(contentEl) {

                    log("processRequest: Requested AJAX content has been added to the content element and classes changed");

                    // Replace body classes with those of the loaded body classes
                    $body.attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(data.substring(data.indexOf("<body"), data.indexOf("") + 7))[3]);

                    // All content has been populated, assume we've succeeded
                    $(document).trigger("wpAjax.complete", [contentEl]);

                }
            }

            // Fade in the content DIV now we've done what we've wanted with it
            wpAjax.fadeInContent();

        } else {
            log("processRequest: Returned AJAX content is empty. Could be a problem server-side.");
        }
    };

    // Populates the appropriate content DIV with our
    // load content from the AJAX request (if successful)
    wpAjax.populateContent = function(content, callback) {
        // Populate the content element
        $content.html(content);

        // If we have a callback function
        if ($.isFunction(callback)) {
            callback($content);
        }
    };

    // Console log wrapper checks if debugging is on
    function log(msg) {
        if (o.debug) {
            console.log(msg);
        }
    }

    // Expose our method to the world
    return wpAjax;

})(jQuery, window, document, window.History);

// github.com/paulirish/jquery-ajax-localstorage-cache
// dependent on Modernizr's localStorage test

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

  // Modernizr.localstorage, version 3 12/12/13
  function hasLocalStorage() {
    var mod = 'modernizr';
    try {
      localStorage.setItem(mod, mod);
      localStorage.removeItem(mod);
      return true;
    } catch(e) {
      return false;
    }
  }

  // Cache it ?
  if ( !hasLocalStorage() || !options.localCache ) return;

  var hourstl = options.cacheTTL || 5;

  var cacheKey = options.cacheKey ||
                 options.url.replace( /jQuery.*/,'' ) + options.type + (options.data || '');

  // isCacheValid is a function to validate cache
  if ( options.isCacheValid &&  ! options.isCacheValid() ){
    localStorage.removeItem( cacheKey );
  }
  // if there's a TTL that's expired, flush this item
  var ttl = localStorage.getItem(cacheKey + 'cachettl');
  if ( ttl && ttl < +new Date() ){
    localStorage.removeItem( cacheKey );
    localStorage.removeItem( cacheKey  + 'cachettl' );
    ttl = 'expired';
  }

  var value = localStorage.getItem( cacheKey );
  if ( value ){
    //In the cache? So get it, apply success callback & abort the XHR request
    // parse back to JSON if we can.
    if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
    options.success( value );
    // Abort is broken on JQ 1.5 :(
    jqXHR.abort();
  } else {

    //If it not in the cache, we change the success callback, just put data on localstorage and after that apply the initial callback
    if ( options.success ) {
      options.realsuccess = options.success;
    }
    options.success = function( data ) {
      var strdata = data;
      if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );

      // Save the data to localStorage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
      try {
        localStorage.setItem( cacheKey, strdata );
      } catch (e) {
        // Remove any incomplete data that may have been saved before the exception was caught
        localStorage.removeItem( cacheKey );
        localStorage.removeItem( cacheKey + 'cachettl' );
        if ( options.cacheError ) options.cacheError( e, cacheKey, strdata );
      }

      if ( options.realsuccess ) options.realsuccess( data );
    };

    // store timestamp
    if ( ! ttl || ttl === 'expired' ) {
      localStorage.setItem( cacheKey  + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl );
    }

  }
});
<|endoftext|>


<commit_before>const express = require('express')
const bodyParser = require('body-parser');
const path = require('path');
const { User, Template, Activity, History } = require('../db/mongoose-schemas.js')
const app = express();
const logger = require('morgan');
const cors = require('cors');
const jwt = require('express-jwt');
const { secret, audience } = require('./secret/jwt');

app.use(cors());

app.set('port', (process.env.PORT || 3002));
const PORT = app.get('port');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

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

// AUTH0
app.use('/login', express.static(path.join(__dirname, '../src')));

//HANDLE GET REQUESTS
const authCheck = jwt({ secret, audience, credentialsRequired: true });
// SET UP A PUBLIC AND PRIVATE ENDPOINT
app.get('/api/public', (req, res) => {
  console.log('hi from /api/public')
  res.json({ message: "Hello from a public endpoint!. You don't need to be authenticated to see this." })
});

// to protect this endpoint pass our middleware as second arg
// will require an auth header to be present for user to go through to this endpoint
app.get('/api/private', authCheck, (req, res) => {
  res.json({ message: "Hello from a private endpoint!. You DO need to be authenticated to see this." })
});

//

app.get('/users', function(req, res) {
  var users = [];
  User.find({}, function(err, user) {
    if (err) console.log(err);
    users.push(user);
  })
  .then(function() {
    console.log(users);
    res.send(users);
  });
});

app.get('/templates', function(req, res) {
  var templates = [];

  Template.find({}, function(err, template) {
    if (err) console.log(err);
    templates.push(template);
  })
  .then(function() {
    console.log(templates);
    res.send(templates);
  });
});

app.get('/activities', function(req, res) {
  var activities = [];

  Activity.find({}, function(err, activity) {
    if (err) console.log(err);
    activities.push(activity);
  })
  .then(function() {
    console.log(activities);
    res.send(activities);
  });
});

app.get('/histories', function(req, res) {
  var histories = [];

  History.find({}, function(err, history) {
    if (err) console.log(err);
    Histories.push(history);
  })
  .then(function() {
    console.log(histories);
    res.send(histories);
  });
});

//HANDLE POST REQUESTS

app.post('/users', function(req, res) {
  console.log(req.body);
  User.create(req.body);
  res.send('Posted User');
});

app.post('/templates', function(req, res) {
  console.log(req.body);
  Template.create(req.body);
  res.send('Posted Template');
});

app.post('/activities', function(req, res) {
  console.log(req.body);
  Activity.create(req.body);
  res.send('Posted Activity');
});

app.post('/histories', function(req, res) {
  console.log(req.body);
  History.create(req.body);
  res.send('Posted History');
});

app.listen(PORT, function() {
  console.log(`Node app is running on http://localhost:${PORT}`);
});
<commit_msg>Add Private Vars Attached to process.env<commit_after>const express = require('express')
const bodyParser = require('body-parser');
const path = require('path');
const { User, Template, Activity, History } = require('../db/mongoose-schemas.js')
const app = express();
const logger = require('morgan');
const cors = require('cors'); // allow cors headers
const jwt = require('express-jwt');
require('dotenv').config(); // allows you to use .env file

app.use(cors());

app.set('port', (process.env.PORT || 3002));
const PORT = app.get('port');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

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

// AUTH0
app.use('/login', express.static(path.join(__dirname, '../src')));

//HANDLE GET REQUESTS
const authCheck = jwt({ secret: process.env.SECRET, audience: process.env.AUDIENCE, credentialsRequired: true });
// SET UP A PUBLIC AND PRIVATE ENDPOINT
app.get('/api/public', (req, res) => {
  console.log('hi from /api/public')
  res.json({ message: "Hello from a public endpoint!. You don't need to be authenticated to see this." })
});

// to protect this endpoint pass our middleware as second arg
// will require an auth header to be present for user to go through to this endpoint
app.get('/api/private', authCheck, (req, res) => {
  res.json({ message: "Hello from a private endpoint!. You DO need to be authenticated to see this." })
});

//

app.get('/users', function(req, res) {
  var users = [];
  User.find({}, function(err, user) {
    if (err) console.log(err);
    users.push(user);
  })
  .then(function() {
    console.log(users);
    res.send(users);
  });
});

app.get('/templates', function(req, res) {
  var templates = [];

  Template.find({}, function(err, template) {
    if (err) console.log(err);
    templates.push(template);
  })
  .then(function() {
    console.log(templates);
    res.send(templates);
  });
});

app.get('/activities', function(req, res) {
  var activities = [];

  Activity.find({}, function(err, activity) {
    if (err) console.log(err);
    activities.push(activity);
  })
  .then(function() {
    console.log(activities);
    res.send(activities);
  });
});

app.get('/histories', function(req, res) {
  var histories = [];

  History.find({}, function(err, history) {
    if (err) console.log(err);
    Histories.push(history);
  })
  .then(function() {
    console.log(histories);
    res.send(histories);
  });
});

//HANDLE POST REQUESTS

app.post('/users', function(req, res) {
  console.log(req.body);
  User.create(req.body);
  res.send('Posted User');
});

app.post('/templates', function(req, res) {
  console.log(req.body);
  Template.create(req.body);
  res.send('Posted Template');
});

app.post('/activities', function(req, res) {
  console.log(req.body);
  Activity.create(req.body);
  res.send('Posted Activity');
});

app.post('/histories', function(req, res) {
  console.log(req.body);
  History.create(req.body);
  res.send('Posted History');
});

app.listen(PORT, function() {
  console.log(`Node app is running on http://localhost:${PORT}`);
});
<|endoftext|>


<commit_before>var fortune = require('fortune'),
	express = require('express');

var app = fortune ({
    db: 'techreadytweets'
  })
  .resource('tweet', {
    author: String,
    message: String,
    timestamp: Number
  });

app.use(express.static(__dirname + '/../client/dist'));

app.listen(1337);
<commit_msg>Adjust port<commit_after>var fortune = require('fortune'),
	express = require('express');

var app = fortune ({
    db: 'techreadytweets'
  })
  .resource('tweet', {
    author: String,
    message: String,
    timestamp: Number
  });

app.use(express.static(__dirname + '/../client/dist'));

app.listen(process.env.PORT || 80);
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var http = require('http');

var express = require('express');
var bodyParser = require('body-parser');

var pjson = require('../package.json');
var serverSentEvents = require('./sse');
var Rooms = require('./rooms');
var utils = require('./utils');

function requireJSON(req, res, next) {
  if (req.method !== "POST") {
    next();
    return;
  }

  if (req.get("Content-Type") !== "application/json") {
    res.json(400, ['application/json']);
    return;
  }

  next();
}

function SmokeServer(config) {
  this.config = config;
  this.rooms = new Rooms();

  this.app = express();
  this.app.use(bodyParser.json());
  this.app.use(requireJSON);
  this.app.use(serverSentEvents);
  this.app.get("/",             this.hello.bind(this));
  this.app.post("/rooms",       this.createRoom.bind(this));
  this.app.get("/rooms/:room",  this.eventStream.bind(this));
  this.app.post("/rooms/:room", this.forwardEvent.bind(this));

  this.server = http.createServer(this.app);
}

SmokeServer.prototype = {
  /**
   * Displays some version information at the root of the service.
   **/
  hello: function(req, res) {
    var infos = {
      name: pjson.name,
      description: pjson.description,
      version: pjson.version,
      endpoint: req.protocol + "://" + req.get('host')
    };

    res.json(200, infos);
  },

  /**
   * Create a room as a point of rendez-vous for users.
   **/
  createRoom: function(req, res) {
    var roomId = req.param('room') || utils.generateID();
    var ttl    = req.param('ttl') || 60;
    ttl = ttl * 1000;

    if (this.rooms.get(roomId)) {
      res.json(409, "");
      return;
    }

    var room = this.rooms.create(roomId, ttl);
    room.on("timeout", function() {
      room.stopHeartbeat();
      this.rooms.remove(roomId);
    }.bind(this));

    room.on("heartbeat", function() {
      room.users.forEach(function(user) {
        user.connection.ssePing();
      });
    }.bind(this));

    room.startHeartbeat();
    room.timeoutAfter(room.ttl);

    res.json(200, {room: roomId});
  },

  eventStream: function(req, res) {
    var roomId = req.param('room');
    var room, pinger;

    room = this.rooms.get(roomId);
    if (room === undefined) {
      res.json(404, "");
      return;
    }

    var peer = room.users.create(res);
    room.clearTimeout();

    peer.connection.sse("uid", {uid: peer.uid, token: peer.token});
    peer.on("disconnection", function() {
      room.users.remove(peer);
      clearInterval(pinger);

      room.users.forEach(function(user) {
        user.connection.sse("buddyleft", {peer: peer.uid});
      });

      if (room.empty())
        room.timeoutAfter(room.ttl);
    });

    room.users.forEach(function(user) {
      if (user === peer)
        return;

      user.connection.sse("newbuddy", {peer: peer.uid});
    });
  },

  forwardEvent: function(req, res) {
    var roomId  = req.param('room');
    var event   = req.body;
    var room    = this.rooms.get(roomId);
    var user, peer;

    if (room === undefined) {
      res.json(404, "");
      return;
    }

    user = room.users.getByToken(event.token);
    peer = room.users.getByUid(event.peer);
    if (user === undefined || peer === undefined) {
      res.json(400, "");
      return;
    }

    if ((typeof event.payload) !== "object") {
      res.json(400, "");
      return;
    }

    event.payload.peer = user.uid;
    peer.connection.sse(event.type, event.payload);

    res.send(200, "ok");
  },

  run: function(callback) {
    this.server.listen(7665, callback);
  },

  stop: function(callback) {
    this.server.close(callback);
  },
};

module.exports = SmokeServer;

<commit_msg>Fix the requireJSON middleware<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var http = require('http');

var express = require('express');
var bodyParser = require('body-parser');

var pjson = require('../package.json');
var serverSentEvents = require('./sse');
var Rooms = require('./rooms');
var utils = require('./utils');

function requireJSON(req, res, next) {
  if (req.method !== "POST") {
    next();
    return;
  }

  if (req.get("Content-Type").indexOf("application/json") === -1) {
    res.json(400, ['application/json']);
    return;
  }

  next();
}

function SmokeServer(config) {
  this.config = config;
  this.rooms = new Rooms();

  this.app = express();
  this.app.use(bodyParser.json());
  this.app.use(requireJSON);
  this.app.use(serverSentEvents);
  this.app.get("/",             this.hello.bind(this));
  this.app.post("/rooms",       this.createRoom.bind(this));
  this.app.get("/rooms/:room",  this.eventStream.bind(this));
  this.app.post("/rooms/:room", this.forwardEvent.bind(this));

  this.server = http.createServer(this.app);
}

SmokeServer.prototype = {
  /**
   * Displays some version information at the root of the service.
   **/
  hello: function(req, res) {
    var infos = {
      name: pjson.name,
      description: pjson.description,
      version: pjson.version,
      endpoint: req.protocol + "://" + req.get('host')
    };

    res.json(200, infos);
  },

  /**
   * Create a room as a point of rendez-vous for users.
   **/
  createRoom: function(req, res) {
    var roomId = req.param('room') || utils.generateID();
    var ttl    = req.param('ttl') || 60;
    ttl = ttl * 1000;

    if (this.rooms.get(roomId)) {
      res.json(409, "");
      return;
    }

    var room = this.rooms.create(roomId, ttl);
    room.on("timeout", function() {
      room.stopHeartbeat();
      this.rooms.remove(roomId);
    }.bind(this));

    room.on("heartbeat", function() {
      room.users.forEach(function(user) {
        user.connection.ssePing();
      });
    }.bind(this));

    room.startHeartbeat();
    room.timeoutAfter(room.ttl);

    res.json(200, {room: roomId});
  },

  eventStream: function(req, res) {
    var roomId = req.param('room');
    var room, pinger;

    room = this.rooms.get(roomId);
    if (room === undefined) {
      res.json(404, "");
      return;
    }

    var peer = room.users.create(res);
    room.clearTimeout();

    peer.connection.sse("uid", {uid: peer.uid, token: peer.token});
    peer.on("disconnection", function() {
      room.users.remove(peer);
      clearInterval(pinger);

      room.users.forEach(function(user) {
        user.connection.sse("buddyleft", {peer: peer.uid});
      });

      if (room.empty())
        room.timeoutAfter(room.ttl);
    });

    room.users.forEach(function(user) {
      if (user === peer)
        return;

      user.connection.sse("newbuddy", {peer: peer.uid});
    });
  },

  forwardEvent: function(req, res) {
    var roomId  = req.param('room');
    var event   = req.body;
    var room    = this.rooms.get(roomId);
    var user, peer;

    if (room === undefined) {
      res.json(404, "");
      return;
    }

    user = room.users.getByToken(event.token);
    peer = room.users.getByUid(event.peer);
    if (user === undefined || peer === undefined) {
      res.json(400, "");
      return;
    }

    if ((typeof event.payload) !== "object") {
      res.json(400, "");
      return;
    }

    event.payload.peer = user.uid;
    peer.connection.sse(event.type, event.payload);

    res.send(200, "ok");
  },

  run: function(callback) {
    this.server.listen(7665, callback);
  },

  stop: function(callback) {
    this.server.close(callback);
  },
};

module.exports = SmokeServer;

<|endoftext|>


<commit_before>const bodyParser = require('body-parser')
const express = require('express')

const app = express()

// Populates req.body as a Buffer.
app.use(bodyParser.raw({ type: 'text/plain' }))

app.post('/telegrams', function (req, res) {
  const telegram = req.body.toString()
  console.log(telegram)

  res.sendStatus(200)
})

app.listen(3000)
<commit_msg>Listen only on localhost by default<commit_after>const bodyParser = require('body-parser')
const express = require('express')

const app = express()

// Populates req.body as a Buffer.
app.use(bodyParser.raw({ type: 'text/plain' }))

app.post('/telegrams', function (req, res) {
  const telegram = req.body.toString()
  console.log(telegram)

  res.sendStatus(200)
})

app.listen(3000, '127.0.0.1')
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const path = require('path');
const morgan = require('morgan'); // logger
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const winston = require('./winston/config');

app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function () {
  winston.info('Mitosis NodeJS App listening on port ' + app.get('port'));
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(morgan('dev'));
app.use('/api', api);

// all other routes are handled by Angular
app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, '/../dist/index.html'));
});

require('./db/connect');
require('./db/user');
require('./kafka/consumer');
require('./mip/');

module.exports = app;

<commit_msg>remove mip<commit_after>'use strict';

const express = require('express');
const path = require('path');
const morgan = require('morgan'); // logger
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const winston = require('./winston/config');

app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function () {
  winston.info('Mitosis NodeJS App listening on port ' + app.get('port'));
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(morgan('dev'));
app.use('/api', api);

// all other routes are handled by Angular
app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, '/../dist/index.html'));
});

require('./db/connect');
require('./db/user');
require('./kafka/consumer');

module.exports = app;

<|endoftext|>


<commit_before>require('./rollbar')

var compress = require('compression')
var cors = require('cors')
var express = require('express')
var http = require('http')
var pug = require('pug')
var path = require('path')
var twilio = require('twilio')
var url = require('url')
var util = require('util')

var config = require('../config')

var PORT = Number(process.argv[2]) || 4000

var CORS_WHITELIST = [
  // Official WebTorrent site
  'http://webtorrent.io',
  'https://webtorrent.io',

  // Favor to friends :)
  'http://rollcall.audio',
  'https://rollcall.audio'
]

var secret
try {
  secret = require('../secret')
} catch (err) {}

var app = express()
var server = http.createServer(app)

// Trust "X-Forwarded-For" and "X-Forwarded-Proto" nginx headers
app.enable('trust proxy')

// Disable "powered by express" header
app.set('x-powered-by', false)

// Use pug for templates
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.engine('pug', pug.renderFile)

// Pretty print JSON
app.set('json spaces', 2)

// Use GZIP
app.use(compress())

app.use(function (req, res, next) {
  // Force SSL
  if (config.isProd && req.protocol !== 'https') {
    return res.redirect('https://' + (req.hostname || 'instant.io') + req.url)
  }

  // Redirect www to non-www
  if (config.isProd && req.hostname === 'www.instant.io') {
    return res.redirect('https://instant.io' + req.url)
  }

  // Use HTTP Strict Transport Security
  // Lasts 1 year, incl. subdomains, allow browser preload list
  if (config.isProd) {
    res.header(
      'Strict-Transport-Security',
      'max-age=31536000; includeSubDomains; preload'
    )
  }

  // Add cross-domain header for fonts, required by spec, Firefox, and IE.
  var extname = path.extname(req.url)
  if (['.eot', '.ttf', '.otf', '.woff', '.woff2'].indexOf(extname) >= 0) {
    res.header('Access-Control-Allow-Origin', '*')
  }

  // Prevents IE and Chrome from MIME-sniffing a response. Reduces exposure to
  // drive-by download attacks on sites serving user uploaded content.
  res.header('X-Content-Type-Options', 'nosniff')

  // Prevent rendering of site within a frame.
  res.header('X-Frame-Options', 'DENY')

  // Enable the XSS filter built into most recent web browsers. It's usually
  // enabled by default anyway, so role of this headers is to re-enable for this
  // particular website if it was disabled by the user.
  res.header('X-XSS-Protection', '1; mode=block')

  // Force IE to use latest rendering engine or Chrome Frame
  res.header('X-UA-Compatible', 'IE=Edge,chrome=1')

  next()
})

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

app.get('/', function (req, res) {
  res.render('index', {
    title: 'Instant.io - Streaming file transfer over WebTorrent'
  })
})

// Fetch new iceServers from twilio token regularly
var iceServers
var twilioClient
try {
  twilioClient = twilio(secret.twilio.accountSid, secret.twilio.authToken)
} catch (err) {}

function updateIceServers () {
  twilioClient.tokens.create({}, function (err, token) {
    if (err) return console.error(err.message || err)
    if (!token.iceServers) {
      return console.error('twilio response ' + util.inspect(token) + ' missing iceServers')
    }

    // Support new spec (`RTCIceServer.url` was renamed to `RTCIceServer.urls`)
    iceServers = token.iceServers.map(function (server) {
      if (server.url != null) {
        server.urls = server.url
        delete server.url
      }
      return server
    })
  })
}

if (twilioClient) {
  setInterval(updateIceServers, 60 * 60 * 4 * 1000).unref()
  updateIceServers()
}

// WARNING: This is *NOT* a public endpoint. Do not depend on it in your app.
app.get('/__rtcConfig__', cors({
  origin: function (origin, cb) {
    var allowed = CORS_WHITELIST.indexOf(origin) >= 0 ||
      /https?:\/\/localhost(:|$)/.test(origin) ||
      /https?:\/\/airtap\.local(:|$)/.test(origin)
    cb(null, allowed)
  }
}), function (req, res) {
  if (!iceServers) return res.status(404).send({ iceServers: [] })
  res.send({
    comment: 'WARNING: This is *NOT* a public endpoint. Do not depend on it in your app',
    iceServers: iceServers
  })
})

app.get('/500', (req, res, next) => {
  next(new Error('Manually visited /500'))
})

app.get('*', function (req, res) {
  res.status(404).render('error', {
    title: '404 Page Not Found - Instant.io',
    message: '404 Not Found'
  })
})

if (global.rollbar) app.use(global.rollbar.errorHandler())

// error handling middleware
app.use(function (err, req, res, next) {
  console.error(err.stack)
  const code = typeof err.code === 'number' ? err.code : 500
  res.status(code).render('error', {
    title: '500 Internal Server Error - Instant.io',
    message: err.message || err
  })
})

server.listen(PORT, function () {
  console.log('listening on port %s', server.address().port)
})
<commit_msg>standard<commit_after>require('./rollbar')

var compress = require('compression')
var cors = require('cors')
var express = require('express')
var http = require('http')
var pug = require('pug')
var path = require('path')
var twilio = require('twilio')
var util = require('util')

var config = require('../config')

var PORT = Number(process.argv[2]) || 4000

var CORS_WHITELIST = [
  // Official WebTorrent site
  'http://webtorrent.io',
  'https://webtorrent.io',

  // Favor to friends :)
  'http://rollcall.audio',
  'https://rollcall.audio'
]

var secret
try {
  secret = require('../secret')
} catch (err) {}

var app = express()
var server = http.createServer(app)

// Trust "X-Forwarded-For" and "X-Forwarded-Proto" nginx headers
app.enable('trust proxy')

// Disable "powered by express" header
app.set('x-powered-by', false)

// Use pug for templates
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.engine('pug', pug.renderFile)

// Pretty print JSON
app.set('json spaces', 2)

// Use GZIP
app.use(compress())

app.use(function (req, res, next) {
  // Force SSL
  if (config.isProd && req.protocol !== 'https') {
    return res.redirect('https://' + (req.hostname || 'instant.io') + req.url)
  }

  // Redirect www to non-www
  if (config.isProd && req.hostname === 'www.instant.io') {
    return res.redirect('https://instant.io' + req.url)
  }

  // Use HTTP Strict Transport Security
  // Lasts 1 year, incl. subdomains, allow browser preload list
  if (config.isProd) {
    res.header(
      'Strict-Transport-Security',
      'max-age=31536000; includeSubDomains; preload'
    )
  }

  // Add cross-domain header for fonts, required by spec, Firefox, and IE.
  var extname = path.extname(req.url)
  if (['.eot', '.ttf', '.otf', '.woff', '.woff2'].indexOf(extname) >= 0) {
    res.header('Access-Control-Allow-Origin', '*')
  }

  // Prevents IE and Chrome from MIME-sniffing a response. Reduces exposure to
  // drive-by download attacks on sites serving user uploaded content.
  res.header('X-Content-Type-Options', 'nosniff')

  // Prevent rendering of site within a frame.
  res.header('X-Frame-Options', 'DENY')

  // Enable the XSS filter built into most recent web browsers. It's usually
  // enabled by default anyway, so role of this headers is to re-enable for this
  // particular website if it was disabled by the user.
  res.header('X-XSS-Protection', '1; mode=block')

  // Force IE to use latest rendering engine or Chrome Frame
  res.header('X-UA-Compatible', 'IE=Edge,chrome=1')

  next()
})

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

app.get('/', function (req, res) {
  res.render('index', {
    title: 'Instant.io - Streaming file transfer over WebTorrent'
  })
})

// Fetch new iceServers from twilio token regularly
var iceServers
var twilioClient
try {
  twilioClient = twilio(secret.twilio.accountSid, secret.twilio.authToken)
} catch (err) {}

function updateIceServers () {
  twilioClient.tokens.create({}, function (err, token) {
    if (err) return console.error(err.message || err)
    if (!token.iceServers) {
      return console.error('twilio response ' + util.inspect(token) + ' missing iceServers')
    }

    // Support new spec (`RTCIceServer.url` was renamed to `RTCIceServer.urls`)
    iceServers = token.iceServers.map(function (server) {
      if (server.url != null) {
        server.urls = server.url
        delete server.url
      }
      return server
    })
  })
}

if (twilioClient) {
  setInterval(updateIceServers, 60 * 60 * 4 * 1000).unref()
  updateIceServers()
}

// WARNING: This is *NOT* a public endpoint. Do not depend on it in your app.
app.get('/__rtcConfig__', cors({
  origin: function (origin, cb) {
    var allowed = CORS_WHITELIST.indexOf(origin) >= 0 ||
      /https?:\/\/localhost(:|$)/.test(origin) ||
      /https?:\/\/airtap\.local(:|$)/.test(origin)
    cb(null, allowed)
  }
}), function (req, res) {
  if (!iceServers) return res.status(404).send({ iceServers: [] })
  res.send({
    comment: 'WARNING: This is *NOT* a public endpoint. Do not depend on it in your app',
    iceServers: iceServers
  })
})

app.get('/500', (req, res, next) => {
  next(new Error('Manually visited /500'))
})

app.get('*', function (req, res) {
  res.status(404).render('error', {
    title: '404 Page Not Found - Instant.io',
    message: '404 Not Found'
  })
})

if (global.rollbar) app.use(global.rollbar.errorHandler())

// error handling middleware
app.use(function (err, req, res, next) {
  console.error(err.stack)
  const code = typeof err.code === 'number' ? err.code : 500
  res.status(code).render('error', {
    title: '500 Internal Server Error - Instant.io',
    message: err.message || err
  })
})

server.listen(PORT, function () {
  console.log('listening on port %s', server.address().port)
})
<|endoftext|>


<commit_before>import { run } from '@ember/runloop';
import { test, module } from 'qunit';
import startApp from '../helpers/start-app';

var application, redux, subscribed, unsubscribed, original;

module('Acceptance | subscribe e2e test', {
  beforeEach() {
    subscribed = 0;
    unsubscribed = 0;
    application = startApp();
    redux = application.__container__.lookup('service:redux');
    original = redux.subscribe;
    redux.subscribe = function() {
      subscribed = subscribed + 1;
      var unsubscribe = original.apply(this, arguments);
      var unsubscribe_copy = unsubscribe;
      unsubscribe = function() {
        unsubscribed = unsubscribed + 1;
        return unsubscribe_copy.apply(this, arguments);
      };
      return unsubscribe;
    };
  },
  afterEach() {
    redux.subscribe = original;
    run(application, 'destroy');
  }
});

test('should subscribe and unsubscribe when components are created/destroyed', function(assert) {
  visit('/');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 1);
    assert.equal(unsubscribed, 0);
  });
  click('.dashboard-link');
  andThen(() => {
    assert.equal(currentURL(), '/dashboard');
    assert.equal(subscribed, 2);
    assert.equal(unsubscribed, 1);
  });
  click('.counts-link');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 3);
    assert.equal(unsubscribed, 2);
  });
});

test('components without state should not subscribe or unsubscribe', function(assert) {
  visit('/empty');
  andThen(() => {
    assert.equal(currentURL(), '/empty');
    assert.equal(subscribed, 0);
    assert.equal(unsubscribed, 0);
    assert.equal(find('.empty-state').text(), 'empty');
  });
  click('.dashboard-link');
  andThen(() => {
    assert.equal(currentURL(), '/dashboard');
    assert.equal(subscribed, 1);
    assert.equal(unsubscribed, 0);
  });
  click('.counts-link');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 2);
    assert.equal(unsubscribed, 1);
  });
});
<commit_msg>TESTS: added test to confirm unsubscribe is fired from willDestroy<commit_after>import { run } from '@ember/runloop';
import { test, module } from 'qunit';
import startApp from '../helpers/start-app';

var application, redux, subscribed, unsubscribed, original;

module('Acceptance | subscribe e2e test', {
  beforeEach() {
    subscribed = 0;
    unsubscribed = 0;
    application = startApp();
    redux = application.__container__.lookup('service:redux');
    original = redux.subscribe;
    redux.subscribe = function() {
      subscribed = subscribed + 1;
      var unsubscribe = original.apply(this, arguments);
      var unsubscribe_copy = unsubscribe;
      unsubscribe = function() {
        unsubscribed = unsubscribed + 1;
        return unsubscribe_copy.apply(this, arguments);
      };
      return unsubscribe;
    };
  },
  afterEach() {
    redux.subscribe = original;
    run(application, 'destroy');
  }
});

test('should subscribe and unsubscribe when components are created/destroyed', function(assert) {
  visit('/');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 1);
    assert.equal(unsubscribed, 0);
  });
  click('.dashboard-link');
  andThen(() => {
    assert.equal(currentURL(), '/dashboard');
    assert.equal(subscribed, 2);
    assert.equal(unsubscribed, 1);
  });
  click('.counts-link');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 3);
    assert.equal(unsubscribed, 2);
  });
});

test('es2015 class based components subscribe and unsubscribe when components are created/destroyed', function(assert) {
  visit('/clazz');
  andThen(() => {
    assert.equal(currentURL(), '/clazz');
    assert.equal(subscribed, 1);
    assert.equal(unsubscribed, 0);
  });
  click('.dashboard-link');
  andThen(() => {
    assert.equal(currentURL(), '/dashboard');
    assert.equal(subscribed, 2);
    assert.equal(unsubscribed, 1);
  });
  click('.clazz-link');
  andThen(() => {
    assert.equal(currentURL(), '/clazz');
    assert.equal(subscribed, 3);
    assert.equal(unsubscribed, 2);
  });
});

test('components without state should not subscribe or unsubscribe', function(assert) {
  visit('/empty');
  andThen(() => {
    assert.equal(currentURL(), '/empty');
    assert.equal(subscribed, 0);
    assert.equal(unsubscribed, 0);
    assert.equal(find('.empty-state').text(), 'empty');
  });
  click('.dashboard-link');
  andThen(() => {
    assert.equal(currentURL(), '/dashboard');
    assert.equal(subscribed, 1);
    assert.equal(unsubscribed, 0);
  });
  click('.counts-link');
  andThen(() => {
    assert.equal(currentURL(), '/');
    assert.equal(subscribed, 2);
    assert.equal(unsubscribed, 1);
  });
});
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* eslint-disable prefer-reflect */

'use strict';

const program = require('commander');
const fs = require('fs');
const glob = require('glob');

const SVGIcons2SVGFontStream = require('../src/index.js');
const SVGIconsDirStream = require('../src/iconsdir.js');

program
  .version(require('../package').version)
  .usage('[options] <icons ...>')
  .option('-v, --verbose', 'tell me everything!')
  .option('-o, --output [/dev/stdout]', 'file to write output to')
  .option('-f, --fontname [value]', 'the font family name you want [iconfont]')
  .option('-i, --fontId [value]', 'the font id you want [fontname]')
  .option('-st, --style [value]', 'the font style you want')
  .option('-we, --weight [value]', 'the font weight you want')
  .option(
    '-w, --fixedWidth',
    'creates a monospace font of the width of the largest input icon'
  )
  .option(
    '-c, --centerhorizontally',
    'calculate the bounds of a glyph and center it horizontally'
  )
  .option(
    '-y, --centerVertically',
    'centers the glyphs vertically in the generated font.'
  )
  .option(
    '-n, --normalize',
    'normalize icons by scaling them to the height of the highest icon'
  )
  .option(
    '-h, --height [value]',
    'the output font height [MAX(icons.height)] (icons will be scaled so the highest has this height)',
    parseInt
  )
  .option(
    '-r, --round [value]',
    'setup the SVG path rounding [10e12]',
    parseFloat
  )
  .option('-d, --descent [value]', 'the font descent [0]', parseInt)
  .option(
    '-a, --ascent [value]',
    'the font ascent [height - descent]',
    parseInt
  )
  .option(
    '-s, --startunicode [value]',
    'the start unicode codepoint for' + ' unprefixed files [0xEA01]',
    parseInt
  )
  .option(
    '-a, --prependUnicode',
    'prefix files with their automatically' + ' allocated unicode code point',
    parseInt
  )
  .option('-m, --metadata', 'content of the metadata tag')
  .parse(process.argv);

if (!program.args.length) {
  console.error('No icons specified!'); // eslint-disable-line
  process.exit(1);
}

const files = program.args.flatMap((file) => glob.sync(file));

new SVGIconsDirStream(files, {
  startUnicode: program.startunicode,
  prependUnicode: program.prependUnicode,
  log: program.v ? console.log : function () {}, // eslint-disable-line
})
  .pipe(
    new SVGIcons2SVGFontStream({
      fontName: program.fontname,
      fontId: program.fontId,
      fixedWidth: program.fixedwidth,
      centerHorizontally: program.centerHorizontally,
      centerVertically: program.centerVertically,
      normalize: program.normalize,
      fontHeight: program.height,
      round: program.round,
      descent: program.descent,
      ascent: program.ascent,
      metadata: program.metadata,
      log: program.v ? console.log : function () {}, // eslint-disable-line
    })
  )
  .pipe(program.output ? fs.createWriteStream(program.output) : process.stdout);
<commit_msg>Fix bug with commander<commit_after>#! /usr/bin/env node
/* eslint-disable prefer-reflect */

'use strict';

const program = require('commander');
const fs = require('fs');
const glob = require('glob');

const SVGIcons2SVGFontStream = require('../src/index.js');
const SVGIconsDirStream = require('../src/iconsdir.js');

program
  .storeOptionsAsProperties(true)
  .version(require('../package').version)
  .usage('[options] <icons ...>')
  .option('-v, --verbose', 'tell me everything!')
  .option('-o, --output [/dev/stdout]', 'file to write output to')
  .option('-f, --fontname [value]', 'the font family name you want [iconfont]')
  .option('-i, --fontId [value]', 'the font id you want [fontname]')
  .option('-st, --style [value]', 'the font style you want')
  .option('-we, --weight [value]', 'the font weight you want')
  .option(
    '-w, --fixedWidth',
    'creates a monospace font of the width of the largest input icon'
  )
  .option(
    '-c, --centerhorizontally',
    'calculate the bounds of a glyph and center it horizontally'
  )
  .option(
    '-y, --centerVertically',
    'centers the glyphs vertically in the generated font.'
  )
  .option(
    '-n, --normalize',
    'normalize icons by scaling them to the height of the highest icon'
  )
  .option(
    '-h, --height [value]',
    'the output font height [MAX(icons.height)] (icons will be scaled so the highest has this height)',
    parseInt
  )
  .option(
    '-r, --round [value]',
    'setup the SVG path rounding [10e12]',
    parseFloat
  )
  .option('-d, --descent [value]', 'the font descent [0]', parseInt)
  .option(
    '-a, --ascent [value]',
    'the font ascent [height - descent]',
    parseInt
  )
  .option(
    '-s, --startunicode [value]',
    'the start unicode codepoint for' + ' unprefixed files [0xEA01]',
    parseInt
  )
  .option(
    '-a, --prependUnicode',
    'prefix files with their automatically' + ' allocated unicode code point',
    parseInt
  )
  .option('-m, --metadata', 'content of the metadata tag')
  .parse(process.argv);

if (!program.args.length) {
  console.error('No icons specified!'); // eslint-disable-line
  process.exit(1);
}

const files = program.args.flatMap((file) => glob.sync(file));

new SVGIconsDirStream(files, {
  startUnicode: program.startunicode,
  prependUnicode: program.prependUnicode,
  log: program.v ? console.log : function () {}, // eslint-disable-line
})
  .pipe(
    new SVGIcons2SVGFontStream({
      fontName: program.fontname,
      fontId: program.fontId,
      fixedWidth: program.fixedwidth,
      centerHorizontally: program.centerHorizontally,
      centerVertically: program.centerVertically,
      normalize: program.normalize,
      fontHeight: program.height,
      round: program.round,
      descent: program.descent,
      ascent: program.ascent,
      metadata: program.metadata,
      log: program.v ? console.log : function () {}, // eslint-disable-line
    })
  )
  .pipe(program.output ? fs.createWriteStream(program.output) : process.stdout);
<|endoftext|>