<commit_before>const router = require('express').Router();
const path = require('path');
const rp = require('request-promise');
const verifyUserAjax = require('../middleware/verify-user.js')({ajax: true});
const verifyBot = require('../middleware/verify-bot.js');
const StickerPack = require('./models/sticker-pack-model.js');
const Guild = require('./models/guild-model.js');
const User = require('./models/user-model.js');
const util = require('./utilities/utilities.js');
const imageToCdn = require('./utilities/image-to-cdn.js');
const deleteCdnImage = require('./utilities/delete-cdn-image.js');
const emojis = require('./utilities/emojis.json');
const multer = require('multer');
const covert = require('../../covert.js');

let storage = multer.memoryStorage();
let upload = multer({
	storage: storage,
	limits: {fileSize: 5 * 1024 * 1024} //5MB max image upload
});
let handleMulterError = function(err, req, res, next){
	if(err)	res.status(400).send(err.message)
	else next();
}

const removedFields = {
	'_id': false,
	'__v': false,
	'stickers._id': false
}

///////
//GET//
///////

router.get('/', async (req, res) =>{

	const packsPerPage = 18;

	//Page #
	let requestedPage = parseInt(req.query.page);
	let skipAmount = 0;

	if(!isNaN(requestedPage) && requestedPage !== 0){
		skipAmount = (parseInt(req.query.page) - 1) * packsPerPage;
	}

	//Sort Type
	let sortType;

	if(req.query.sort === 'popular') sortType = '-subscribers';
	else if(req.query.sort === 'oldest') sortType = 'createdAt';
	else sortType = '-createdAt';

	//Search
	let search = {published: true};

	if(req.query.search){
		let s = decodeURIComponent(req.query.search).trim();
		let regex = new RegExp(s, 'i');
		search.$or = [{name: regex}, {key: regex}, {description: regex}];
	}

	try{

		const totalPackCount = await StickerPack.count(search);
		const packs = await StickerPack.find(search, removedFields).sort(sortType).skip(skipAmount).limit(packsPerPage);
		let packInfo = packs.map(p => p._doc);
		packInfo.forEach(p => delete p.stickers);
		return res.send({packs: packInfo});

	}catch(err){
		console.log(err.message);
		return res.status(500).send('Internal server error');
	}

});

