<commit_before>/* jshint esversion:6, node: true */

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();

app.set('port', (process.env.PORT || 5000));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse application/json
app.use(bodyParser.json());

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot');
});

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge']);
	} else {
		res.send('Error, wrong token');
	}
});

// to post data
app.post('/webhook/', function (req, res) {
	var results;

	let messaging_events = req.body.entry[0].messaging;
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i];
		let sender = event.sender.id;
		//requestSearchType(sender);

		if (event.message && event.message.text) {
			let text = event.message.text;
			if (text == 'Generic') {
				sendGenericMessage(sender);
				continue;
			}
			else if(text == 'hi' || text =='hey'){
				//requestSearchType(sender);
				continue;
			}
			else if (text.includes("product: ")){
				var headers = {
				    'Authorization': 'bearer fd887ce5-7b15-4c1e-93a0-dc91ce883ec6'
				};

				//Extract the search key
				var str = text.replace('product: ',' ');
				console.log(str);
				var url = 'https://www.loblaws.ca/ecommerce/v2/loblaw/products/search?q=';
				url = url.concat(str.trim(), '&page=0&pageSize=10&sort=recommended');
				console.log(url);

				var options = {
				    url: url,
				    headers: headers
				};
				function callback(error, response, body) {
				    if (!error && response.statusCode == 200) {
				        console.log(body);
				        var resp = JSON.parse(body);
				        results = resp["searchResults"];
				        console.log(results[0]);
				        console.log(results.products.totalNumberOfResults);

				        if(results.products.totalNumberOfResults != 0)
							sendProductMessage(sender, results);
						else{
							sendTextMessage(sender, "There are no results for that search.", token);
						}
				    }
				}

				request(options, callback);

			}
			//sendTextMessage(sender, "echo: " + text.substring(0, 200));
		}
		if (event.postback) {
			switch(JSON.stringify(postback.payload)){
				case "searchProduct":
					sendTextMessage(sender, "Search by product", token);
					break;
				case "searchRecipe":
					sendTextMessage(sender, "Search by recipe", token);
					break;
				case "searchBarcode":
					sendTextMessage(sender, "Search by barcode", token);
					break;
			}
			continue;
		}
	}
	res.sendStatus(200);
});

//Request for product, image, or recipe search
function requestSearchType(sender){
	let messageData = {
		"attachment": {
			"type": "template",
			"payload":{
		        "template_type":"button",
		        "text":"What do you want to do next?",
		        "buttons":[
		          {
			        "type":"postback",
			        "title":"By Product",
			        "payload":"searchProduct",
			      },
			      {
			        "type":"postback",
			        "title":"By Recipe",
			        "payload":"searchRecipe",
			      },
			      {
			      	"type":"postback",
			      	"title": "By Barcode",
			      	"payload": "searchBarcode"
			      }
        		]
      		}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: sender,
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

// recommended to inject access tokens as environmental variables, e.g.
const token = process.env.PAGE_ACCESS_TOKEN;
//const token = "<PAGE_ACCESS_TOKEN>"

function sendTextMessage(sender, text) {
	let messageData = { text:text };

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

/*
	* Results is the api response
	* Makes a carouel displaying tile, description, and image
*/
function sendProductMessage(sender, results) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": loadElements(results.products) //Load the products into an object that messenger api can handle
				/*"elements": [{
					"title": results.products[0].productName,
					"subtitle": results.products[0].description,
					"image_url": results.products[0].primaryImage,
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}] */
			}
		}
	};

	//Send message
	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

/*
	* Load products into an array that can be handled by messenger api
	* Makes carousel as long as number of responses
*/
function loadElements(products){
	var elements = []; //Create blank array

	console.log("Length: " + products.length);

	for (var i = 0; i < products.length; i++){
		var element = {
			"title": products[i].productName, //Sets title
			"subtitle": products[i].description, //Sets description
			"image_url": products[i].primaryImage, //Sets image
		};

		elements.push(element); //Add the element to the array
	}

	return elements;
}

// Start the server
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
});
<commit_msg>Uncommented "requestSearchType" to test buttons<commit_after>/* jshint esversion:6, node: true */

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();

app.set('port', (process.env.PORT || 5000));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse application/json
app.use(bodyParser.json());

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot');
});

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge']);
	} else {
		res.send('Error, wrong token');
	}
});

// to post data
app.post('/webhook/', function (req, res) {
	var results;

	let messaging_events = req.body.entry[0].messaging;
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i];
		let sender = event.sender.id;
		//requestSearchType(sender);

		if (event.message && event.message.text) {
			let text = event.message.text;
			if (text == 'Generic') {
				sendGenericMessage(sender);
				continue;
			}
			else if(text == 'hi' || text =='hey'){
				requestSearchType(sender);
				continue;
			}
			else if (text.includes("product: ")){
				var headers = {
				    'Authorization': 'bearer fd887ce5-7b15-4c1e-93a0-dc91ce883ec6'
				};

				//Extract the search key
				var str = text.replace('product: ',' ');
				console.log(str);
				var url = 'https://www.loblaws.ca/ecommerce/v2/loblaw/products/search?q=';
				url = url.concat(str.trim(), '&page=0&pageSize=10&sort=recommended');
				console.log(url);

				var options = {
				    url: url,
				    headers: headers
				};
				function callback(error, response, body) {
				    if (!error && response.statusCode == 200) {
				        console.log(body);
				        var resp = JSON.parse(body);
				        results = resp["searchResults"];
				        console.log(results[0]);
				        console.log(results.products.totalNumberOfResults);

				        if(results.products.totalNumberOfResults != 0)
							sendProductMessage(sender, results);
						else{
							sendTextMessage(sender, "There are no results for that search.", token);
						}
				    }
				}

				request(options, callback);

			}
			//sendTextMessage(sender, "echo: " + text.substring(0, 200));
		}
		if (event.postback) {
			switch(JSON.stringify(event.postback)){
				case "searchProduct":
					sendTextMessage(sender, "Search by product", token);
					break;
				case "searchRecipe":
					sendTextMessage(sender, "Search by recipe", token);
					break;
				case "searchBarcode":
					sendTextMessage(sender, "Search by barcode", token);
					break;
			}
			continue;
		}
	}
	res.sendStatus(200);
});

//Request for product, image, or recipe search
function requestSearchType(sender){
	let messageData = {

		"attachment": {
			"type": "template",
			"payload":{
		        "template_type":"button",
		        "text":"What do you want to do next?",
		        "buttons":[
		          {
			        "type":"postback",
			        "title":"By Product",
			        "payload":"searchProduct",
			      },
			      {
			        "type":"postback",
			        "title":"By Recipe",
			        "payload":"searchRecipe",
			      },
			      {
			      	"type":"postback",
			      	"title": "By Barcode",
			      	"payload": "searchBarcode"
			      }
        		]
      		}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: sender,
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

// recommended to inject access tokens as environmental variables, e.g.
const token = process.env.PAGE_ACCESS_TOKEN;
//const token = "<PAGE_ACCESS_TOKEN>"

function sendTextMessage(sender, text) {
	let messageData = { text:text };

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

/*
	* Results is the api response
	* Makes a carouel displaying tile, description, and image
*/
function sendProductMessage(sender, results) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": loadElements(results.products) //Load the products into an object that messenger api can handle
				/*"elements": [{
					"title": results.products[0].productName,
					"subtitle": results.products[0].description,
					"image_url": results.products[0].primaryImage,
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}] */
			}
		}
	};

	//Send message
	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

/*
	* Load products into an array that can be handled by messenger api
	* Makes carousel as long as number of responses
*/
function loadElements(products){
	var elements = []; //Create blank array

	console.log("Length: " + products.length);

	for (var i = 0; i < products.length; i++){
		var element = {
			"title": products[i].productName, //Sets title
			"subtitle": products[i].description, //Sets description
			"image_url": products[i].primaryImage, //Sets image
		};

		elements.push(element); //Add the element to the array
	}

	return elements;
}

// Start the server
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
});
<|endoftext|>


<commit_before>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');

var bluecifer = new Bluecifer (150, 150, 50, 41);

$('#game-over').css('visibility', 'visible');

var themeSong = document.getElementById("theme-song");

var enemy = new Enemy();
var enemy2 = new Enemy();
var enemy3 = new Enemy();

function drawAirport () {
  var image = new Image();
  image.src = "IMGS/dia-photo.jpg";
  ctx.drawImage(image, 150, 340, 30, 30);
  var airport = {};
  airport.x = 150;
  airport.y = 340;
  airportCollision(airport, bluecifer);
  return this;
}

function newEnemy () {
  enemy.draw(ctx);
  // collision(enemy, bluecifer);
  enemy.moveLeftRandom();
}

function newEnemy2 () {
  enemy2.draw(ctx);
  // collision(enemy2, bluecifer);
  setTimeout(function() {
    enemy2.moveLeftRandom();
    return enemy2;
  }, 3000);
}

function newEnemy3 () {
  enemy3.draw(ctx);
  // collision(enemy3, bluecifer);
  setTimeout(function() {
    enemy3.moveLeftRandom();
    return enemy3;
  }, 6000);
}

function collision(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    themeSong.pause();
    $('#game-over').css('visibility', 'visible');
    resetGame();
  }
} //end of collision function

function airportCollision (a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    themeSong.pause();
    alert("You win!");
    resetGame();
  }
} //end of airportCollision function

function repeat () {
  setTimeout(function() {
    requestAnimationFrame(repeat);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    bluecifer.draw(ctx);
    bluecifer.gravity();
    newEnemy();
    newEnemy2();
    newEnemy3();
    detectFloorCollision();
  }, 1000 / 50);
    keepScore();
} //end of big repeat function

$(document).on("click", function () {
  themeSong.play();
  $('#game-over').css('visibility', 'hidden');
  repeat();
});

var scoreCounter = 0;

function keepScore() {
    var currentScore = scoreCounter++;
    if (currentScore <= 100){
   $('#game-score').text("000" + currentScore);
 }else if (currentScore <= 1000){
  $('#game-score').text("00" + currentScore);
}else if (currentScore <= 10000){
  $('#game-score').text("0" + currentScore);
  drawAirport();
}else{
  $('#game-score').text(currentScore);
  }
}