//GET Sticker pack by key
router.get('/:key', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		res.json(pack);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET Sticker Pack info (all data except stickers themselves)
router.get('/:key/info', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		delete pack._doc.stickers;
		res.json(pack._doc);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET Sticker Pack stickers
router.get('/:key/stickers', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		res.json(pack.stickers);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET a specific sticker from a Sticker Pack
router.get('/:key/stickers/:stickername', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		const sticker = pack.stickers.find(s => s.name === req.params.stickername);
		if(!sticker) return res.status(404).send('Sticker Pack does not contain a sticker with that name');
		res.json(sticker);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

////////
//POST//
////////

//POST new sticker pack
router.post('/', verifyUserAjax, upload.single('icon'), handleMulterError, async (req, res) => {

	if(!req.body.name || !req.body.key || !req.body.description || !req.file){
		return res.status(400).send('Invalid body data');
	}

	let {name, key, description} = req.body;
	name = name.trim().replace(/\s+/g, ' ');
	key = key.trim().replace(/\s+/g, ' ');
	description = description.trim().replace(/\s+/g, ' ');

	if(name.length === 0 || key.length === 0 || description.length === 0) return res.status(400).send('Invalid body data');
	if(!key.match(/^[a-z0-9]+$/g)) return res.status(400).send('Sticker Pack key must contain lowercase letters and numbers only');
	if(name.length > 60) return res.status(400).send('Sticker Pack name cannot be longer than 60 characters');
	if(key.length > 8) return res.status(400).send('Sticker Pack key cannot be longer than 8 characters');
	if(description.length > 110) return res.status(400).send('Sticker Pack key cannot be longer than 110 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	//Check if Sticker Pack key is already used
	const keyAlreadyUsed = await StickerPack.findOne({key});
	if(keyAlreadyUsed) return res.status(400).send('There is already a Sticker Pack with that key');

	//Ensure user has voted on DBL within the last 24hrs before continuing (only works if DBL integrated)
	if(covert.discord_bot_list.integrated){
		let dbl_vote_check = await rp({
			uri: `https://discordbots.org/api/bots/${covert.discord.app_id}/check?userId=${res.locals.userId}`,
			headers: {Authorization: covert.discord_bot_list.api_key},
			json: true
		});

		if(dbl_vote_check.voted === 0) return res.status(401).send('User has not voted on DBL today');
	}

	//Create Sticker Pack
	let data = Object.assign({}, {name, key, description});
	data.creatorId = res.locals.userId;
	data.icon = await imageToCdn(req.file.buffer, `${data.key}-ICON-${(new Date()).getTime()}`);

	try{
		await new StickerPack(data).save();
		const pack = await StickerPack.findOne({key}, removedFields);
		res.status(201).json(pack);
	}catch(err){
		console.error(err);
		res.status(500).send('Internal server error');
	}

});

//Publish a Sticker Pack
router.post('/:key/publish', verifyUserAjax, async (req, res) => {

	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	try{
		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');
		if(pack.stickers.length < 4) return res.status(400).send('At least 4 stickers must be in this pack before publishing');
		pack.published = true;
		await pack.save();

		return res.json(util.removeProps(pack._doc, Object.keys(removedFields)));
	}catch(err){
		console.error(err);
		res.status(500).send('Internal server error');
	}

});

//POST new sticker to sticker pack
router.post('/:key/stickers', verifyUserAjax, upload.single('sticker'), handleMulterError, async (req, res) => {

	if(!req.body.name || (!req.body.url && !req.file)) return res.status(400).send('Invalid body data');
	if(!req.body.name.match(/^:?-?[a-z0-9]+:?$/g)) return res.status(400).send('Sticker name must contain lowercase letters and numbers only');
	if(req.body.name.length > 20) return res.status(400).send('Sticker name cannot be longer than 20 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	let sticker = {
		image: (req.file) ? req.file.buffer : req.body.url,
		name: req.body.name.toLowerCase().replace(/(:|-)/g, ''),
		createdVia: (req.file) ? 'website' : 'discord',
		groupId: req.params.key,
		creatorId: res.locals.userId
	}

	let imageIsLocal = (req.file) ? true : false;

	try{

		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');
		if(pack.stickers.map(s => s.name).includes(sticker.name)) return res.status(400).send('Sticker Pack already has a sticker with that name');
		if(pack.stickers.length >= 400) return res.status(403).send('Sticker Pack has reached maximum amount of stickers (400)');

		sticker.url = await imageToCdn(sticker.image, `${pack.key}-${(new Date()).getTime()}-${sticker.name}`);

		pack.stickers.unshift(sticker);
		pack = await pack.save();

		sticker = pack.stickers.find(s => s.name === sticker.name);
		return res.status(201).json(util.removeProps(sticker._doc, ['_id']));

	}catch(err){

		if(err.message.includes('Unauthorized')) return res.status(401).send('Unauthorized');
		console.error(err);
		res.status(500).send('Internal server error');

	}

});

//Increment `uses` property on a sticker
router.post('/:key/stickers/:stickername/uses', verifyBot, async (req, res) => {

	let pack = await StickerPack.findOne({key: req.params.key});
	if(!pack) return res.status(404).send('Sticker Pack not found');
	let sticker = pack._doc.stickers.find(s => s.name === req.params.stickername);
	if(!sticker) return res.status(404).send('Sticker Pack does not have a sticker with that name');

	sticker.uses += 1;
	pack.save();

	return res.json(util.removeProps(sticker._doc, ['_id']));

});

/////////
//PATCH//
/////////

//Update Sticker Pack
router.patch('/:key', verifyUserAjax, async (req, res) => {

	if(!req.body.name || !req.body.description) return res.status(400).send('Invalid body data');

	let {name, description} = req.body;
	name = name.trim().replace(/\s+/g, ' ');
	description = description.trim().replace(/\s+/g, ' ');

	if(name.length === 0 || !description.length === 0) return res.status(400).send('Invalid body data');
	if(name.length > 60) return res.status(400).send('Sticker Pack name cannot be longer than 60 characters');
	if(description.length > 110) return res.status(400).send('Sticker Pack key cannot be longer than 110 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	try{
		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');

		Object.assign(pack, {name, description});

		await pack.save();
		delete pack._doc.stickers;
		return res.json(pack._doc);

	}catch(err){
		console.error(err);
		return res.status(500).send('Internal server error');
	}

});

//////////
//DELETE//
//////////

//DELETE sticker from sticker pack
router.delete('/:key/stickers/:stickername', verifyUserAjax, async (req, res) => {

	try{

		let pack = await StickerPack.findOne({key: req.params.key});

		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');

		let sticker_names = pack.stickers.map(s => s.name);
		let deletion_request_index = sticker_names.indexOf(req.params.stickername);
		if(deletion_request_index === -1) return res.status(404).send('Sticker Pack does not have a sticker with that name');

		deleteCdnImage(pack.stickers[deletion_request_index].url);
		pack.stickers.splice(deletion_request_index, 1);
		await pack.save();

		return res.send('Successfully deleted sticker');

	}catch(err){

		if(err.message.includes('Unauthorized')) return res.status(401).send('Unauthorized');
		console.error(err);
		res.status(500).send('Internal server error');

	}

});

module.exports = router;
<commit_msg>Correct typo in sticker pack api responses<commit_after>const router = require('express').Router();
const path = require('path');
const rp = require('request-promise');
const verifyUserAjax = require('../middleware/verify-user.js')({ajax: true});
const verifyBot = require('../middleware/verify-bot.js');
const StickerPack = require('./models/sticker-pack-model.js');
const Guild = require('./models/guild-model.js');
const User = require('./models/user-model.js');
const util = require('./utilities/utilities.js');
const imageToCdn = require('./utilities/image-to-cdn.js');
const deleteCdnImage = require('./utilities/delete-cdn-image.js');
const emojis = require('./utilities/emojis.json');
const multer = require('multer');
const covert = require('../../covert.js');

let storage = multer.memoryStorage();
let upload = multer({
	storage: storage,
	limits: {fileSize: 5 * 1024 * 1024} //5MB max image upload
});
let handleMulterError = function(err, req, res, next){
	if(err)	res.status(400).send(err.message)
	else next();
}

const removedFields = {
	'_id': false,
	'__v': false,
	'stickers._id': false
}

///////
//GET//
///////

router.get('/', async (req, res) =>{

	const packsPerPage = 18;

	//Page #
	let requestedPage = parseInt(req.query.page);
	let skipAmount = 0;

	if(!isNaN(requestedPage) && requestedPage !== 0){
		skipAmount = (parseInt(req.query.page) - 1) * packsPerPage;
	}

	//Sort Type
	let sortType;

	if(req.query.sort === 'popular') sortType = '-subscribers';
	else if(req.query.sort === 'oldest') sortType = 'createdAt';
	else sortType = '-createdAt';

	//Search
	let search = {published: true};

	if(req.query.search){
		let s = decodeURIComponent(req.query.search).trim();
		let regex = new RegExp(s, 'i');
		search.$or = [{name: regex}, {key: regex}, {description: regex}];
	}

	try{

		const totalPackCount = await StickerPack.count(search);
		const packs = await StickerPack.find(search, removedFields).sort(sortType).skip(skipAmount).limit(packsPerPage);
		let packInfo = packs.map(p => p._doc);
		packInfo.forEach(p => delete p.stickers);
		return res.send({packs: packInfo});

	}catch(err){
		console.log(err.message);
		return res.status(500).send('Internal server error');
	}

});

//GET Sticker pack by key
router.get('/:key', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		res.json(pack);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET Sticker Pack info (all data except stickers themselves)
router.get('/:key/info', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		delete pack._doc.stickers;
		res.json(pack._doc);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET Sticker Pack stickers
router.get('/:key/stickers', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		res.json(pack.stickers);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

//GET a specific sticker from a Sticker Pack
router.get('/:key/stickers/:stickername', async (req, res) => {

	try{
		const pack = await StickerPack.findOne({key: req.params.key}, removedFields);
		if(!pack) return res.status(404).send('Sticker Pack not found');
		const sticker = pack.stickers.find(s => s.name === req.params.stickername);
		if(!sticker) return res.status(404).send('Sticker Pack does not contain a sticker with that name');
		res.json(sticker);
	}catch(err){
		res.status(500).send('Internal server error');
	}

});

////////
//POST//
////////

//POST new sticker pack
router.post('/', verifyUserAjax, upload.single('icon'), handleMulterError, async (req, res) => {

	if(!req.body.name || !req.body.key || !req.body.description || !req.file){
		return res.status(400).send('Invalid body data');
	}

	let {name, key, description} = req.body;
	name = name.trim().replace(/\s+/g, ' ');
	key = key.trim().replace(/\s+/g, ' ');
	description = description.trim().replace(/\s+/g, ' ');

	if(name.length === 0 || key.length === 0 || description.length === 0) return res.status(400).send('Invalid body data');
	if(!key.match(/^[a-z0-9]+$/g)) return res.status(400).send('Sticker Pack key must contain lowercase letters and numbers only');
	if(name.length > 60) return res.status(400).send('Sticker Pack name cannot be longer than 60 characters');
	if(key.length > 8) return res.status(400).send('Sticker Pack key cannot be longer than 8 characters');
	if(description.length > 110) return res.status(400).send('Sticker Pack description cannot be longer than 110 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	//Check if Sticker Pack key is already used
	const keyAlreadyUsed = await StickerPack.findOne({key});
	if(keyAlreadyUsed) return res.status(400).send('There is already a Sticker Pack with that key');

	//Ensure user has voted on DBL within the last 24hrs before continuing (only works if DBL integrated)
	if(covert.discord_bot_list.integrated){
		let dbl_vote_check = await rp({
			uri: `https://discordbots.org/api/bots/${covert.discord.app_id}/check?userId=${res.locals.userId}`,
			headers: {Authorization: covert.discord_bot_list.api_key},
			json: true
		});

		if(dbl_vote_check.voted === 0) return res.status(401).send('User has not voted on DBL today');
	}

	//Create Sticker Pack
	let data = Object.assign({}, {name, key, description});
	data.creatorId = res.locals.userId;
	data.icon = await imageToCdn(req.file.buffer, `${data.key}-ICON-${(new Date()).getTime()}`);

	try{
		await new StickerPack(data).save();
		const pack = await StickerPack.findOne({key}, removedFields);
		res.status(201).json(pack);
	}catch(err){
		console.error(err);
		res.status(500).send('Internal server error');
	}

});

//Publish a Sticker Pack
router.post('/:key/publish', verifyUserAjax, async (req, res) => {

	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	try{
		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');
		if(pack.stickers.length < 4) return res.status(400).send('At least 4 stickers must be in this pack before publishing');
		pack.published = true;
		await pack.save();

		return res.json(util.removeProps(pack._doc, Object.keys(removedFields)));
	}catch(err){
		console.error(err);
		res.status(500).send('Internal server error');
	}

});

//POST new sticker to sticker pack
router.post('/:key/stickers', verifyUserAjax, upload.single('sticker'), handleMulterError, async (req, res) => {

	if(!req.body.name || (!req.body.url && !req.file)) return res.status(400).send('Invalid body data');
	if(!req.body.name.match(/^:?-?[a-z0-9]+:?$/g)) return res.status(400).send('Sticker name must contain lowercase letters and numbers only');
	if(req.body.name.length > 20) return res.status(400).send('Sticker name cannot be longer than 20 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	let sticker = {
		image: (req.file) ? req.file.buffer : req.body.url,
		name: req.body.name.toLowerCase().replace(/(:|-)/g, ''),
		createdVia: (req.file) ? 'website' : 'discord',
		groupId: req.params.key,
		creatorId: res.locals.userId
	}

	let imageIsLocal = (req.file) ? true : false;

	try{

		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');
		if(pack.stickers.map(s => s.name).includes(sticker.name)) return res.status(400).send('Sticker Pack already has a sticker with that name');
		if(pack.stickers.length >= 400) return res.status(403).send('Sticker Pack has reached maximum amount of stickers (400)');

		sticker.url = await imageToCdn(sticker.image, `${pack.key}-${(new Date()).getTime()}-${sticker.name}`);

		pack.stickers.unshift(sticker);
		pack = await pack.save();

		sticker = pack.stickers.find(s => s.name === sticker.name);
		return res.status(201).json(util.removeProps(sticker._doc, ['_id']));

	}catch(err){

		if(err.message.includes('Unauthorized')) return res.status(401).send('Unauthorized');
		console.error(err);
		res.status(500).send('Internal server error');

	}

});

//Increment `uses` property on a sticker
router.post('/:key/stickers/:stickername/uses', verifyBot, async (req, res) => {

	let pack = await StickerPack.findOne({key: req.params.key});
	if(!pack) return res.status(404).send('Sticker Pack not found');
	let sticker = pack._doc.stickers.find(s => s.name === req.params.stickername);
	if(!sticker) return res.status(404).send('Sticker Pack does not have a sticker with that name');

	sticker.uses += 1;
	pack.save();

	return res.json(util.removeProps(sticker._doc, ['_id']));

});

/////////
//PATCH//
/////////

//Update Sticker Pack
router.patch('/:key', verifyUserAjax, async (req, res) => {

	if(!req.body.name || !req.body.description) return res.status(400).send('Invalid body data');

	let {name, description} = req.body;
	name = name.trim().replace(/\s+/g, ' ');
	description = description.trim().replace(/\s+/g, ' ');

	if(name.length === 0 || !description.length === 0) return res.status(400).send('Invalid body data');
	if(name.length > 60) return res.status(400).send('Sticker Pack name cannot be longer than 60 characters');
	if(description.length > 110) return res.status(400).send('Sticker Pack description cannot be longer than 110 characters');
	if(!res.locals.userId) return res.status(401).send('Unauthorized');

	try{
		let pack = await StickerPack.findOne({key: req.params.key});
		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');

		Object.assign(pack, {name, description});

		await pack.save();
		delete pack._doc.stickers;
		return res.json(pack._doc);

	}catch(err){
		console.error(err);
		return res.status(500).send('Internal server error');
	}

});

//////////
//DELETE//
//////////

//DELETE sticker from sticker pack
router.delete('/:key/stickers/:stickername', verifyUserAjax, async (req, res) => {

	try{

		let pack = await StickerPack.findOne({key: req.params.key});

		if(!pack) return res.status(404).send('Sticker Pack not found');
		if(res.locals.userId != pack.creatorId) return res.status(401).send('Unauthorized');

		let sticker_names = pack.stickers.map(s => s.name);
		let deletion_request_index = sticker_names.indexOf(req.params.stickername);
		if(deletion_request_index === -1) return res.status(404).send('Sticker Pack does not have a sticker with that name');

		deleteCdnImage(pack.stickers[deletion_request_index].url);
		pack.stickers.splice(deletion_request_index, 1);
		await pack.save();

		return res.send('Successfully deleted sticker');

	}catch(err){

		if(err.message.includes('Unauthorized')) return res.status(401).send('Unauthorized');
		console.error(err);
		res.status(500).send('Internal server error');

	}

});

module.exports = router;
<|endoftext|>


<commit_before>var Gmail =  function() {

  var api = {
              get : {},
              observe : {},
              check : {},
              detect : {},
              dom : {}
            };

  api.get.user_email = function() {
    return GLOBALS[10];
  };

  api.check.is_thread = function() {
    var check_1 = $($($('.nH .if').children()[1]).children().children()[1]).children();
    var check_2 = $($($($('.nH .if').children()[1]).children()).children()[1]).children();
    var check_3 = api.get.email_ids();

    return (check_1.length > 1 || check_2.length > 1) || check_3.length > 1;
  };

  api.dom.inbox_content = function() {
    return $('div[role=main]:first');
  }

  api.check.is_preview_pane = function() {
    var dom = api.dom.inbox_content();
    var box = dom.find("[gh=tl]");

    if(box.length > 0) {
      return box[0].getAttribute('class').indexOf('aia') != -1;
    }

    return false;
  }

  api.check.is_horizontal_split = function() {
    var dom = api.dom.inbox_content();
    var box = dom.find("[gh=tl]").find('.nn');

    return box.length == 0;
  }

  api.check.is_vertical_split = function() {
    return api.check.is_horizontal_split() == false;
  }

  api.check.is_tabbed_inbox = function() {
    return $(".aKh").length == 1;
  }

  api.check.is_right_side_chat = function() {
    return $('.ApVoH')[0].getAttribute('aria-labelledby') == ':wf';
  }

  api.check.is_google_apps_user =function() {
    var email = api.get.user_email();
    return email.indexOf('gmail.com', email.length - 'gmail.com'.length) == -1;
  }

  api.get.storage_info = function() {
    var div = $('.md.mj').find('div')[0];
    var used = $(div).find('span')[0].innerText;
    var total = $(div).find('span')[1].innerText;
    var percent = parseFloat(used.replace(/[^0-9\.]/g, '')) * 100 / parseFloat(total.replace(/[^0-9\.]/g, ''));

    return {used : used, total : total, percent : Math.floor(percent)}
  }

  api.dom.email_subject = function () {
    return $('h1.ha');
  }

  api.get.email_subject = function() {
    var subject_dom = api.dom.email_subject();

    return subject_dom.find('.hP')[0].innerText;
  }

  api.dom.email_body = function() {
    return $('.nH.hx');
  }

  api.check.inside_email = function() {
    return api.dom.email_contents().length > 0;
  }

  api.dom.email_contents = function() {
    return $('.ii.gt');
  }

  api.get.email_ids = function () {
    var items = api.dom.email_contents();
    var ids = [];

    for(var i=0; i<items.length; i++) {
      var mail_id = items[i].getAttribute('class').split(' ')[2];
      var is_editable = items[i].getAttribute('contenteditable');
      if(mail_id != 'undefined' && mail_id != undefined) {
        if(is_editable != 'true') {
          ids.push(mail_id);
        }
      }
    }

    return ids;
  }

  api.get.email_id = function() {
    var hash = null;

    if(api.check.inside_email()) {
      if(api.check.is_preview_pane()) {
        var text = api.get.email_ids();
        hash = text[0].substring(1, text[0].length);
      } else {
        hash = window.location.hash.split("/").pop().replace(/#/, '').split('?')[0];
      }

    }

    return hash;
  }

  return api;
}<commit_msg>Added api.check.is_priority_inbox()<commit_after>var Gmail =  function() {

  var api = {
              get : {},
              observe : {},
              check : {},
              detect : {},
              dom : {}
            };

  api.get.user_email = function() {
    return GLOBALS[10];
  };

  api.check.is_thread = function() {
    var check_1 = $($($('.nH .if').children()[1]).children().children()[1]).children();
    var check_2 = $($($($('.nH .if').children()[1]).children()).children()[1]).children();
    var check_3 = api.get.email_ids();

    return (check_1.length > 1 || check_2.length > 1) || check_3.length > 1;
  };

  api.dom.inbox_content = function() {
    return $('div[role=main]:first');
  }

  api.check.is_preview_pane = function() {
    var dom = api.dom.inbox_content();
    var box = dom.find("[gh=tl]");

    if(box.length > 0) {
      return box[0].getAttribute('class').indexOf('aia') != -1;
    }

    return false;
  }

  api.check.is_horizontal_split = function() {
    var dom = api.dom.inbox_content();
    var box = dom.find("[gh=tl]").find('.nn');

    return box.length == 0;
  }

  api.check.is_vertical_split = function() {
    return api.check.is_horizontal_split() == false;
  }

  api.check.is_tabbed_inbox = function() {
    return $(".aKh").length == 1;
  }

  api.check.is_right_side_chat = function() {
    return $('.ApVoH')[0].getAttribute('aria-labelledby') == ':wf';
  }

  api.check.is_google_apps_user =function() {
    var email = api.get.user_email();
    return email.indexOf('gmail.com', email.length - 'gmail.com'.length) == -1;
  }

  api.get.storage_info = function() {
    var div = $('.md.mj').find('div')[0];
    var used = $(div).find('span')[0].innerText;
    var total = $(div).find('span')[1].innerText;
    var percent = parseFloat(used.replace(/[^0-9\.]/g, '')) * 100 / parseFloat(total.replace(/[^0-9\.]/g, ''));

    return {used : used, total : total, percent : Math.floor(percent)}
  }

  api.dom.email_subject = function () {
    return $('h1.ha');
  }

  api.get.email_subject = function() {
    var subject_dom = api.dom.email_subject();

    return subject_dom.find('.hP')[0].innerText;
  }

  api.dom.email_body = function() {
    return $('.nH.hx');
  }

  api.check.inside_email = function() {
    return api.dom.email_contents().length > 0;
  }

  api.dom.email_contents = function() {
    return $('.ii.gt');
  }

  api.get.email_ids = function () {
    var items = api.dom.email_contents();
    var ids = [];

    for(var i=0; i<items.length; i++) {
      var mail_id = items[i].getAttribute('class').split(' ')[2];
      var is_editable = items[i].getAttribute('contenteditable');
      if(mail_id != 'undefined' && mail_id != undefined) {
        if(is_editable != 'true') {
          ids.push(mail_id);
        }
      }
    }

    return ids;
  }

  api.get.email_id = function() {
    var hash = null;

    if(api.check.inside_email()) {
      if(api.check.is_preview_pane()) {
        var text = api.get.email_ids();
        hash = text[0].substring(1, text[0].length);
      } else {
        hash = window.location.hash.split("/").pop().replace(/#/, '').split('?')[0];
      }

    }

    return hash;
  }

  api.check.is_priority_inbox = function() {
    return $('.qh').length > 0;
  }

  return api;
}<|endoftext|>


<commit_before>import {
  APP_NAME,
  APP_URL,
  APP_DESCRIPTION,
  APP_COLOR_PRIMARY
} from './constants/app'

export default {
  ssr: true,
  components: [
    { path: '~/components', pathPrefix: false }
  ],
  head: {
    titleTemplate: `%s - ${APP_NAME}`,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: APP_DESCRIPTION },

      { hid: 'og:site_name', property: 'og:site_name', content: APP_NAME },
      { hid: 'og:type', property: 'og:type', content: 'website' },
      { hid: 'og:url', property: 'og:url', content: APP_URL }
    ],
    link: [
      { rel: 'preconnect', href: 'https://fonts.gstatic.com' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap' },
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  loading: {
    color: `#${APP_COLOR_PRIMARY}`,
    height: '3px'
  },
  css: [
    '~/assets/css/app.scss'
  ],
  plugins: [
    '~/plugins/fontawesome',
    '~/plugins/init.client.js'
  ],
  buildModules: [
    '@nuxtjs/eslint-module',
    '@nuxtjs/google-analytics',
    '@nuxtjs/router',
    '@nuxtjs/stylelint-module',
    'nuxt-purgecss'
  ],
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa'
  ],
  build: {
    // analyze: true,
    terser: {
      extractComments: {
        filename: 'licenses.txt'
      }
    }
  },
  // top level options for packages
  googleAnalytics: {
    id: process.env.GOOGLE_ANALYTICS_TRACKING_ID,
    disabled: true,
    set: [
      { field: 'anonymizeIp', value: true }
    ]
  },
  manifest: {
    name: APP_NAME,
    short_name: APP_NAME,
    description: APP_DESCRIPTION,
    lang: 'en',
    background_color: '#222',
    display: 'standalone',
    start_url: '/'
  },
  purgeCSS: {
    paths: [
      './node_modules/@fortawesome/fontawesome-svg-core/index.js',
      './node_modules/bootstrap/js/dist/collapse.js',
      './node_modules/bootstrap/js/dist/dropdown.js',
      './node_modules/lazysizes/lazysizes.js'
    ],
    extractors: () => []
  }
}
<commit_msg>Fix loading bar settings<commit_after>import {
  APP_NAME,
  APP_URL,
  APP_DESCRIPTION,
  APP_COLOR_PRIMARY
} from './constants/app'

export default {
  ssr: true,
  components: [
    { path: '~/components', pathPrefix: false }
  ],
  head: {
    titleTemplate: `%s - ${APP_NAME}`,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: APP_DESCRIPTION },

      { hid: 'og:site_name', property: 'og:site_name', content: APP_NAME },
      { hid: 'og:type', property: 'og:type', content: 'website' },
      { hid: 'og:url', property: 'og:url', content: APP_URL }
    ],
    link: [
      { rel: 'preconnect', href: 'https://fonts.gstatic.com' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap' },
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  loading: {
    color: `#${APP_COLOR_PRIMARY}`,
    throttle: 0
  },
  css: [
    '~/assets/css/app.scss'
  ],
  plugins: [
    '~/plugins/fontawesome',
    '~/plugins/init.client.js'
  ],
  buildModules: [
    '@nuxtjs/eslint-module',
    '@nuxtjs/google-analytics',
    '@nuxtjs/router',
    '@nuxtjs/stylelint-module',
    'nuxt-purgecss'
  ],
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa'
  ],
  build: {
    // analyze: true,
    terser: {
      extractComments: {
        filename: 'licenses.txt'
      }
    }
  },
  // top level options for packages
  googleAnalytics: {
    id: process.env.GOOGLE_ANALYTICS_TRACKING_ID,
    disabled: true,
    set: [
      { field: 'anonymizeIp', value: true }
    ]
  },
  manifest: {
    name: APP_NAME,
    short_name: APP_NAME,
    description: APP_DESCRIPTION,
    lang: 'en',
    background_color: '#222',
    display: 'standalone',
    start_url: '/'
  },
  purgeCSS: {
    paths: [
      './node_modules/@fortawesome/fontawesome-svg-core/index.js',
      './node_modules/bootstrap/js/dist/collapse.js',
      './node_modules/bootstrap/js/dist/dropdown.js',
      './node_modules/lazysizes/lazysizes.js'
    ],
    extractors: () => []
  }
}
<|endoftext|>


<commit_before>var http = require("http");
var fs = require("fs");

var PLEX_SERVER_PORT = 32400;

var requestCountOnUri;

var server = http.createServer(function(req, res) {
	var sampleFilename = "root";

	recordRequestedUri(req.url);

	if (req.url === "/library/sections/1/refresh") {
		res.writeHead(200);
		return res.end();
	} else if (req.url === "/library/sections") {
		sampleFilename = "library_sections";
	}  else if (req.url === "/clients") {
		sampleFilename = "clients";
	}

	deliverXml(sampleFilename, res);
});

function deliverXml(filename, response) {
	fs.readFile("test/samples/"+ filename +".xml", function(err, content) {
		response.write(content);
		response.end();
	});
}

function recordRequestedUri(uri) {
	requestCountOnUri[uri] = (requestCountOnUri[uri] || 0) + 1;
}

module.exports = {
	start: function (port) {
		requestCountOnUri = [];
		server.listen(port || PLEX_SERVER_PORT);
	},

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

	uri: function(uri) {
		return {
			requested: requestCountOnUri[uri] !== undefined
		};
	},

	requests: function() {
		return requestCountOnUri;
	}
};<commit_msg>Minor server refactoring for easier navigation testing<commit_after>var http = require("http");
var fs = require("fs");

var PLEX_SERVER_PORT = 32400;

var requestCountOnUri;

var server = http.createServer(function(req, res) {
	var sampleFilename = "root";

	recordRequestedUri(req.url);

 	if (req.url === "/library/sections") {
		sampleFilename = "library_sections";
	}  else if (req.url === "/clients") {
		sampleFilename = "clients";
	} else {
		res.writeHead(200);
		return res.end();
	}

	deliverXml(sampleFilename, res);
});

function deliverXml(filename, response) {
	fs.readFile("test/samples/"+ filename +".xml", function(err, content) {
		response.write(content);
		response.end();
	});
}

function recordRequestedUri(uri) {
	requestCountOnUri[uri] = (requestCountOnUri[uri] || 0) + 1;
}

module.exports = {
	start: function (port) {
		requestCountOnUri = [];
		server.listen(port || PLEX_SERVER_PORT);
	},

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

	uri: function(uri) {
		return {
			requested: requestCountOnUri[uri] !== undefined
		};
	},

	requests: function() {
		return requestCountOnUri;
	}
};<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.findAll('centre');
  },
  activate() {
    this.io.socket.get('/centres', function serverResponded(body, JWR) {
      console.log('Sails responded with: ', body);
      console.log('with headers: ', JWR.headers);
      console.log('and with status code: ', JWR.statusCode);
    });
  }
});
<commit_msg>BM-417 Application Route to update datastore on server messages received via socket-io<commit_after>import Ember from 'ember';
import DS from 'ember-data';

export default Ember.Route.extend({
  beforeModel() {
    var self = this;
    self.io.socket.on('centres', function(message) {
      var data = message.data;
      var modelClass = self.store.modelFor(data.type);
      var serializer = self.store.serializerFor('application');
      var json = serializer.normalizeSingleResponse(self.store, modelClass, data, data.id);

      self.store.push(json);
    });
  },
  model() {
    return this.store.findAll('centre');
  },
  activate() {
    this.io.socket.get('/centres', function serverResponded(body, JWR) {
    });
  },
  deactivate() {
    this.self.io.socket.disconnect();
  }
});
<|endoftext|>


<commit_before>/*node/no-unpublished-require*/

var expect = require('expect');
var server = require('../lib/server.js');

var http = require('http');
var io = require('socket.io-client');//require('socket.io')(http);
var assert =  require('assert');

let socketAddr = 'http://localhost:';
let socketPort = process.env.PORT || 3000;
let socketURL = socketAddr+socketPort;

let options ={
  transports: ['websocket'],
  'force new connection': true
};

describe('Server',function(){

  it('should connect to socket io 1',function(done){
    let client1 = io.connect(socketURL, options);
    client1.on('connect', function(data){
      done();
    });
    expect(client1).toExist();
  });

  describe('login', function(){
    it('should notify all users if user logs in', function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('login', function(username){
        expect(username).toBe('tom');
      });

      let resultFn = expect.createSpy();

      client1.emit('login','tom',resultFn);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },50);
    });

  });

  it('should run properly run test',function(done){
    expect(server).toExist();
    done();
  });

  describe('Example Node Server', function(){
    it('should return 200', function(done){
      http.get('http://127.0.0.1:'+(process.env.PORT || 3000), res => {
        assert.equal(200, res.statusCode);
        done();
      });
    });
  });

  describe('Logout', function(){
    it('should notify users that a logout event for user has occured', function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('logout', function(username){
        expect(username).toBe('tom');
      });

      let resultFn = expect.createSpy();

      client1.emit('login','tom',()=>{});

      setTimeout(function(){
        client1.emit('logout','tom',resultFn);
      },10);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },20);
    });
  });

  describe('onUserDisconnection',function(){
    it('should log out user and notify all online users',function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('logout', function(username){
        expect(username).toBe('tom');
      });

      client1.emit('login','tom',()=>{});

      setTimeout(function(){
        client1.disconnect();
      },10);

      setTimeout(function(){
        client2.disconnect();
        done();
      },20);
      });
    });

  describe('onMessage',function(){
    it('should broadcast message to all clients',function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      client1.on('message', function(msg){
        expect(msg.author).toBe('tom');
        expect(msg.message).toBe('message contents');
        expect(msg.date).toExist();
      });
      client2.on('message', function(msg){
        expect(msg.author).toBe('tom');
        expect(msg.message).toBe('message contents');
        expect(msg.date).toExist();
      });

      let resultFn = expect.createSpy();
      client1.emit('message',{author:'tom', message:'message contents'},resultFn);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },20);
    });
  });

  describe('onGetMessagesRequest',function(){
    it('should return a list of messages',function(done){
      let client1 = io.connect(socketURL, options);

      let msgs = null;
      client1.emit('get_messages',(res)=>{msgs=res;});

      setTimeout(function(){
        expect(msgs).toExist();
        expect(msgs.length).toBeGreaterThan(0);
        client1.disconnect();
        done();
      },20);
    });
  });

  describe('onGetUsersRequest',function(){
    it('should return a list of users',function(done){
      let client1 = io.connect(socketURL, options);
      client1.emit('login','tom',()=>{});

      let users = null;
      client1.emit('get_users',(res)=>{users=res;});

      setTimeout(function(){
        expect(users).toExist();
        expect(users.length).toBeGreaterThan(0);
        client1.disconnect();
        done();
      },20);
    });
});
});
/*
  checkCallback
    should throw error & result false when callback is not passed
    should throw error & result false when callback is null
    should throw error & result false when callback is string
    should throw error & result false when callback is number
    should return true when callback is a function (tested by successful login/logout)

  onLogin
    @ should notify all users if user logs in
    should not notify all users if a logged in user logs in

  logout
    should not notify users if user wasn't logged in but tries to logout
    @ should notify users that a logout event for user has occured

  onUserConnection

  onUserDisconnection
    @should log out user and notify all online users

  onMessage
    @should broadcast message to all clients

  onGetMessagesRequest
    @should return a list of messages

  onGetUsersRequest
    @should return a list of users

    stashMessages
*/
<commit_msg>increased server.js done() timeout from 20 to 50ms<commit_after>/*node/no-unpublished-require*/

var expect = require('expect');
var server = require('../lib/server.js');

var http = require('http');
var io = require('socket.io-client');//require('socket.io')(http);
var assert =  require('assert');

let socketAddr = 'http://localhost:';
let socketPort = process.env.PORT || 3000;
let socketURL = socketAddr+socketPort;

let options ={
  transports: ['websocket'],
  'force new connection': true
};

describe('Server',function(){

  it('should connect to socket io 1',function(done){
    let client1 = io.connect(socketURL, options);
    client1.on('connect', function(data){
      done();
    });
    expect(client1).toExist();
  });

  describe('login', function(){
    it('should notify all users if user logs in', function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('login', function(username){
        expect(username).toBe('tom');
      });

      let resultFn = expect.createSpy();

      client1.emit('login','tom',resultFn);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },50);
    });

  });

  it('should run properly run test',function(done){
    expect(server).toExist();
    done();
  });

  describe('Example Node Server', function(){
    it('should return 200', function(done){
      http.get('http://127.0.0.1:'+(process.env.PORT || 3000), res => {
        assert.equal(200, res.statusCode);
        done();
      });
    });
  });

  describe('Logout', function(){
    it('should notify users that a logout event for user has occured', function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('logout', function(username){
        expect(username).toBe('tom');
      });

      let resultFn = expect.createSpy();

      client1.emit('login','tom',()=>{});

      setTimeout(function(){
        client1.emit('logout','tom',resultFn);
      },10);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },50);
    });
  });

  describe('onUserDisconnection',function(){
    it('should log out user and notify all online users',function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      //client 2 should be notified when client 1 logs in
      client2.on('logout', function(username){
        expect(username).toBe('tom');
      });

      client1.emit('login','tom',()=>{});

      setTimeout(function(){
        client1.disconnect();
      },10);

      setTimeout(function(){
        client2.disconnect();
        done();
      },50);
      });
    });

  describe('onMessage',function(){
    it('should broadcast message to all clients',function(done){
      let client1 = io.connect(socketURL, options);
      let client2 = io.connect(socketURL, options);

      client1.on('message', function(msg){
        expect(msg.author).toBe('tom');
        expect(msg.message).toBe('message contents');
        expect(msg.date).toExist();
      });
      client2.on('message', function(msg){
        expect(msg.author).toBe('tom');
        expect(msg.message).toBe('message contents');
        expect(msg.date).toExist();
      });

      let resultFn = expect.createSpy();
      client1.emit('message',{author:'tom', message:'message contents'},resultFn);

      setTimeout(function(){
        expect(resultFn).toHaveBeenCalledWith(true);
        client1.disconnect();
        client2.disconnect();
        done();
      },50);
    });
  });

  describe('onGetMessagesRequest',function(){
    it('should return a list of messages',function(done){
      let client1 = io.connect(socketURL, options);

      let msgs = null;
      client1.emit('get_messages',(res)=>{msgs=res;});

      setTimeout(function(){
        expect(msgs).toExist();
        expect(msgs.length).toBeGreaterThan(0);
        client1.disconnect();
        done();
      },50);
    });
  });

  describe('onGetUsersRequest',function(){
    it('should return a list of users',function(done){
      let client1 = io.connect(socketURL, options);
      client1.emit('login','tom',()=>{});

      let users = null;
      client1.emit('get_users',(res)=>{users=res;});

      setTimeout(function(){
        expect(users).toExist();
        expect(users.length).toBeGreaterThan(0);
        client1.disconnect();
        done();
      },50);
    });
});
});
/*
  checkCallback
    should throw error & result false when callback is not passed
    should throw error & result false when callback is null
    should throw error & result false when callback is string
    should throw error & result false when callback is number
    should return true when callback is a function (tested by successful login/logout)

  onLogin
    @ should notify all users if user logs in
    should not notify all users if a logged in user logs in

  logout
    should not notify users if user wasn't logged in but tries to logout
    @ should notify users that a logout event for user has occured

  onUserConnection

  onUserDisconnection
    @should log out user and notify all online users

  onMessage
    @should broadcast message to all clients

  onGetMessagesRequest
    @should return a list of messages

  onGetUsersRequest
    @should return a list of users

    stashMessages
*/
<|endoftext|>