function detectFloorCollision () {
  if (bluecifer.y > 350) {
    themeSong.pause();
    resetGame();
    bluecifer.y = 300;
  }
}

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('#game-over').css('visibility', 'hidden')) {
      bluecifer.moveUp();
      detectCeilingCollision();
    }
    else {
      resetGame();
    }
  } //end of if statement for space bar
  else if (key.which === 13) {
    themeSong.pause();
  } // end of if statement for enter key
}); //end of entire function

function detectCeilingCollision () {
  if (bluecifer.y < 0) {
    bluecifer.y = bluecifer.y + 20;
  }
}

function resetGame () {
  alert("Game over! Your score was " + scoreCounter);
  location.reload();
  $('#game-over').css('visibility', 'hidden');
  repeat();
}
<commit_msg>refactored airport object to make less repetitive<commit_after>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');

var bluecifer = new Bluecifer (150, 150, 50, 41);

$('#game-over').css('visibility', 'visible');

var themeSong = document.getElementById("theme-song");

var enemy = new Enemy();
var enemy2 = new Enemy();
var enemy3 = new Enemy();

function drawAirport () {
  var image = new Image();
  image.src = "IMGS/dia-photo.jpg";
  var airport = {};
  airport.x = 150;
  airport.y = 340;
  ctx.drawImage(image, airport.x, airport.y, 30, 30);
  airportCollision(airport, bluecifer);
  return this;
}

function newEnemy () {
  enemy.draw(ctx);
  // collision(enemy, bluecifer);
  enemy.moveLeftRandom();
}

function newEnemy2 () {
  enemy2.draw(ctx);
  // collision(enemy2, bluecifer);
  setTimeout(function() {
    enemy2.moveLeftRandom();
    return enemy2;
  }, 3000);
}

function newEnemy3 () {
  enemy3.draw(ctx);
  // collision(enemy3, bluecifer);
  setTimeout(function() {
    enemy3.moveLeftRandom();
    return enemy3;
  }, 6000);
}

function collision(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    themeSong.pause();
    $('#game-over').css('visibility', 'visible');
    resetGame();
  }
} //end of collision function

function airportCollision (a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    themeSong.pause();
    alert("You win!");
    resetGame();
  }
} //end of airportCollision function

function repeat () {
  setTimeout(function() {
    requestAnimationFrame(repeat);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    bluecifer.draw(ctx);
    bluecifer.gravity();
    newEnemy();
    newEnemy2();
    newEnemy3();
    detectFloorCollision();
  }, 1000 / 50);
    keepScore();
} //end of big repeat function

$(document).on("click", function () {
  themeSong.play();
  $('#game-over').css('visibility', 'hidden');
  repeat();
});

var scoreCounter = 0;

function keepScore() {
    var currentScore = scoreCounter++;
    if (currentScore <= 100){
   $('#game-score').text("000" + currentScore);
 }else if (currentScore <= 1000){
  $('#game-score').text("00" + currentScore);
}else if (currentScore <= 10000){
  $('#game-score').text("0" + currentScore);
  drawAirport();
}else{
  $('#game-score').text(currentScore);
  }
}

function detectFloorCollision () {
  if (bluecifer.y > 350) {
    themeSong.pause();
    resetGame();
    bluecifer.y = 300;
  }
}

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('#game-over').css('visibility', 'hidden')) {
      bluecifer.moveUp();
      detectCeilingCollision();
    }
    else {
      resetGame();
    }
  } //end of if statement for space bar
  else if (key.which === 13) {
    themeSong.pause();
  } // end of if statement for enter key
}); //end of entire function

function detectCeilingCollision () {
  if (bluecifer.y < 0) {
    bluecifer.y = bluecifer.y + 20;
  }
}

function resetGame () {
  alert("Game over! Your score was " + scoreCounter);
  location.reload();
  $('#game-over').css('visibility', 'hidden');
  repeat();
}
<|endoftext|>


<commit_before>
'use strict';

var CryptService = require('./CryptService');
var RedisControl = require('./RedisControl');
var c_service;
var redis_key;

function Session(app_key, prefix){

    c_service = new CryptService(app_key);

    redis_key = prefix+":";

    function reload(self){
       (RedisControl.get(redis_key)).then(function(reply){
           self.data = reply;
       });
    }

   this.data = {};

   this.db = function(cookie, dbindex, port, ip){

       if(cookie === null || typeof cookie === "undefined"){
           throw new Error("argument 1 : expected valid cookie value");
       }

       if(typeof cookie === "string" && /^(?:[a-zA-Z0-9\=]+)$/.test(cookie)){ // test as base64 encoded value
           throw new Error("invalid cookie value");
       }

       if(typeof dbindex !== "number"){
          throw new TypeError('argument 1: expected type [number] found ['+typeof(dbindex)+']');
       }

       var dbindex = dbindex || 0; // default redis DB
       var port = port || 6379; // default redis port
       var ip = ip || '127.0.0.1'; // defult redis host
       var self = this;

      if(RedisControl.isConnected()){
          RedisControl.disconnect();
       }

       return RedisControl.connect(port, ip, dbindex).then(function(connect){

           if(redis_key.indexOf(":") === (redis_key.length - 1)){
               redis_key += c_service.decrypt(cookie);
           }

           reload(self);

      });

   };

   this.all = function(){
        var data = this.data, all = [];
        for(var i in data){
           if(data.hasOwnProperty(i)){
              all.push(data[i]);
           }
        }
        return all;
   }

   this.get = function(key){
      var data = this.data;
      return data[key];
   };

   this.put = function(key, value){
      var data = this.data;
      data[key] = value;
      this.data[key] = value;
      RedisControl.set(redis_key, data, reload.bind(null, this));
   }

   this.del = function(key){
      var data = this.data;
      var value = data[key];
      delete this.data[key];
      RedisControl.del(key);
      return value;
   }

}

module.exports = Session;
<commit_msg>Update index.js<commit_after>
'use strict';

var CryptService = require('./CryptService');
var RedisControl = require('./RedisControl');
var c_service;
var redis_key;

function Session(app_key, prefix){

    c_service = new CryptService(app_key);

    redis_key = prefix+":";

    function reload(self){
       (RedisControl.get(redis_key)).then(function(reply){
           self.data = reply;
       });
    }

   this.data = {};

   this.db = function(cookie, dbindex, port, ip){

       if(cookie === null || typeof cookie === "undefined"){
           throw new Error("argument 1 : expected valid cookie value");
       }

       if(typeof cookie === "string" && /^(?:[a-zA-Z0-9\=]+)$/.test(cookie)){ // test as base64 encoded value
           throw new Error("invalid cookie value");
       }

       if(typeof dbindex !== "number"){
          throw new TypeError('argument 1: expected type [number] found ['+typeof(dbindex)+']');
       }

       var dbindex = dbindex || 0; // default redis DB
       var port = port || 6379; // default redis port
       var ip = ip || '127.0.0.1'; // defult redis host
       var self = this;

      if(RedisControl.isConnected()){
          RedisControl.disconnect();
       }

       return RedisControl.connect(port, ip, dbindex).then(function(connect){

           if(redis_key.indexOf(":") === (redis_key.length - 1)){
               redis_key += c_service.decrypt(cookie);
           }

           reload(self);

      });

   };

   this.all = function(){
        var data = this.data, all = [];
        for(var i in data){
           if(data.hasOwnProperty(i)){
              all.push(data[i]);
           }
        }
        return all;
   }

   this.get = function(key){
      var data = this.data;
      return data[key];
   };

   this.put = function(key, value){
      var data = this.data;
      data[key] = value;
      this.data[key] = value;
      RedisControl.set(redis_key, data, reload.bind(null, this));
   }

   this.poof = function(key){
      var data = this.data;
      var value = data[key];
      delete this.data[key];
      RedisControl.del(key);
      return value;
   }

}

module.exports = Session;
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	chmod:              require('./chmod'),
	copy:               require('./copy'),
	descriptorsHandler: require('./descriptors-handler'),
	isIgnored:          require('./is-ignored'),
	lchmod:             require('./lchmod'),
	lstat:              require('./lstat'),
	mkdir:              require('./mkdir'),
	readFile:           require('./read-file'),
	readdir:            require('./readdir'),
	rmdir:              require('./rmdir'),
	stat:               require('./stat'),
	typeByStats:        require('./type-by-stats'),
	unlink:             require('./unlink'),
	watch:              require('./watch'),
	watchPath:          require('./watch-path'),
	writeFile:          require('./write-file')
};
<commit_msg>Add `rename` to index<commit_after>'use strict';