<commit_before>var WebRPCServer = require('../server');

var window = typeof global ? global : window;

function serve() {
  var s = {};
  s.port = 55001;
  s.url = 'ws://localhost:' + s.port + '/';

  // Browser mode: server runs separately in Node.
  if (window.inBrowser)
    return s;

  s.server = new WebRPCServer({ port: s.port });
  s.serverDisconnect = null;

  s.server.onconnect = function connectEvent(ws) {
    ws.emit('connected');
    ws.on('hello', function hello() {
      ws.emit('hi');
    });
    ws.on('how are you?', function mood() {
      return 'good';
    });
    ws.ondisconnect = function disconnectEvent() {
      if (s.serverDisconnect) {
        s.serverDisconnect();
      }
    };
  };

  return s;
}

function fileServe() {
  var http = eval("require('http')");

  var finalhandler = eval("require('finalhandler')");
  var serveStatic = eval("require('serve-static')");

  var serve = serveStatic("./build");

  var server = http.createServer(function(req, res) {
    var done = finalhandler(req, res);
    serve(req, res, done);
  });

  server.listen(8080);

  return server;
}

function sauceTest(fn) {
  var sauceConnectLauncher = eval("require('sauce-connect-launcher')");
  var MochaSauce = eval("require('./mocha-sauce-server')");

  // Open a sauce-connect connection.
  sauceConnectLauncher({
    username: process.env.SAUCE_USERNAME,
    accessKey: process.env.SAUCE_ACCESS_KEY,
    build: process.env.TRAVIS_BUILD_NUMBER,
    tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
  }, function (err, sauceConnectProcess) {
    if (err) {
      console.error(err.message);
      return;
    }
    console.log("Sauce Connect ready");

    var sauce = new MochaSauce({
      name: "webrpc.js",
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      build: process.env.TRAVIS_BUILD_NUMBER,
      tunnel: process.env.TRAVIS_JOB_NUMBER,
      url: "http://localhost:8080/"
    });

    // A simple browser matrix.
    sauce.browser({ browserName: 'firefox', platform: 'Windows 7' });
    sauce.browser({ browserName: 'chrome', platform: 'Windows 7' });
    sauce.browser({ browserName: 'internet explorer', version: '10', platform: 'Windows 7' });
    sauce.browser({ browserName: 'internet explorer', version: '11', platform: 'Windows 7' });

    // Console output for debugging.
    sauce.on('init', function(browser) {
      console.log('  init : %s %s', browser.browserName, browser.platform);
    });
    sauce.on('start', function(browser) {
      console.log('  start : %s %s', browser.browserName, browser.platform);
    });
    sauce.on('end', function(browser, res) {
      console.log('  end : %s %s : %d failures', browser.browserName, browser.platform, res.failures);
    });

    // Run tests, close tunnel, run callback.
    sauce.start(function() {
      sauceConnectProcess.close(function () {
        console.log("Closed Sauce Connect process");
      });

      if (fn) fn();
    });
  });
}

function harness() {
  process.chdir(__dirname);
  var webpack = eval("require('webpack')");
  var cfg = eval("require('./webpack.config')");

  // start websocket server
  var s = serve().server;

  // compile code
  webpack(cfg, function(err, stats) {
    if (err)
      throw err;

    var fs = fileServe();

    // If SAUCE_ACCESS_KEY is set, test via SauceLabs.
    if (process.env.SAUCE_ACCESS_KEY)
      sauceTest(function() {
        s.close();
        fs.close();
        process.exit();
      });
  })
}

require.main === module && harness();
module.exports = serve;
<commit_msg>Fix sauce-connect arguments.<commit_after>var WebRPCServer = require('../server');

var window = typeof global ? global : window;

function serve() {
  var s = {};
  s.port = 55001;
  s.url = 'ws://localhost:' + s.port + '/';

  // Browser mode: server runs separately in Node.
  if (window.inBrowser)
    return s;

  s.server = new WebRPCServer({ port: s.port });
  s.serverDisconnect = null;

  s.server.onconnect = function connectEvent(ws) {
    ws.emit('connected');
    ws.on('hello', function hello() {
      ws.emit('hi');
    });
    ws.on('how are you?', function mood() {
      return 'good';
    });
    ws.ondisconnect = function disconnectEvent() {
      if (s.serverDisconnect) {
        s.serverDisconnect();
      }
    };
  };

  return s;
}