module.exports = {
	chmod:              require('./chmod'),
	copy:               require('./copy'),
	descriptorsHandler: require('./descriptors-handler'),
	isIgnored:          require('./is-ignored'),
	lchmod:             require('./lchmod'),
	lstat:              require('./lstat'),
	mkdir:              require('./mkdir'),
	readFile:           require('./read-file'),
	readdir:            require('./readdir'),
	rename:             require('./rename'),
	rmdir:              require('./rmdir'),
	stat:               require('./stat'),
	typeByStats:        require('./type-by-stats'),
	unlink:             require('./unlink'),
	watch:              require('./watch'),
	watchPath:          require('./watch-path'),
	writeFile:          require('./write-file')
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var alias = require('alias');
var convertDates = require('convert-dates');
var integration = require('analytics.js-integration');
var md5 = require('./md5.js');

/**
 * Expose `Boomtrain` integration.
 */

var Boomtrain = module.exports = integration('Boomtrain')
  .global('_bt')
  .option('apiKey', '')
  .tag('<script src="https://cdn.boomtrain.com/analyticstrain/{{ apiKey }}/analyticstrain.min.js"></script>');

/**
 * Initialize.
 *
 *
 *
 * @api public
 */

Boomtrain.prototype.initialize = function() {
  window._bt = window._bt || [];
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

Boomtrain.prototype.loaded = function() {
  return !!(window._bt && window._bt.push !== Array.prototype.push);
};

/**
 * Identify.
 *
 *
 *
 * @api public
 * @param {Identify} identify
 */

Boomtrain.prototype.identify = function(identify) {
  if (!identify.userId()) return this.debug('user id required');
  var traits = identify.traits({ createdAt: 'created' });
  traits = alias(traits, { created: 'created_at' });
  traits = convertDates(traits, convertDate);
  window._bt.identify(traits);
  window.console.log('id:' + window._bt.getCurrentId());
  window.console.log('app:' + window._bt.getApp());
};

/**
 * Page.
 *
 *
 *
 * @api public
 * @param {Page} page
 */

Boomtrain.prototype.page = function(page) {
  var properties = page.properties();
  properties.model = getModel();
  properties.id = md5(page.properties().url);
  window._bt.track('viewed', { model: properties.model, id: properties.id});
  window.console.log('Page: ' + page.name());
  window.console.log('Page props: ' + JSON.stringify(properties));
};

/**
 * Track.
 *
 *
 *
 * @api public
 * @param {Track} track
 */

Boomtrain.prototype.track = function(track) {
  var properties = track.properties();
  window._bt.track(track.event(), properties);
  window.console.log('Tracked: ' + track.event());
  window.console.log('properties: ' + JSON.stringify(track.properties()));
};

/**
 * Convert a date to the format Boomtrain supports.
 *
 * @api private
 * @param {Date} date
 * @return {number}
 */

function convertDate(date) {
  return Math.floor(date.getTime() / 1000);
}

/**
 * Get model of page, stored under meta-tag with property "og:type"
 *
 * @api private
 * @param
 * @return {string}
 */

function getModel(){
  var elements = window.document.getElementsByTagName('meta');
  var data = {};
  var pattern = 'og:';
  var key = 'property';
  for (var i = elements.length - 1; i >= 0; i--) {
    var property = elements[i].getAttribute && elements[i].getAttribute(key);
    if (property && property.match(pattern)) {
      data[property.replace(pattern, '')] = elements[i].getAttribute('content');
    }
  }
  return data.type;
}
<commit_msg>removing console.log()<commit_after>
/**
 * Module dependencies.
 */

var alias = require('alias');
var convertDates = require('convert-dates');
var integration = require('analytics.js-integration');
var md5 = require('./md5.js');

/**
 * Expose `Boomtrain` integration.
 */

var Boomtrain = module.exports = integration('Boomtrain')
  .global('_bt')
  .option('apiKey', '')
  .tag('<script src="https://cdn.boomtrain.com/analyticstrain/{{ apiKey }}/analyticstrain.min.js"></script>');

/**
 * Initialize.
 *
 *
 *
 * @api public
 */

Boomtrain.prototype.initialize = function() {
  window._bt = window._bt || [];
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

Boomtrain.prototype.loaded = function() {
  return !!(window._bt && window._bt.push !== Array.prototype.push);
};

/**
 * Identify.
 *
 *
 *
 * @api public
 * @param {Identify} identify
 */

Boomtrain.prototype.identify = function(identify) {
  if (!identify.userId()) return this.debug('user id required');
  var traits = identify.traits({ createdAt: 'created' });
  traits = alias(traits, { created: 'created_at' });
  traits = convertDates(traits, convertDate);
  window._bt.identify(traits);
};

/**
 * Page.
 *
 *
 *
 * @api public
 * @param {Page} page
 */

Boomtrain.prototype.page = function(page) {
  var properties = page.properties();
  properties.model = getModel();
  properties.id = md5(page.properties().url);
  window._bt.track('viewed', { model: properties.model, id: properties.id});
};

/**
 * Track.
 *
 *
 *
 * @api public
 * @param {Track} track
 */

Boomtrain.prototype.track = function(track) {
  var properties = track.properties();
  window._bt.track(track.event(), properties);
};

/**
 * Convert a date to the format Boomtrain supports.
 *
 * @api private
 * @param {Date} date
 * @return {number}
 */

function convertDate(date) {
  return Math.floor(date.getTime() / 1000);
}

/**
 * Get model of page, stored under meta-tag with property "og:type"
 *
 * @api private
 * @param
 * @return {string}
 */

function getModel(){
  var elements = window.document.getElementsByTagName('meta');
  var data = {};
  var pattern = 'og:';
  var key = 'property';
  for (var i = elements.length - 1; i >= 0; i--) {
    var property = elements[i].getAttribute && elements[i].getAttribute(key);
    if (property && property.match(pattern)) {
      data[property.replace(pattern, '')] = elements[i].getAttribute('content');
    }
  }
  return data.type;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var each = require('async').each;
var debug = require('debug')('metalsmith-mtime');

/**
 * Expose `plugin`.
 */

module.exports = plugin;

/**
 * A Metalsmith plugin that adds files mtimes to their metadata.
 *
 * @return {Function}
 */
function plugin() {
  return addAllMtimes;
}

function addAllMtimes(files, metalsmith, done) {

  // File system will be accessed for each element so iterate in parallel.
  each(Object.keys(files), getAddMtime, done);

  function getAddMtime(file, done) {
    fs.stat(path.join(metalsmith.source(), file), addMtime);

    function addMtime(err, stats) {
      if (err) {
        // Skip elements of `files` that don't point to existing files.
        // This can happen if some other Metalsmith plugin does something
        // strange with `files`.
        if (err.code === 'ENOENT') {
          debug('file %s not found', file);
          return done();
        }
        return done(err);
      }

      debug('mtime of file %s is %s', file, stats.mtime);
      files[file].mtime = stats.mtime;
      done();
    }
  }
}
<commit_msg>Add code documentation<commit_after>/**
 * Module dependencies.
 */

var fs = require('fs');
var path = require('path');
var each = require('async').each;
var debug = require('debug')('metalsmith-mtime');

/**
 * Expose `plugin`.
 */

module.exports = plugin;

/**
 * A Metalsmith plugin that adds files mtimes to their metadata.
 *
 * @return {Function}
 * @api public
 */

function plugin() {
  return addAllMtimes;
}

/**
 * Adds files mtimes to all corresponding objects in `files`.
 *
 * @param {Object} files
 * @param {Object} metalsmith
 * @param {Function} done
 * @api private
 */

function addAllMtimes(files, metalsmith, done) {

  var source = metalsmith.source();

  // File system will be accessed for each element so iterate in parallel.
  each(Object.keys(files), getAddMtime, done);

  /**
   * Gets mtime of given `file` and adds it to metadata.
   *
   * @param {String} file
   * @param {Function} done
   * @api private
   */

  function getAddMtime(file, done) {
    fs.stat(path.join(source, file), addMtime);

    /**
     * Adds `stats.mtime` of `file` to its metadata.
     *
     * @param {Error} err
     * @param {fs.Stats} stats
     * @api private
     */

    function addMtime(err, stats) {
      if (err) {
        // Skip elements of `files` that don't point to existing files.
        // This can happen if some other Metalsmith plugin does something
        // strange with `files`.
        if (err.code === 'ENOENT') {
          debug('file %s not found', file);
          return done();
        }
        return done(err);
      }

      debug('mtime of file %s is %s', file, stats.mtime);
      files[file].mtime = stats.mtime;
      done();
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @file Helper for libreOffice file processing
 * For more information about libreoffice :
 * http://www.libreoffice.org/
 */

var fs = require('fs');
var async = require('async');
var shellExec = require('child_process').exec;
var Anyfetch = require('anyfetch');
var async = require('async');

var image = require('./helpers/image.js');

var extensions = {
  '.xls': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.xlsx': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.ods': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.doc': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.docx': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.odt': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.rtf': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.ppt': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  },
  '.pptx': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  },
  '.odp': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  }
};

/**
 * Extract the content in html of the specified document
 *
 * @param {string} path Path of the specified file
 * @param {string} document to hydrate
 * @param {function} cb Callback, first parameter, is the error if any, then the processed data
 */
module.exports = function(path, document, cb) {

  async.waterfall([
    function(cb) {
      if(path) {
        var fileName = path.substr(path.lastIndexOf('/') + 1);
        if(fileName.lastIndexOf('.') !== -1) {
          fileName = fileName.substr(0, fileName.lastIndexOf('.'));
        }

        var options = [
          '--headless',
          '--norestore',
          '--nolockcheck'
        ];

        var file = path.substr(path.lastIndexOf('/') + 1);
        if (file.lastIndexOf(".") === -1) {
          return cb(new Error("No file extension"));
        }

        var fileExtension = file.substr(file.lastIndexOf('.')).toLowerCase();
        if (! extensions[fileExtension]){
          return cb(new Error("Unknown file extension"));
        }
        var converter = extensions[fileExtension].converter;
        var type = extensions[fileExtension].type;

        var outFile = '';
        if (type === "html"){
          outFile = fileName + '.html';
        }
        else  {
          outFile = fileName + '.pdf';
        }

        shellExec('loffice ' + options.join(' ') + ' --convert-to '+ type + converter + ' --outdir /tmp ' + path, function(err, stdout, stderr) {
          // err.code to 139 means accessibility errors, we don't really care
          if(err && err.code !== 139) {
            cb(new Error([err, stderr, stdout]));
          }

          cb(null, '/tmp/' + outFile, type);
        });
      }
    },
    function(outPath, type, cb) {
      fs.readFile(outPath, function(err, data) {
        if (type === 'html'){
          data = data.toString();
          // Cleanup datas
          // Retrieve CSS
          var css = data.match(/<style[\S\s]+?<\/style>/i)[0];
          // Remove HTML
          data = data.match(/<body[\S\s]+?>([\S\s]+)<\/body>/i)[1];
          // Reform valid partial document
          data = css + data;
        }
        cb(err, outPath, data, type);
      });
    },
    function(outPath, data, type, cb) {
      if (type === 'html') {
        document.datas.html = data.toString();
      }
      document.document_type = "document";
      cb(null, outPath ,type);
    },
    function(outPath, type, cb) {
      if (type === 'html'){
        image(document.datas.html, '/tmp', function(err, html) {
          document.datas.html = html;
          cb(err, outPath);
        });
      }
      else {
        var cluestr = new Anyfetch();
        cluestr.setAccessToken(document.access_token);

        var pdfFile = {};
        pdfFile.identifier = document.identifier;
        pdfFile.document_type = document.document_type;
        pdfFile.metadatas = document.metadatas || {};
        pdfFile.metadatas.mime_type = "application/pdf";
        // File to send
        var fileConfig = function(){
          return {
            file: fs.createReadStream(outPath),
            filename: document.fileName,
            knownLength: document.length
          };
        };

        cluestr.sendDocumentAndFile(pdfFile, fileConfig, function(err) {
          // Overwrite initial document, to finish properly hydration (without overwriting everything we just made)
          document = pdfFile;
          cb(err, outPath);
        });
      }
    },
    function(outPath, cb) {
      fs.unlink(outPath, function() {
        cb();
      });
    }
  ], function(err) {
    cb(err, document);
  });
};
<commit_msg>fix No file extention Error<commit_after>'use strict';

/**
 * @file Helper for libreOffice file processing
 * For more information about libreoffice :
 * http://www.libreoffice.org/
 */

var fs = require('fs');
var async = require('async');
var shellExec = require('child_process').exec;
var Anyfetch = require('anyfetch');
var async = require('async');

var image = require('./helpers/image.js');

var extensions = {
  '.xls': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.xlsx': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.ods': {
    converter :':"HTML (StarCalc)"',
    type: "html",
  },
  '.doc': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.docx': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.odt': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.rtf': {
    converter :':"HTML (StarWriter)"',
    type: "html",
  },
  '.ppt': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  },
  '.pptx': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  },
  '.odp': {
    converter :':"writer_web_pdf_Export"',
    type: "pdf",
  }
};

/**
 * Extract the content in html of the specified document
 *
 * @param {string} path Path of the specified file
 * @param {string} document to hydrate
 * @param {function} cb Callback, first parameter, is the error if any, then the processed data
 */
module.exports = function(path, document, cb) {

  async.waterfall([
    function(cb) {
      if(path) {
        var fileName = path.substr(path.lastIndexOf('/') + 1);
        if(fileName.lastIndexOf('.') !== -1) {
          fileName = fileName.substr(0, fileName.lastIndexOf('.'));
        }

        var options = [
          '--headless',
          '--norestore',
          '--nolockcheck'
        ];

        var file = document.metadatas.path.substr(document.metadatas.path.lastIndexOf('/') + 1);
        if (file.lastIndexOf(".") === -1) {
          return cb(new Error("No file extension"));
        }

        var fileExtension = file.substr(file.lastIndexOf('.')).toLowerCase();
        if (! extensions[fileExtension]){
          return cb(new Error("Unknown file extension"));
        }
        var converter = extensions[fileExtension].converter;
        var type = extensions[fileExtension].type;

        var outFile = '';
        if (type === "html"){
          outFile = fileName + '.html';
        }
        else  {
          outFile = fileName + '.pdf';
        }

        shellExec('loffice ' + options.join(' ') + ' --convert-to '+ type + converter + ' --outdir /tmp ' + path, function(err, stdout, stderr) {
          // err.code to 139 means accessibility errors, we don't really care
          if(err && err.code !== 139) {
            cb(new Error([err, stderr, stdout]));
          }

          cb(null, '/tmp/' + outFile, type);
        });
      }
    },
    function(outPath, type, cb) {
      fs.readFile(outPath, function(err, data) {
        if (type === 'html'){
          data = data.toString();
          // Cleanup datas
          // Retrieve CSS
          var css = data.match(/<style[\S\s]+?<\/style>/i)[0];
          // Remove HTML
          data = data.match(/<body[\S\s]+?>([\S\s]+)<\/body>/i)[1];
          // Reform valid partial document
          data = css + data;
        }
        cb(err, outPath, data, type);
      });
    },
    function(outPath, data, type, cb) {
      if (type === 'html') {
        document.datas.html = data.toString();
      }
      document.document_type = "document";
      cb(null, outPath ,type);
    },
    function(outPath, type, cb) {
      if (type === 'html'){
        image(document.datas.html, '/tmp', function(err, html) {
          document.datas.html = html;
          cb(err, outPath);
        });
      }
      else {
        var cluestr = new Anyfetch();
        cluestr.setAccessToken(document.access_token);

        var pdfFile = {};
        pdfFile.identifier = document.identifier;
        pdfFile.document_type = document.document_type;
        pdfFile.metadatas = document.metadatas || {};
        pdfFile.metadatas.mime_type = "application/pdf";
        // File to send
        var fileConfig = function(){
          return {
            file: fs.createReadStream(outPath),
            filename: document.fileName,
            knownLength: document.length
          };
        };

        cluestr.sendDocumentAndFile(pdfFile, fileConfig, function(err) {
          // Overwrite initial document, to finish properly hydration (without overwriting everything we just made)
          document = pdfFile;
          cb(err, outPath);
        });
      }
    },
    function(outPath, cb) {
      fs.unlink(outPath, function() {
        cb();
      });
    }
  ], function(err) {
    cb(err, document);
  });
};
<|endoftext|>


<commit_before>//
// HL7 Parser
//
// Author:    Evan Lucas
// Filename:  index.js
// Created:   2/6/14
// Copyright: Evan Lucas 2014
//

/**
 * Module dependencies
 */
var Transform = require('stream').Transform
  , util = require('util')
  , segment = require('./segment')()
  , Message = require('./message')

module.exports = Parser

/**
 * Constructor
 */
function Parser() {
  var opts = { objectMode: true }
  if (!(this instanceof Parser))
    return new Parser(opts)

  var self = this
  Transform.call(this, opts)

  this._messages = []
  this.current = []
}

util.inherits(Parser, Transform)

/**
 * Transform for parser
 *
 * **NOTE: The stream should have been pipe through `split()` already**
 *
 * @param {Buffer} data The segment as a buffer
 * @param {String} encoding The encoding of the buffer
 * @param {Function} cb function(err, res)
 * @api private
 */
Parser.prototype._transform = function(data, encoding, done) {
  var self = this
  var res
  try {
    res = segment.parse(data)
  }
  catch (e) {
    self.emit('error', e)
    res = null
  }
  if (res) {
    if (segment.isHeader(res) && this.current.length) {
      var message = new Message(this.current)
      this.emit('message', message)
      this._messages.push(message)
      this.current = [res]
    } else {
      this.current.push(res)
    }
    this.push(res)
  }
  done()
}

Parser.prototype._flush = function(done) {
  var self = this
  if (this.current.length) {
    var message = new Message(this.current)
    this.emit('message', message)
    this._messages.push(message)
    this.current = []
  }
  this.emit('messages', this._messages)
}
<commit_msg>Take into account changes in Message and Segment<commit_after>//
// HL7 Parser
//
// Author:    Evan Lucas
// Filename:  index.js
// Created:   2/6/14
// Copyright: Evan Lucas 2014
//

/**
 * Module dependencies
 */
var Transform = require('stream').Transform
  , util = require('util')
  , Segment = require('./segment')
  , Message = require('./message')
  , utils = require('./utils')

exports.Message = Message
exports.Segment = Segment
exports.Parser = Parser

/**
 * Constructor
 */
function Parser() {
  var opts = { objectMode: true }
  if (!(this instanceof Parser))
    return new Parser(opts)

  var self = this
  Transform.call(this, opts)

  this._messages = []
  this.current = null
}

util.inherits(Parser, Transform)

/**
 * Transform for parser
 *
 * **NOTE: The stream should have been pipe through `split()` already**
 *
 * @param {Buffer} data The segment as a buffer
 * @param {String} encoding The encoding of the buffer
 * @param {Function} cb function(err, res)
 * @api private
 */
Parser.prototype._transform = function(data, encoding, done) {
  var self = this
  var segment
  try {
    if (this.current) {
      segment = new Segment(data, this.current.delimiters())
    } else {
      segment = new Segment(data)
    }
  }
  catch (e) {
    self.emit('error', e)
    segment = null
  }
  if (segment) {
    var isHeader = utils.segmentIsHeader(segment)
    if (isHeader && this.current) {
      var message = new Message()
      message.addSegment(segment)
      this.emit('message', message)
      this._messages.push(message)
      this.current = message
    } else if (isHeader && !this.current) {
      this.current = new Message()
      this.current.addSegment(segment)
    } else {
      this.current.addSegment(segment)
    }
    this.push(segment)
  }
  done()
}

Parser.prototype._flush = function(done) {
  var self = this
  if (this.current) {
    var message = new Message(this.current)
    this.emit('message', message)
    this._messages.push(message)
    this.current = null
  }
  this.emit('messages', this._messages)
}
<|endoftext|>


<commit_before>'use strict';

const precompile = require('@glimmer/compiler').precompile;
const Minimatch = require('minimatch').Minimatch;
const getConfig = require('./get-config');
const stripBom = require('strip-bom');
const chalk = require('chalk');

const TransformDotComponentInvocation = require('./plugins/transform-dot-component-invocation');

const WARNING_SEVERITY = 1;
const ERROR_SEVERITY = 2;

class Linter {
  constructor(_options) {
    let options = _options || {};

    this.options = options;
    this.console = options.console || console;

    this.loadConfig();
    this.constructor = Linter;
  }

  loadConfig() {
    this.config = getConfig(this.options);
  }

  _defaultSeverityForRule(ruleName, pendingStatus) {
    if (typeof pendingStatus === 'boolean') {
      return pendingStatus ? WARNING_SEVERITY : ERROR_SEVERITY;
    } else if (pendingStatus.only){
      if (pendingStatus.only.indexOf(ruleName) > -1) {
        return WARNING_SEVERITY;
      } else {
        return ERROR_SEVERITY;
      }
    }

    return 2;
  }

  buildASTPlugins(config) {
    let results = config.results;

    function addToResults(result) {
      results.push(result);
    }

    let rules = this.config.loadedRules;
    let astPlugins = [TransformDotComponentInvocation];

    for (let pluginName in rules) {

      let Plugin = rules[pluginName];
      let plugin = new Plugin({
        name: pluginName,
        config: this.config.rules[pluginName],
        console: this.console,
        log: addToResults,
        defaultSeverity: this._defaultSeverityForRule(pluginName, config.pending)
      });

      astPlugins.push(env => {
        plugin.templateEnvironmentData = env;

        let visitor = plugin.getVisitor();

        return {
          name: pluginName,
          visitor
        };
      });
    }

    return astPlugins;
  }

  statusForModule(type, moduleId) {
    let list = this.config[type];
    if (!list) { return false; }

    for (let i = 0; i < list.length; i++) {
      let item = list[i];

      if (item instanceof Minimatch && item.match(moduleId)) {
        return true;
      } else if (typeof item === 'string' && moduleId === item) {
        return true;
      } else if (item.moduleId === moduleId){
        return item;
      }
    }

    return false;
  }

  verify(options) {
    let messages = [];
    let pendingStatus = this.statusForModule('pending', options.moduleId);
    let shouldIgnore = this.statusForModule('ignore', options.moduleId);

    if (shouldIgnore) {
      return messages;
    }

    let pluginConfig = {
      results: messages,
      pending: pendingStatus
    };

    try {
      precompile(stripBom(options.source), {
        moduleName: options.moduleId,
        rawSource: stripBom(options.source),
        plugins: {
          ast: this.buildASTPlugins(pluginConfig)
        }
      });
    } catch (error) {
      messages.push({
        fatal: true,
        moduleId: options.moduleId,
        message: error.message,
        source: error.stack,
        severity: 2
      });
    }

    if (pendingStatus && messages.length === 0) {
      messages.push({
        message: `Pending module (\`${options.moduleId}\`) passes all rules. Please remove \`${options.moduleId}\` from pending list.`,
        moduleId: options.moduleId,
        severity: 2
      });
    }

    return messages;
  }

  logLintingError(name, moduleName, message) {
    this._messages.push({
      rule: name,
      moduleId: moduleName,
      message
    });

    this.console.log(message);
  }

  static errorsToMessages(filePath, errors, options) {
    errors = errors || [];
    options = options || {
      verbose: false
    };

    if (errors.length === 0) {
      return '';
    }

    let errorsMessages = errors.map((error) => this._formatError(error, options)).join('\n');

    return `${chalk.underline(filePath)}\n${errorsMessages}\n`;
  }

  static _formatError(error, options) {
    let message = '';

    let line = error.line === undefined ? '-' : error.line;
    let column = error.column === undefined ? '-' : error.column;

    message += chalk.dim(`  ${line}:${column}`);

    if (error.severity === WARNING_SEVERITY) {
      message += `  ${chalk.yellow('warning')}`;
    } else {
      message += `  ${chalk.red('error')}`;
    }

    message += `  ${error.message}  ${chalk.dim(error.rule)}`;

    if (options.verbose) {
      message += `\n${error.source}`;
    }

    return message;
  }
}

module.exports = Linter;
module.exports.Rule = require('./rules/base');
module.exports.ASTHelpers = require('./helpers/ast-node-info');
<commit_msg>Add location information to fatal errors.<commit_after>'use strict';

const precompile = require('@glimmer/compiler').precompile;
const Minimatch = require('minimatch').Minimatch;
const getConfig = require('./get-config');
const stripBom = require('strip-bom');
const chalk = require('chalk');

const TransformDotComponentInvocation = require('./plugins/transform-dot-component-invocation');

const WARNING_SEVERITY = 1;
const ERROR_SEVERITY = 2;

class Linter {
  constructor(_options) {
    let options = _options || {};

    this.options = options;
    this.console = options.console || console;

    this.loadConfig();
    this.constructor = Linter;
  }

  loadConfig() {
    this.config = getConfig(this.options);
  }

  _defaultSeverityForRule(ruleName, pendingStatus) {
    if (typeof pendingStatus === 'boolean') {
      return pendingStatus ? WARNING_SEVERITY : ERROR_SEVERITY;
    } else if (pendingStatus.only){
      if (pendingStatus.only.indexOf(ruleName) > -1) {
        return WARNING_SEVERITY;
      } else {
        return ERROR_SEVERITY;
      }
    }

    return 2;
  }

  buildASTPlugins(config) {
    let results = config.results;

    function addToResults(result) {
      results.push(result);
    }

    let rules = this.config.loadedRules;
    let astPlugins = [TransformDotComponentInvocation];

    for (let pluginName in rules) {

      let Plugin = rules[pluginName];
      let plugin = new Plugin({
        name: pluginName,
        config: this.config.rules[pluginName],
        console: this.console,
        log: addToResults,
        defaultSeverity: this._defaultSeverityForRule(pluginName, config.pending)
      });

      astPlugins.push(env => {
        plugin.templateEnvironmentData = env;

        let visitor = plugin.getVisitor();

        return {
          name: pluginName,
          visitor
        };
      });
    }

    return astPlugins;
  }

  statusForModule(type, moduleId) {
    let list = this.config[type];
    if (!list) { return false; }

    for (let i = 0; i < list.length; i++) {
      let item = list[i];

      if (item instanceof Minimatch && item.match(moduleId)) {
        return true;
      } else if (typeof item === 'string' && moduleId === item) {
        return true;
      } else if (item.moduleId === moduleId){
        return item;
      }
    }

    return false;
  }

  verify(options) {
    let messages = [];
    let pendingStatus = this.statusForModule('pending', options.moduleId);
    let shouldIgnore = this.statusForModule('ignore', options.moduleId);

    if (shouldIgnore) {
      return messages;
    }

    let pluginConfig = {
      results: messages,
      pending: pendingStatus
    };

    try {
      precompile(stripBom(options.source), {
        moduleName: options.moduleId,
        rawSource: stripBom(options.source),
        plugins: {
          ast: this.buildASTPlugins(pluginConfig)
        }
      });
    } catch (error) {
      let message = {
        fatal: true,
        moduleId: options.moduleId,
        message: error.message,
        source: error.stack,
        severity: 2
      };

      if (error.location) {
        message.column = error.location.start.column;
        message.line = error.location.start.line;
      }

      messages.push(message);
    }

    if (pendingStatus && messages.length === 0) {
      messages.push({
        message: `Pending module (\`${options.moduleId}\`) passes all rules. Please remove \`${options.moduleId}\` from pending list.`,
        moduleId: options.moduleId,
        severity: 2
      });
    }

    return messages;
  }

  logLintingError(name, moduleName, message) {
    this._messages.push({
      rule: name,
      moduleId: moduleName,
      message
    });

    this.console.log(message);
  }

  static errorsToMessages(filePath, errors, options) {
    errors = errors || [];
    options = options || {
      verbose: false
    };

    if (errors.length === 0) {
      return '';
    }

    let errorsMessages = errors.map((error) => this._formatError(error, options)).join('\n');

    return `${chalk.underline(filePath)}\n${errorsMessages}\n`;
  }

  static _formatError(error, options) {
    let message = '';

    let line = error.line === undefined ? '-' : error.line;
    let column = error.column === undefined ? '-' : error.column;

    message += chalk.dim(`  ${line}:${column}`);

    if (error.severity === WARNING_SEVERITY) {
      message += `  ${chalk.yellow('warning')}`;
    } else {
      message += `  ${chalk.red('error')}`;
    }

    message += `  ${error.message}  ${chalk.dim(error.rule)}`;

    if (options.verbose) {
      message += `\n${error.source}`;
    }

    return message;
  }
}

module.exports = Linter;
module.exports.Rule = require('./rules/base');
module.exports.ASTHelpers = require('./helpers/ast-node-info');
<|endoftext|>


<commit_before>var tsort         = require('tsort'),
	_             = require('lodash'),
	AliasResolver = require('./aliases'),
	UA            = require('./UA'),
	sources       = require('./sources');

// Polyfill String.prototype.startsWith
if (!String.prototype.startsWith) {
	require('../polyfills/String.prototype.startsWith/polyfill');
}

require('es6-promise').polyfill();

// Load additional useragent features: primarily to use: agent.satisfies to
// test a browser version against a semver string
require('useragent/features');

"use strict";

function getAllPolyfills() {
	return sources.latest.listPolyfills();
}

function getOptions(opts) {
	return _.extend({
		uaString: '',
		minify: true,
		unknown: 'ignore',
		features: {},
		libVersion: 'latest'
	}, opts);
}

/**
 * Given a set of features that should be polyfilled in 'options.features' (with flags i.e. `{<featurename>: {flags:[<flaglist>]}, ...}`), determine which have a configuration valid for the given options.uaString, and return a set of canonical (unaliased) features (with flags) and polyfill variants.
 *
 * @return array, canonicalised features filtered for UA
 */
function getPolyfills(options) {
	var ua, features, sourceslib;

	options = getOptions(options);

	features = options.features;
	sourceslib = sources.getCollection(options.libVersion);
	ua = new UA(options.uaString);

	var aliasResolver = new AliasResolver([
		function aliasFromConfig(featureName) {
			return sourceslib.getConfigAliases(featureName);
		},
		function aliasAll(featureName) {
			if (featureName === 'all') {
				return sourceslib.listPolyfills();
			}
		}
	]);

	features = aliasResolver.resolve(features);

	function chooseVariant(featureName, feature) {
		if (!feature || feature.polyfillVariant !== undefined) return;
		var polyfill = sourceslib.getPolyfill(featureName);
		if (polyfill) {
			Object.keys(polyfill.variants).forEach(function(variantName) {
				var v = polyfill.variants[variantName];
				if (v.browsers && v.browsers[ua.getFamily()] && ua.satisfies(v.browsers[ua.getFamily()])) {
					feature.polyfillVariant = variantName;
					return false;
				}
			});
			if (!feature.polyfillVariant && feature.flags.indexOf('always') !== -1 && polyfill.variants['default']) {
				feature.polyfillVariant = 'default';
			}
			if (!feature.polyfillVariant && (options.unknown === 'polyfill' && ua.isUnknown())) {
				feature.polyfillVariant = 'default';
			}
			if (feature.polyfillVariant) {
				if (polyfill.variants[feature.polyfillVariant].dependencies) {
					polyfill.variants[feature.polyfillVariant].dependencies.forEach(function(dep) {
						if (!features[dep]) {
							features[dep] = {flags:feature.flags, aliasOf: [featureName]};
						} else if (!features[dep].aliasOf) {
							features[dep].aliasOf = [];
						}
						if (features[dep].aliasOf.indexOf(featureName) == -1) {
							features[dep].aliasOf.push(featureName);
						}
						chooseVariant(dep, features[dep]);
					});
				}
				return;
			}
		}
		delete features[featureName];
	}

	// chooseVariant modifies the features object, so use forEach rather than map and disregard return value
	Object.keys(features).forEach(function(featureName) {
		chooseVariant(featureName, features[featureName]);
	});
	return features;
}

function getPolyfillString(options) {
	var ua, uaDebugName;
	var currentPolyfills = {};
	var features = [];
	var explainerComment = [];
	var sourceslib;

	options = getOptions(options);
	ua = new UA(options.uaString);
	uaDebugName = (ua.isUnknown() ? 'Unknown (using policy: '+options.unknown+')' : ua.getFamily() + '/' + ua.getVersion());

	try {
		sourceslib = sources.getCollection(options.libVersion);
	} catch(e) {
		if (e.message == 'No matching version found') {
			sourceslib = null;
		} else {
			throw e;
		}
	}

	if (!ua.meetsBaseline() && !(ua.isUnknown() && options.unknown === 'polyfill')) {
		explainerComment = ['Unsupported UA detected: ' + uaDebugName];
		if (ua.getBaseline()) {
			explainerComment.push('Version range for polyfill support in this family is: ' + ua.getBaseline());
		}

	} else if (!sourceslib) {
		explainerComment = [
			'Cannot find a polyfill collection to satisfy version: '+options.libVersion+'.',
			'Available versions: '+sources.listVersions()
		];

	} else {
		if (options.minify) {
			explainerComment = ['Rerun without minification for verbose metadata'];
		} else  {
			explainerComment = [
				'For detailed credits and licence information see http://github.com/financial-times/polyfill-service.',
				'',
				'UA detected: ' + uaDebugName,
				'Features requested: ' + Object.keys(options.features),
				'Library version: ' + sourceslib.getVersion(),
				''
			]
		}
		features = getPolyfills(options);
	}

	var warnings = {unknown:[], nopolyfill:[]};
	var graph = tsort();

	Object.keys(features).forEach(function(featureName) {
		var feature = features[featureName];

		if (!sourceslib.getPolyfill(featureName)) {
			warnings.unknown.push(' - '+featureName);
		} else if (!feature.polyfillVariant) {
			warnings.nopolyfill.push(' - '+featureName);
		} else {

			graph.add(featureName);
			var polyfill = sourceslib.getPolyfill(featureName).variants[feature.polyfillVariant];
			var srcKey = (options.minify ? 'min':'raw') + 'Source';

			feature.polyfillOutput = polyfill[srcKey];

			if (feature.flags.indexOf('gated') !== -1 && polyfill.detectSource) {
				feature.polyfillOutput = "if (!(" + polyfill.detectSource + ")) {" + feature.polyfillOutput + "}\n\n";
			}

			if (polyfill.dependencies) {
				for (var i = 0; i < polyfill.dependencies.length; i++) {
					if (features[polyfill.dependencies[i]]) {
						graph.add(polyfill.dependencies[i], featureName);
					}
				}
			}
			feature.comment = '- ' + featureName + (feature.polyfillVariant !== 'default' ? '-'+feature.polyfillVariant:'') + ', License: ' + (polyfill.license || 'CC0')  + ' ' + ((feature.aliasOf && feature.aliasOf.length) ? ' (required by "' + feature.aliasOf.join('", "') + '")' : '');
		}
	});

	// Using the graph order, build the completed polyfill bundle
	var builtPolyfillString = '';
	graph.sort().forEach(function(featureName) {
		builtPolyfillString += features[featureName].polyfillOutput || '';
		if (!options.minify && features[featureName].comment) explainerComment.push(features[featureName].comment);
	});

	builtPolyfillString = "(function() {\n"+builtPolyfillString+"})();";

	if (warnings.unknown.length && !options.minify) {
		explainerComment = explainerComment.concat(
			'',
			'These features were not recognised:',
			warnings.unknown
		);
	}

	if (warnings.nopolyfill.length && !options.minify) {
		explainerComment = explainerComment.concat(
			'',
			'These features have no polyfill suitable for '+ua.getFamily() + '/' + ua.getVersion() + ':',
			warnings.nopolyfill
		);
	}

	return '/* ' + explainerComment.join('\n * ') + ' */\n\n' + builtPolyfillString;
}

module.exports = {
	getPolyfills: getPolyfills,
	getAllPolyfills: getAllPolyfills,
	getPolyfillString: getPolyfillString,
	normalizeUserAgent: UA.normalize
};
<commit_msg>Don't add line breaks to minified output<commit_after>var tsort         = require('tsort'),
	_             = require('lodash'),
	AliasResolver = require('./aliases'),
	UA            = require('./UA'),
	sources       = require('./sources');

// Polyfill String.prototype.startsWith
if (!String.prototype.startsWith) {
	require('../polyfills/String.prototype.startsWith/polyfill');
}

require('es6-promise').polyfill();

// Load additional useragent features: primarily to use: agent.satisfies to
// test a browser version against a semver string
require('useragent/features');

"use strict";

function getAllPolyfills() {
	return sources.latest.listPolyfills();
}

function getOptions(opts) {
	return _.extend({
		uaString: '',
		minify: true,
		unknown: 'ignore',
		features: {},
		libVersion: 'latest'
	}, opts);
}

/**
 * Given a set of features that should be polyfilled in 'options.features' (with flags i.e. `{<featurename>: {flags:[<flaglist>]}, ...}`), determine which have a configuration valid for the given options.uaString, and return a set of canonical (unaliased) features (with flags) and polyfill variants.
 *
 * @return array, canonicalised features filtered for UA
 */
function getPolyfills(options) {
	var ua, features, sourceslib;

	options = getOptions(options);

	features = options.features;
	sourceslib = sources.getCollection(options.libVersion);
	ua = new UA(options.uaString);

	var aliasResolver = new AliasResolver([
		function aliasFromConfig(featureName) {
			return sourceslib.getConfigAliases(featureName);
		},
		function aliasAll(featureName) {
			if (featureName === 'all') {
				return sourceslib.listPolyfills();
			}
		}
	]);

	features = aliasResolver.resolve(features);

	function chooseVariant(featureName, feature) {
		if (!feature || feature.polyfillVariant !== undefined) return;
		var polyfill = sourceslib.getPolyfill(featureName);
		if (polyfill) {
			Object.keys(polyfill.variants).forEach(function(variantName) {
				var v = polyfill.variants[variantName];
				if (v.browsers && v.browsers[ua.getFamily()] && ua.satisfies(v.browsers[ua.getFamily()])) {
					feature.polyfillVariant = variantName;
					return false;
				}
			});
			if (!feature.polyfillVariant && feature.flags.indexOf('always') !== -1 && polyfill.variants['default']) {
				feature.polyfillVariant = 'default';
			}
			if (!feature.polyfillVariant && (options.unknown === 'polyfill' && ua.isUnknown())) {
				feature.polyfillVariant = 'default';
			}
			if (feature.polyfillVariant) {
				if (polyfill.variants[feature.polyfillVariant].dependencies) {
					polyfill.variants[feature.polyfillVariant].dependencies.forEach(function(dep) {
						if (!features[dep]) {
							features[dep] = {flags:feature.flags, aliasOf: [featureName]};
						} else if (!features[dep].aliasOf) {
							features[dep].aliasOf = [];
						}
						if (features[dep].aliasOf.indexOf(featureName) == -1) {
							features[dep].aliasOf.push(featureName);
						}
						chooseVariant(dep, features[dep]);
					});
				}
				return;
			}
		}
		delete features[featureName];
	}

	// chooseVariant modifies the features object, so use forEach rather than map and disregard return value
	Object.keys(features).forEach(function(featureName) {
		chooseVariant(featureName, features[featureName]);
	});
	return features;
}

function getPolyfillString(options) {
	var ua, uaDebugName;
	var currentPolyfills = {};
	var features = [];
	var explainerComment = [];
	var sourceslib;

	options = getOptions(options);
	ua = new UA(options.uaString);
	uaDebugName = (ua.isUnknown() ? 'Unknown (using policy: '+options.unknown+')' : ua.getFamily() + '/' + ua.getVersion());

	try {
		sourceslib = sources.getCollection(options.libVersion);
	} catch(e) {
		if (e.message == 'No matching version found') {
			sourceslib = null;
		} else {
			throw e;
		}
	}

	if (!ua.meetsBaseline() && !(ua.isUnknown() && options.unknown === 'polyfill')) {
		explainerComment = ['Unsupported UA detected: ' + uaDebugName];
		if (ua.getBaseline()) {
			explainerComment.push('Version range for polyfill support in this family is: ' + ua.getBaseline());
		}

	} else if (!sourceslib) {
		explainerComment = [
			'Cannot find a polyfill collection to satisfy version: '+options.libVersion+'.',
			'Available versions: '+sources.listVersions()
		];

	} else {
		if (options.minify) {
			explainerComment = ['Rerun without minification for verbose metadata'];
		} else  {
			explainerComment = [
				'For detailed credits and licence information see http://github.com/financial-times/polyfill-service.',
				'',
				'UA detected: ' + uaDebugName,
				'Features requested: ' + Object.keys(options.features),
				'Library version: ' + sourceslib.getVersion(),
				''
			]
		}
		features = getPolyfills(options);
	}

	var warnings = {unknown:[], nopolyfill:[]};
	var graph = tsort();
	var lf = options.minify ? '' : '\n';

	Object.keys(features).forEach(function(featureName) {
		var feature = features[featureName];

		if (!sourceslib.getPolyfill(featureName)) {
			warnings.unknown.push(' - '+featureName);
		} else if (!feature.polyfillVariant) {
			warnings.nopolyfill.push(' - '+featureName);
		} else {

			graph.add(featureName);
			var polyfill = sourceslib.getPolyfill(featureName).variants[feature.polyfillVariant];
			var srcKey = (options.minify ? 'min':'raw') + 'Source';

			feature.polyfillOutput = polyfill[srcKey];

			if (feature.flags.indexOf('gated') !== -1 && polyfill.detectSource) {
				feature.polyfillOutput = "if (!(" + polyfill.detectSource + ")) {" + lf + feature.polyfillOutput + "}" + lf + lf;
			}

			if (polyfill.dependencies) {
				for (var i = 0; i < polyfill.dependencies.length; i++) {
					if (features[polyfill.dependencies[i]]) {
						graph.add(polyfill.dependencies[i], featureName);
					}
				}
			}
			feature.comment = '- ' + featureName + (feature.polyfillVariant !== 'default' ? '-'+feature.polyfillVariant:'') + ', License: ' + (polyfill.license || 'CC0')  + ' ' + ((feature.aliasOf && feature.aliasOf.length) ? ' (required by "' + feature.aliasOf.join('", "') + '")' : '');
		}
	});

	// Using the graph order, build the completed polyfill bundle
	var builtPolyfillString = '';
	graph.sort().forEach(function(featureName) {
		builtPolyfillString += features[featureName].polyfillOutput || '';
		if (!options.minify && features[featureName].comment) explainerComment.push(features[featureName].comment);
	});

	// Outer closure hides private features from global scope
	builtPolyfillString = "(function() {" + lf + builtPolyfillString + lf + "})();";

	if (warnings.unknown.length && !options.minify) {
		explainerComment = explainerComment.concat(
			'',
			'These features were not recognised:',
			warnings.unknown
		);
	}

	if (warnings.nopolyfill.length && !options.minify) {
		explainerComment = explainerComment.concat(
			'',
			'These features have no polyfill suitable for '+ua.getFamily() + '/' + ua.getVersion() + ':',
			warnings.nopolyfill
		);
	}

	return '/* ' + explainerComment.join('\n * ') + ' */\n\n' + builtPolyfillString;
}

module.exports = {
	getPolyfills: getPolyfills,
	getAllPolyfills: getAllPolyfills,
	getPolyfillString: getPolyfillString,
	normalizeUserAgent: UA.normalize
};
<|endoftext|>


<commit_before>'use strict';

/**
 * @file Helper for iptc/exif metadata processing
 */

var ex = require('exiv2');

var hydrationError = require('anyfetch-hydrater').hydrationError;

/**
 * Extract the metadata of the specified image file
 *
 * @param {string} path Path of the specified file
 * @param {function} cb Callback, first parameter, is the error if any, then the processed data
 */
module.exports = function(path, document, changes, finalCb) {
  ex.getImageTags(path, function(err, tags) {
    if(err) {
      return finalCb(new hydrationError(err.toString()));
    }
    if(!tags) {
      return finalCb(null, changes);
    }

    var selection = {
      author: 'Iptc.Application2.Byline',
      description: 'Iptc.Application2.Caption',
      keywords: 'Xmp.dc.subject'
    };

    for(var key in selection) {
      if(tags.hasOwnProperty(selection[key])) {
        changes.metadata[key] = tags[selection[key]];
      }
    }

    finalCb(null, changes);
  });
};
<commit_msg>hydrationError => HydrationError<commit_after>'use strict';

/**
 * @file Helper for iptc/exif metadata processing
 */

var ex = require('exiv2');

var HydrationError = require('anyfetch-hydrater').HydrationError;

/**
 * Extract the metadata of the specified image file
 *
 * @param {string} path Path of the specified file
 * @param {function} cb Callback, first parameter, is the error if any, then the processed data
 */
module.exports = function(path, document, changes, finalCb) {
  ex.getImageTags(path, function(err, tags) {
    if(err) {
      return finalCb(new HydrationError(err.toString()));
    }
    if(!tags) {
      return finalCb(null, changes);
    }

    var selection = {
      author: 'Iptc.Application2.Byline',
      description: 'Iptc.Application2.Caption',
      keywords: 'Xmp.dc.subject'
    };

    for(var key in selection) {
      if(tags.hasOwnProperty(selection[key])) {
        changes.metadata[key] = tags[selection[key]];
      }
    }

    finalCb(null, changes);
  });
};
<|endoftext|>


<commit_before>"use strict";

var _request = require("request");

var _request2 = _interopRequireDefault(_request);

var _events = require("events");

var _util = require("util");

var _util2 = _interopRequireDefault(_util);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

//Config
var config = {
  hostname: "",
  port: 8384,
  apiKey: "",
  eventListener: false,
  constructor: function constructor(_ref) {
    var _ref$hostname = _ref.hostname;
    var hostname = _ref$hostname === undefined ? "localhost" : _ref$hostname;
    var _ref$port = _ref.port;
    var port = _ref$port === undefined ? 8384 : _ref$port;
    var _ref$apiKey = _ref.apiKey;
    var apiKey = _ref$apiKey === undefined ? "" : _ref$apiKey;
    var _ref$eventListener = _ref.eventListener;
    var eventListener = _ref$eventListener === undefined ? false : _ref$eventListener;
    var _ref$https = _ref.https;
    var https = _ref$https === undefined ? false : _ref$https;

    this.https = https;
    this.hostname = hostname;
    this.port = port;
    this.apiKey = apiKey;
    this.eventListener = eventListener;
  }
};

function req(_ref2, callback) {
  var _ref2$method = _ref2.method;
  var method = _ref2$method === undefined ? "system" : _ref2$method;
  var _ref2$endpoint = _ref2.endpoint;
  var endpoint = _ref2$endpoint === undefined ? "ping" : _ref2$endpoint;
  var _ref2$post = _ref2.post;
  var post = _ref2$post === undefined ? false : _ref2$post;
  var _ref2$body = _ref2.body;
  var body = _ref2$body === undefined ? "" : _ref2$body;
  var attr = _ref2.attr;

  attr = attr ? "?" + attr.map(function (item) {
    return item.key + "=" + encodeURI(item.val);
  }).join("&") : "";
  endpoint = endpoint ? "\/" + endpoint : "";
  var options = {
    method: post ? "POST" : "GET",
    url: (config.https ? 'https' : 'http') + "://" + config.hostname + ":" + config.port + "/rest/" + method + endpoint + attr,
    headers: { 'Content-Type': 'application/json', 'X-API-Key': config.apiKey },
    json: true,
    body: body,
    rejectUnauthorized: false
  };
  (0, _request2.default)(options, function (err, res, body) {
    if (!err && res.statusCode == 200) {
      callback(err, typeof body == "string" && body ? JSON.parse(body) : body);
    } else {
      callback(err || res.statusCode + ", " + body);
    }
  });
}
function callReq(options, cb) {
  if (cb) {
    req(options, cb);
  } else {
    return new Promise(function (resolve, reject) {
      req(options, function (err, res) {
        return !err ? resolve(res) : reject(err);
      });
    });
  }
}

function lowerCaseFirst(str) {
  return str.charAt(0).toLowerCase() + str.slice(1);
}
function Syncthing(options) {
  var _this = this;

  config.constructor(options);
  //Events
  if (config.eventListener) {
    (function () {
      _events.EventEmitter.call(_this);
      var iterator = function iterator(since) {
        var attr = [{ key: "since", val: since }];
        callReq({ method: "events", endpoint: false, attr: attr }).then(function (eventArr) {
          if (since != 0) {
            eventArr.forEach(function (e) {
              _this.emit(lowerCaseFirst(e.type), e.data);
            });
          }
          since = eventArr[eventArr.length - 1].id;
          setTimeout(function () {
            return iterator(since);
          }, 100);
        }).catch(function (err) {
          _this.emit("error", err);
        });
      };
      iterator(0);
    })();
  }
}
_util2.default.inherits(Syncthing, _events.EventEmitter);
Syncthing.prototype.system = {
  ping: function ping(cb) {
    return callReq({}, cb);
  },
  shutdown: function shutdown(cb) {
    return callReq({ endpoint: "shutdown", post: true }, cb);
  },
  restart: function restart(cb) {
    return callReq({ endpoint: "restart", post: true }, cb);
  },
  version: function version(cb) {
    return callReq({ endpoint: "version" }, cb);
  },
  status: function status(cb) {
    return callReq({ endpoint: "status" }, cb);
  },
  connections: function connections(cb) {
    return callReq({ endpoint: "connections" }, cb);
  },
  setConfig: function setConfig(body, cb) {
    return callReq({ endpoint: "config", post: true, body: body }, cb);
  },
  getConfig: function getConfig(cb) {
    return callReq({ endpoint: "config" }, cb);
  },
  debug: function debug(cb) {
    return callReq({ endpoint: "debug" }, cb);
  },
  getDiscovery: function getDiscovery(cb) {
    return callReq({ endpoint: "discovery" }, cb);
  },
  setDiscovery: function setDiscovery(dev, addr, cb) {
    var attr = [{ key: "device", val: dev }, { key: "addr", val: addr }];
    return callReq({ endpoint: "discovery", attr: attr, post: true }, cb);
  },
  errors: function errors(cb) {
    return callReq({ endpoint: "error" }, cb);
  },
  clearErrors: function clearErrors(cb) {
    return callReq({ endpoint: "error/clear", post: true }, cb);
  },
  logs: function logs(cb) {
    return callReq({ endpoint: "log" }, cb);
  },
  getUpgrade: function getUpgrade(cb) {
    return callReq({ endpoint: "upgrade" }, cb);
  },
  upgrade: function upgrade(cb) {
    return callReq({ endpoint: "upgrade", post: true }, cb);
  }
};
//DB
Syncthing.prototype.db = {
  scan: function scan(folder, subdir, cb) {
    var attr = [{ key: "folder", val: folder }];
    if (typeof subdir == "function") {
      cb = subdir;
      subdir = null;
    } else {
      attr.push({ key: "sub", val: subdir });
    }
    return callReq({ method: "db", endpoint: "scan", attr: attr, post: true }, cb);
  },
  status: function status(folder, cb) {
    return callReq({ method: "db", endpoint: "status" }, cb);
  },
  browse: function browse(folder) {
    var levels = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
    var subdir = arguments[2];
    var cb = arguments[3];

    var attr = [{ key: "folder", val: folder }, { key: "levels", val: levels }];
    if (typeof subdir == "function") {
      cb = subdir;
      subdir = null;
    } else if (typeof levels == "function") {
      cb = levels;
      levels = null;
      subdir = null;
    } else {
      attr.push({ key: "prefix", val: subdir });
    }
    return callReq({ method: "db", endpoint: "browse", attr: attr }, cb);
  },
  completion: function completion(device, folder, cb) {
    var attr = [{ key: "device", val: device }, { key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "completion", attr: attr }, cb);
  },
  file: function file(folder, _file, cb) {
    var attr = [{ key: "folder", val: folder }, { key: "file", val: _file }];
    return callReq({ method: "db", endpoint: "file", attr: attr }, cb);
  },
  getIgnores: function getIgnores(folder, cb) {
    var attr = [{ key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "ignores", attr: attr }, cb);
  },
  setIgnores: function setIgnores(folder, ignores, cb) {
    var attr = [{ key: "folder", val: folder }];
    if (typeof ignores == "function") {
      cb = ignores;
      ignores = null;
    } else {
      attr.push({ key: "ignores", val: ignores });
    }
    return callReq({ method: "db", endpoint: "ignores", post: true, attr: attr }, cb);
  },
  need: function need(folder, cb) {
    var attr = [{ key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "need", attr: attr }, cb);
  },
  prio: function prio(folder, file, cb) {
    var attr = [{ key: "folder", val: folder }, { key: "file", val: file }];
    return callReq({ method: "db", endpoint: "prio", post: true, attr: attr }, cb);
  }
};
Syncthing.prototype.stats = {
  devices: function devices(cb) {
    return callReq({ method: "stats", endpoint: "device" }, cb);
  },
  folders: function folders(cb) {
    return callReq({ method: "stats", endpoint: "folder" }, cb);
  }
}, Syncthing.prototype.misc = {
  deviceId: function deviceId(id, cb) {
    var attr = [{ key: "id", val: id }];
    return callReq({ method: "svc", endpoint: "deviceid", attr: attr }, cb);
  },
  lang: function lang(cb) {
    return callReq({ method: "svc", endpoint: "lang" }, cb);
  },
  report: function report(cb) {
    return callReq({ method: "svc", endpoint: "report" }, cb);
  }
};

module.exports = Syncthing;
<commit_msg>Fix db/status<commit_after>"use strict";

var _request = require("request");

var _request2 = _interopRequireDefault(_request);

var _events = require("events");

var _util = require("util");

var _util2 = _interopRequireDefault(_util);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

//Config
var config = {
  hostname: "",
  port: 8384,
  apiKey: "",
  eventListener: false,
  constructor: function constructor(_ref) {
    var _ref$hostname = _ref.hostname;
    var hostname = _ref$hostname === undefined ? "localhost" : _ref$hostname;
    var _ref$port = _ref.port;
    var port = _ref$port === undefined ? 8384 : _ref$port;
    var _ref$apiKey = _ref.apiKey;
    var apiKey = _ref$apiKey === undefined ? "" : _ref$apiKey;
    var _ref$eventListener = _ref.eventListener;
    var eventListener = _ref$eventListener === undefined ? false : _ref$eventListener;
    var _ref$https = _ref.https;
    var https = _ref$https === undefined ? false : _ref$https;

    this.https = https;
    this.hostname = hostname;
    this.port = port;
    this.apiKey = apiKey;
    this.eventListener = eventListener;
  }
};
function req(_ref2, callback) {
  var _ref2$method = _ref2.method;
  var method = _ref2$method === undefined ? "system" : _ref2$method;
  var _ref2$endpoint = _ref2.endpoint;
  var endpoint = _ref2$endpoint === undefined ? "ping" : _ref2$endpoint;
  var _ref2$post = _ref2.post;
  var post = _ref2$post === undefined ? false : _ref2$post;
  var _ref2$body = _ref2.body;
  var body = _ref2$body === undefined ? "" : _ref2$body;
  var attr = _ref2.attr;

  attr = attr ? "?" + attr.map(function (item) {
    return item.key + "=" + encodeURI(item.val);
  }).join("&") : "";
  endpoint = endpoint ? "\/" + endpoint : "";
  var options = {
    method: post ? "POST" : "GET",
    url: (config.https ? 'https' : 'http') + "://" + config.hostname + ":" + config.port + "/rest/" + method + endpoint + attr,
    headers: { 'Content-Type': 'application/json', 'X-API-Key': config.apiKey },
    json: true,
    body: body,
    rejectUnauthorized: false
  };
  (0, _request2.default)(options, function (err, res, body) {
    if (!err && res.statusCode == 200) {
      callback(err, typeof body == "string" && body ? JSON.parse(body) : body);
    } else {
      callback(err || res.statusCode + ", " + body);
    }
  });
}
function callReq(options, cb) {
  if (cb) {
    req(options, cb);
  } else {
    return new Promise(function (resolve, reject) {
      req(options, function (err, res) {
        return !err ? resolve(res) : reject(err);
      });
    });
  }
}

function lowerCaseFirst(str) {
  return str.charAt(0).toLowerCase() + str.slice(1);
}
function Syncthing(options) {
  var _this = this;

  config.constructor(options);
  //Events
  if (config.eventListener) {
    (function () {
      _events.EventEmitter.call(_this);
      var iterator = function iterator(since) {
        var attr = [{ key: "since", val: since }];
        callReq({ method: "events", endpoint: false, attr: attr }).then(function (eventArr) {
          if (since != 0) {
            eventArr.forEach(function (e) {
              _this.emit(lowerCaseFirst(e.type), e.data);
            });
          }
          since = eventArr[eventArr.length - 1].id;
          setTimeout(function () {
            return iterator(since);
          }, 100);
        }).catch(function (err) {
          _this.emit("error", err);
        });
      };
      iterator(0);
    })();
  }
}
_util2.default.inherits(Syncthing, _events.EventEmitter);
Syncthing.prototype.system = {
  ping: function ping(cb) {
    return callReq({}, cb);
  },
  shutdown: function shutdown(cb) {
    return callReq({ endpoint: "shutdown", post: true }, cb);
  },
  restart: function restart(cb) {
    return callReq({ endpoint: "restart", post: true }, cb);
  },
  version: function version(cb) {
    return callReq({ endpoint: "version" }, cb);
  },
  status: function status(cb) {
    return callReq({ endpoint: "status" }, cb);
  },
  connections: function connections(cb) {
    return callReq({ endpoint: "connections" }, cb);
  },
  setConfig: function setConfig(body, cb) {
    return callReq({ endpoint: "config", post: true, body: body }, cb);
  },
  getConfig: function getConfig(cb) {
    return callReq({ endpoint: "config" }, cb);
  },
  debug: function debug(cb) {
    return callReq({ endpoint: "debug" }, cb);
  },
  getDiscovery: function getDiscovery(cb) {
    return callReq({ endpoint: "discovery" }, cb);
  },
  setDiscovery: function setDiscovery(dev, addr, cb) {
    var attr = [{ key: "device", val: dev }, { key: "addr", val: addr }];
    return callReq({ endpoint: "discovery", attr: attr, post: true }, cb);
  },
  errors: function errors(cb) {
    return callReq({ endpoint: "error" }, cb);
  },
  clearErrors: function clearErrors(cb) {
    return callReq({ endpoint: "error/clear", post: true }, cb);
  },
  logs: function logs(cb) {
    return callReq({ endpoint: "log" }, cb);
  },
  getUpgrade: function getUpgrade(cb) {
    return callReq({ endpoint: "upgrade" }, cb);
  },
  upgrade: function upgrade(cb) {
    return callReq({ endpoint: "upgrade", post: true }, cb);
  }
};
//DB
Syncthing.prototype.db = {
  scan: function scan(folder, subdir, cb) {
    var attr = [{ key: "folder", val: folder }];
    if (typeof subdir == "function") {
      cb = subdir;
      subdir = null;
    } else {
      attr.push({ key: "sub", val: subdir });
    }
    return callReq({ method: "db", endpoint: "scan", attr: attr, post: true }, cb);
  },
  status: function status(folder, cb) {
    return callReq({ method: "db", endpoint: "status", attr: [{ key: "folder", val: folder }] }, cb);
  },
  browse: function browse(folder) {
    var levels = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
    var subdir = arguments[2];
    var cb = arguments[3];

    var attr = [{ key: "folder", val: folder }, { key: "levels", val: levels }];
    if (typeof subdir == "function") {
      cb = subdir;
      subdir = null;
    } else if (typeof levels == "function") {
      cb = levels;
      levels = null;
      subdir = null;
    } else {
      attr.push({ key: "prefix", val: subdir });
    }
    return callReq({ method: "db", endpoint: "browse", attr: attr }, cb);
  },
  completion: function completion(device, folder, cb) {
    var attr = [{ key: "device", val: device }, { key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "completion", attr: attr }, cb);
  },
  file: function file(folder, _file, cb) {
    var attr = [{ key: "folder", val: folder }, { key: "file", val: _file }];
    return callReq({ method: "db", endpoint: "file", attr: attr }, cb);
  },
  getIgnores: function getIgnores(folder, cb) {
    var attr = [{ key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "ignores", attr: attr }, cb);
  },
  setIgnores: function setIgnores(folder, ignores, cb) {
    var attr = [{ key: "folder", val: folder }];
    if (typeof ignores == "function") {
      cb = ignores;
      ignores = null;
    } else {
      attr.push({ key: "ignores", val: ignores });
    }
    return callReq({ method: "db", endpoint: "ignores", post: true, attr: attr }, cb);
  },
  need: function need(folder, cb) {
    var attr = [{ key: "folder", val: folder }];
    return callReq({ method: "db", endpoint: "need", attr: attr }, cb);
  },
  prio: function prio(folder, file, cb) {
    var attr = [{ key: "folder", val: folder }, { key: "file", val: file }];
    return callReq({ method: "db", endpoint: "prio", post: true, attr: attr }, cb);
  }
};
Syncthing.prototype.stats = {
  devices: function devices(cb) {
    return callReq({ method: "stats", endpoint: "device" }, cb);
  },
  folders: function folders(cb) {
    return callReq({ method: "stats", endpoint: "folder" }, cb);
  }
}, Syncthing.prototype.misc = {
  deviceId: function deviceId(id, cb) {
    var attr = [{ key: "id", val: id }];
    return callReq({ method: "svc", endpoint: "deviceid", attr: attr }, cb);
  },
  lang: function lang(cb) {
    return callReq({ method: "svc", endpoint: "lang" }, cb);
  },
  report: function report(cb) {
    return callReq({ method: "svc", endpoint: "report" }, cb);
  }
};

module.exports = Syncthing;
<|endoftext|>