function fileServe() {
  var http = eval("require('http')");

  var finalhandler = eval("require('finalhandler')");
  var serveStatic = eval("require('serve-static')");

  var serve = serveStatic("./build");

  var server = http.createServer(function(req, res) {
    var done = finalhandler(req, res);
    serve(req, res, done);
  });

  server.listen(8080);

  return server;
}

function sauceTest(fn) {
  var sauceConnectLauncher = eval("require('sauce-connect-launcher')");
  var MochaSauce = eval("require('./mocha-sauce-server')");

  // Open a sauce-connect connection.
  sauceConnectLauncher({
    username: process.env.SAUCE_USERNAME,
    accessKey: process.env.SAUCE_ACCESS_KEY,
    tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
    vmVersion: "dev-varnish"
  }, function (err, sauceConnectProcess) {
    if (err) {
      console.error(err.message);
      return;
    }
    console.log("Sauce Connect ready");

    var sauce = new MochaSauce({
      name: "webrpc.js",
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      build: process.env.TRAVIS_BUILD_NUMBER,
      tunnel: process.env.TRAVIS_JOB_NUMBER,
      url: "http://localhost:8080/"
    });

    // A simple browser matrix.
    sauce.browser({ browserName: 'firefox', platform: 'Windows 7' });
    sauce.browser({ browserName: 'chrome', platform: 'Windows 7' });
    sauce.browser({ browserName: 'internet explorer', version: '10', platform: 'Windows 7' });
    sauce.browser({ browserName: 'internet explorer', version: '11', platform: 'Windows 7' });

    // Console output for debugging.
    sauce.on('init', function(browser) {
      console.log('  init : %s %s', browser.browserName, browser.platform);
    });
    sauce.on('start', function(browser) {
      console.log('  start : %s %s', browser.browserName, browser.platform);
    });
    sauce.on('end', function(browser, res) {
      console.log('  end : %s %s : %d failures', browser.browserName, browser.platform, res.failures);
    });

    // Run tests, close tunnel, run callback.
    sauce.start(function() {
      sauceConnectProcess.close(function () {
        console.log("Closed Sauce Connect process");
      });

      if (fn) fn();
    });
  });
}

function harness() {
  process.chdir(__dirname);
  var webpack = eval("require('webpack')");
  var cfg = eval("require('./webpack.config')");

  // start websocket server
  var s = serve().server;

  // compile code
  webpack(cfg, function(err, stats) {
    if (err)
      throw err;

    var fs = fileServe();

    // If SAUCE_ACCESS_KEY is set, test via SauceLabs.
    if (process.env.SAUCE_ACCESS_KEY)
      sauceTest(function() {
        s.close();
        fs.close();
        process.exit();
      });
  })
}

require.main === module && harness();
module.exports = serve;
<|endoftext|>


<commit_before>var gui = require('nw.gui');
var log = require('./lib/log.js');
var argv = require('./lib/argv.js');
var os = require('os');
var TorrentDownloader = require('./lib/TorrentDownloader.js');
var LogLevel = require('yalla').LogLevel;
var humanize = require('humanize');

/*
 Bootstrap
 */
argv.init(gui.App.argv); // provide access to process argv to all require()d modules

process.mainModule.exports.init(); // init nodeMain.js

var config = require('./lib/config.js'); // config depends on argv, but cannot access it before we initialize argv module

// set the log level
if (config.logLevel) {
    log.setLevel(config.logLevel)
} else if (config.debug) {
    log.setLevel(LogLevel.DEBUG)
}

log.info('bootstrapping done.');

process.on('uncaughtException', function (err) {
    log.error(err)
});

// Get the current window
var win = gui.Window.get();
var downloader, download_form, download_info;

$(function () {
    download_form = $('#download_form');
    download_info = $('#download_info');
    var totalLength;

    $('#download_btn', download_form).click(function () {
        var downloadLink = $('#download_link').val();
        if(!downloadLink) {
            downloadLink = 'http://torrent.fedoraproject.org/torrents/Fedora-20-x86_64-DVD.torrent';
        }

        var targetFolder = $('#target_folder').val();
        if(!targetFolder) {
            targetFolder = '/tmp';
        }

        downloader = new TorrentDownloader(downloadLink, targetFolder);

        $('#download_status').text('Starting download...');

        downloader.on('start', function () {
            $('#download_status').text('Downloading...');
        });

        downloader.on('info', function (info) {
            //
            totalLength = info.length;

            $('#filelist_toggle .total_files').text(info.files.length);
            $(info.files).each(function (index, file) {
                var li = $('<li />').text(humanize.filesize(file.length) + ' // ' + file.path);
                $('.filelist').append(li);
            });
        });

        downloader.on('progress', function (pct) {
            //log.info('progress: ' + pct + '%');
            $('.progress .bar').css('width', pct + '%');
            $('.progress .percent').text((Math.round(pct * 100) / 100) + '%' + ' | ' + humanize.filesize(downloadSize * pct) + '/' + humanize.filesize(downloadSize));
        });

        downloader.start();

        download_form.hide();
        download_info.css('display', 'flex');
    });

    $('#stop_download', download_info).click(function () {
        downloader.stop();
        downloader = null;
        download_info.hide();
        download_form.css('display', 'flex');
    });

    $('#filelist_toggle').click(function () {
        $('.filelist').toggle();

        $('#filelist_toggle .label').text($('.filelist').is(':visible') ? '- Hide file list' : '+ Show file list')
    });
});<commit_msg>index fixes<commit_after>var gui = require('nw.gui');
var log = require('./lib/log.js');
var argv = require('./lib/argv.js');
var os = require('os');
var TorrentDownloader = require('./lib/TorrentDownloader.js');
var LogLevel = require('yalla').LogLevel;
var humanize = require('humanize');

/*
 Bootstrap
 */
argv.init(gui.App.argv); // provide access to process argv to all require()d modules

process.mainModule.exports.init(); // init nodeMain.js

var config = require('./lib/config.js'); // config depends on argv, but cannot access it before we initialize argv module

// set the log level
if (config.logLevel) {
    log.setLevel(config.logLevel)
} else if (config.debug) {
    log.setLevel(LogLevel.DEBUG)
}

log.info('bootstrapping done.');

process.on('uncaughtException', function (err) {
    log.error(err)
});

// Get the current window
var win = gui.Window.get();
var downloader, download_form, download_info;

$(function () {
    download_form = $('#download_form');
    download_info = $('#download_info');
    var totalLength;

    $('#download_btn', download_form).click(function () {
        totalLength = 0;

        var downloadLink = $('#download_link').val();
        if(!downloadLink) {
            downloadLink = 'http://torrent.fedoraproject.org/torrents/Fedora-20-x86_64-DVD.torrent';
        }

        var targetFolder = $('#target_folder').val();
        if(!targetFolder) {
            targetFolder = '/tmp';
        }

        downloader = new TorrentDownloader(downloadLink, targetFolder);

        $('#download_status').text('Starting download...');

        downloader.on('start', function () {
            $('#download_status').text('Downloading...');
        });

        downloader.on('info', function (info) {
            //
            totalLength = info.length;

            $('#filelist_toggle .total_files').text(info.files.length);
            $(".filelist").empty();
            $(info.files).each(function (index, file) {
                var li = $('<li />').text(humanize.filesize(file.length) + ' // ' + file.path);
                $('.filelist').append(li);
            });
        });

        downloader.on('progress', function (pct) {
            //log.info('progress: ' + pct + '%');
            $('.progress .bar').css('width', pct + '%');
            $('.progress .percent').text((Math.round(pct * 100) / 100) + '%' + ' | ' + humanize.filesize(totalLength * pct / 100) + '/' + humanize.filesize(totalLength));
        });

        downloader.start();

        download_form.hide();
        download_info.css('display', 'flex');
    });

    $('#stop_download', download_info).click(function () {
        downloader.stop();
        downloader = null;
        download_info.hide();
        download_form.css('display', 'flex');
    });

    $('#filelist_toggle').click(function () {
        $('.filelist').toggle();

        $('#filelist_toggle .label').text($('.filelist').is(':visible') ? '- Hide file list' : '+ Show file list')
    });
});
<|endoftext|>


<commit_before>'use strict';

/*
 * Simple API tests
 */

/*
 * Could also check out the nock package to record / replay http interactions
 */

// mocha defines to avoid JSHint breakage
/* global describe, it, before, beforeEach, after, afterEach */

require('mocha-jshint')(); // run JSHint as part of testing

var restbase = require('../lib/server.js');
var preq = require('preq');
var hostPort = 'http://localhost:7231';
var baseURL = hostPort + '/v1/en.wikipedia.test.local';
var bucketURL = baseURL + '/pages';
var assert = require('./util/assert.js');
require('./util/promise.js')(); // augment the Promise prototype

var closeRestbase;

function commonTests() {
    it('should return HTML just created with revision 624484477', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/html/624484477'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
        });
    });
    it('should return HTML just created by revision 624165266', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/html/624165266'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'text/html; charset=UTF-8');
        });
    });
    it('should return data-parsoid just created by revision 624165266, rev 2', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/data-parsoid/624165266'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'application/json; profile=mediawiki.org/specs/data-parsoid/1.0');
        });
    });

    it('should return data-parsoid just created with revision 624484477, rev 2', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/data-parsoid/624484477'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'application/json; profile=mediawiki.org/specs/data-parsoid/1.0');
        });
    });

}

describe('Simple API tests', function () {
    this.timeout(20000);
    before(function() {
        return restbase({
            logging: {
                name: 'restbase-tests',
                level: 'warn'
            }
        }).then(function(server){
            closeRestbase = function () { server.close(); };
        });
    });
    describe('Domain & bucket creation', function() {
        it('should create a domain', function() {
            return preq.put({
                uri: hostPort + '/v1/en.wikipedia.test.local',
                headers: { 'content-type': 'application/json' },
                body: {}
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            });
        });
    });
    describe('Bucket creation', function() {
        it('should require a bucket type', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: {}
            })
            .fails(function(e) {
                assert.deepEqual(e.status, 400);
                assert.deepEqual(e.body.title, 'Invalid bucket spec.');
            });
        });
        it('should require a valid bucket type', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: { type: 'wazzle' }
            })
            .fails(function(e) {
                assert.deepEqual(e.status, 400);
                assert.deepEqual(e.body.title, 'Invalid bucket spec.');
            });
        });
        it('should create a page bucket', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: { type: 'pagecontent' }
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            });
        });
    });
    describe('Item requests', function() {
        //it('should not accept a new html save without a revision', function() {
        //    return preq.put({
        //        uri: bucketURL + '/Foo/html',
        //        headers: { 'content-type': 'text/html' },
        //        body: 'Hello there'
        //    })
        //    .then(function(res) {
        //        assert.deepEqual(res.status, 404);
        //    });
        //});
        it('should respond to OPTIONS request with CORS headers', function() {
            this.timeout(20000);
            return preq.options({ uri: bucketURL + '/Foobar/html/624484477' })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.headers['access-control-allow-origin'], '*');
                assert.deepEqual(res.headers['access-control-allow-methods'], 'GET');
                assert.deepEqual(res.headers['access-control-allow-headers'], 'accept, content-type');
            });
        });
        it('should transparently create a new HTML revision with id 624484477', function() {
            this.timeout(20000);
            return preq.get({
                uri: bucketURL + '/Foobar/html/624484477',
                headers: { 'content-type': 'text/html' },
                body: 'Hello there'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
            });
        });
        it('should transparently create data-parsoid with id 624165266, rev 2', function() {
            this.timeout(20000);
            return preq.get({
                uri: bucketURL + '/Foobar/html/624165266'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
            });
        });
        // This is meant to test ../lib/filters/conf/testHandler.yml
        // Re-enable when that is fixed
        //it('should transparently create a new wikitext revision using proxy handler with id 624484477', function() {
        //    this.timeout(20000);
        //    return preq.get({
        //        uri: bucketURL + '/Foobar/wikitext/624484477',
        //        headers: { 'content-type': 'text/wikitext' },
        //        body: 'Hello there'
        //    })
        //    .then(function(res) {
        //        deepEqual(res.status, 200);
        //    });
        //});
        commonTests();
        it('should accept a new html save with a revision', function() {
            return preq.put({
                uri: bucketURL + '/Foobar/html/76f22880-362c-11e4-9234-0123456789ab',
                headers: { 'content-type': 'text/html; charset=UTF-8' },
                body: 'Hello there'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            })
            .catch(function(e) {
                console.dir(e);
                throw e;
            });
        });
        it('should return the HTML revision just created', function() {
            return preq.get({
                uri: bucketURL + '/Foobar/html/624484477'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.headers['content-type'], 'text/html; charset=UTF-8');
                assert.deepEqual(res.headers.etag, '76f22880-362c-11e4-9234-0123456789ab');
                assert.deepEqual(res.body, 'Hello there');
            });
        });
    });
    describe('404 handling', function() {
        it('should return a proper 404 when trying to retrieve a non-existing domain', function() {
            return preq.get({
                uri: hostPort + '/v1/foobar.com'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when trying to list a non-existing domain', function() {
            return preq.get({
                uri: hostPort + '/v1/foobar.com/'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when accessing an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when trying to list an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket/'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when accessing an item in an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket/item'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
    });

    describe('automated specification tests', function() {

        var specs = require('./util/specs.js');

        // Wrap an HTTP request in a continuation
        function requestK(req) {
            return function () {
                return preq[req.method](req);
            };
        }

        specs.getSpec('http://wikimedia.github.io/restbase/v1/swagger.yaml', function (spec) {
            var xamples = specs.parseXamples(spec, hostPort);
            describe('swagger.yaml', function() {
                var expected = xamples.length;
                var actual = 0;
                xamples.map(function (xample) {
                    it(xample.desc, function() {
                        // Chain the prerequesites in order
                        return xample.prereqs.reduce(function (p, prereq) {
                            return p.then(requestK(prereq));
                        }, Promise.resolve(true))
                        // Fire off the main request
                        .then(requestK(xample.request))
                        // Validate the response
                        .then(function (res) {
                            // The date is too unpredictable to test -- toss it out
                            if (res.headers && res.headers.date) {
                                delete res.headers.date;
                            }
                            assert.deepEqual(res, xample.response);
                            actual = actual + 1;
                        });
                    });
                });
                it('should have verified ' + expected + ' x-ample(s)', function () {
                    assert.deepEqual(actual, expected);
                });
            });
        });

    });
});

describe('Phase 2 - running tests with a restart', function() {
    this.timeout(20000);
    setTimeout(function() {}, 5000);
    before(function() {
        closeRestbase();
        return restbase({
            logging: {
                name: 'restbase-tests',
                level: 'warn'
            }
        });
    });
    describe('It should pass some tests from phase 1', function() {
        commonTests();
    });
});
<commit_msg>Move url out into a variable<commit_after>'use strict';

/*
 * Simple API tests
 */

/*
 * Could also check out the nock package to record / replay http interactions
 */

// mocha defines to avoid JSHint breakage
/* global describe, it, before, beforeEach, after, afterEach */

require('mocha-jshint')(); // run JSHint as part of testing

var restbase = require('../lib/server.js');
var preq = require('preq');
var hostPort = 'http://localhost:7231';
var baseURL = hostPort + '/v1/en.wikipedia.test.local';
var bucketURL = baseURL + '/pages';
var assert = require('./util/assert.js');
require('./util/promise.js')(); // augment the Promise prototype

var closeRestbase;

function commonTests() {
    it('should return HTML just created with revision 624484477', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/html/624484477'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
        });
    });
    it('should return HTML just created by revision 624165266', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/html/624165266'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'text/html; charset=UTF-8');
        });
    });
    it('should return data-parsoid just created by revision 624165266, rev 2', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/data-parsoid/624165266'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'application/json; profile=mediawiki.org/specs/data-parsoid/1.0');
        });
    });

    it('should return data-parsoid just created with revision 624484477, rev 2', function() {
        return preq.get({
            uri: bucketURL + '/Foobar/data-parsoid/624484477'
        })
        .then(function(res) {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.headers['content-type'], 'application/json; profile=mediawiki.org/specs/data-parsoid/1.0');
        });
    });

}

describe('Simple API tests', function () {
    this.timeout(20000);
    before(function() {
        return restbase({
            logging: {
                name: 'restbase-tests',
                level: 'warn'
            }
        }).then(function(server){
            closeRestbase = function () { server.close(); };
        });
    });
    describe('Domain & bucket creation', function() {
        it('should create a domain', function() {
            return preq.put({
                uri: hostPort + '/v1/en.wikipedia.test.local',
                headers: { 'content-type': 'application/json' },
                body: {}
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            });
        });
    });
    describe('Bucket creation', function() {
        it('should require a bucket type', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: {}
            })
            .fails(function(e) {
                assert.deepEqual(e.status, 400);
                assert.deepEqual(e.body.title, 'Invalid bucket spec.');
            });
        });
        it('should require a valid bucket type', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: { type: 'wazzle' }
            })
            .fails(function(e) {
                assert.deepEqual(e.status, 400);
                assert.deepEqual(e.body.title, 'Invalid bucket spec.');
            });
        });
        it('should create a page bucket', function() {
            this.timeout(20000);
            return preq.put({
                uri: bucketURL,
                headers: { 'content-type': 'application/json' },
                body: { type: 'pagecontent' }
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            });
        });
    });
    describe('Item requests', function() {
        //it('should not accept a new html save without a revision', function() {
        //    return preq.put({
        //        uri: bucketURL + '/Foo/html',
        //        headers: { 'content-type': 'text/html' },
        //        body: 'Hello there'
        //    })
        //    .then(function(res) {
        //        assert.deepEqual(res.status, 404);
        //    });
        //});
        it('should respond to OPTIONS request with CORS headers', function() {
            this.timeout(20000);
            return preq.options({ uri: bucketURL + '/Foobar/html/624484477' })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.headers['access-control-allow-origin'], '*');
                assert.deepEqual(res.headers['access-control-allow-methods'], 'GET');
                assert.deepEqual(res.headers['access-control-allow-headers'], 'accept, content-type');
            });
        });
        it('should transparently create a new HTML revision with id 624484477', function() {
            this.timeout(20000);
            return preq.get({
                uri: bucketURL + '/Foobar/html/624484477',
                headers: { 'content-type': 'text/html' },
                body: 'Hello there'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
            });
        });
        it('should transparently create data-parsoid with id 624165266, rev 2', function() {
            this.timeout(20000);
            return preq.get({
                uri: bucketURL + '/Foobar/html/624165266'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
            });
        });
        // This is meant to test ../lib/filters/conf/testHandler.yml
        // Re-enable when that is fixed
        //it('should transparently create a new wikitext revision using proxy handler with id 624484477', function() {
        //    this.timeout(20000);
        //    return preq.get({
        //        uri: bucketURL + '/Foobar/wikitext/624484477',
        //        headers: { 'content-type': 'text/wikitext' },
        //        body: 'Hello there'
        //    })
        //    .then(function(res) {
        //        deepEqual(res.status, 200);
        //    });
        //});
        commonTests();
        it('should accept a new html save with a revision', function() {
            return preq.put({
                uri: bucketURL + '/Foobar/html/76f22880-362c-11e4-9234-0123456789ab',
                headers: { 'content-type': 'text/html; charset=UTF-8' },
                body: 'Hello there'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 201);
            })
            .catch(function(e) {
                console.dir(e);
                throw e;
            });
        });
        it('should return the HTML revision just created', function() {
            return preq.get({
                uri: bucketURL + '/Foobar/html/624484477'
            })
            .then(function(res) {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.headers['content-type'], 'text/html; charset=UTF-8');
                assert.deepEqual(res.headers.etag, '76f22880-362c-11e4-9234-0123456789ab');
                assert.deepEqual(res.body, 'Hello there');
            });
        });
    });
    describe('404 handling', function() {
        it('should return a proper 404 when trying to retrieve a non-existing domain', function() {
            return preq.get({
                uri: hostPort + '/v1/foobar.com'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when trying to list a non-existing domain', function() {
            return preq.get({
                uri: hostPort + '/v1/foobar.com/'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when accessing an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when trying to list an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket/'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
        it('should return a proper 404 when accessing an item in an unknown bucket', function() {
            return preq.get({
                uri: baseURL + '/some_nonexisting_bucket/item'
            })
            .catch(function(e) {
                assert.deepEqual(e.status, 404);
                assert.deepEqual(e.headers['content-type'], 'application/problem+json');
            });
        });
    });

    describe('automated specification tests', function() {

        var specs = require('./util/specs.js');

        // Wrap an HTTP request in a continuation
        function requestK(req) {
            return function () {
                return preq[req.method](req);
            };
        }

        var specUrl = 'http://wikimedia.github.io/restbase/v1/swagger.yaml';

        specs.getSpec(specUrl, function (spec) {
            var xamples = specs.parseXamples(spec, hostPort);
            describe('swagger.yaml', function() {
                var expected = xamples.length;
                var actual = 0;
                xamples.map(function (xample) {
                    it(xample.desc, function() {
                        // Chain the prerequesites in order
                        return xample.prereqs.reduce(function (p, prereq) {
                            return p.then(requestK(prereq));
                        }, Promise.resolve(true))
                        // Fire off the main request
                        .then(requestK(xample.request))
                        // Validate the response
                        .then(function (res) {
                            // The date is too unpredictable to test -- toss it out
                            if (res.headers && res.headers.date) {
                                delete res.headers.date;
                            }
                            assert.deepEqual(res, xample.response);
                            actual = actual + 1;
                        });
                    });
                });
                it('should have verified ' + expected + ' x-ample(s)', function () {
                    assert.deepEqual(actual, expected);
                });
            });
        });

    });
});

describe('Phase 2 - running tests with a restart', function() {
    this.timeout(20000);
    setTimeout(function() {}, 5000);
    before(function() {
        closeRestbase();
        return restbase({
            logging: {
                name: 'restbase-tests',
                level: 'warn'
            }
        });
    });
    describe('It should pass some tests from phase 1', function() {
        commonTests();
    });
});
<|endoftext|>