<commit_before>'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var channels = {}

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message.resource.SlackTeamName);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})
var app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "https://cdn3.iconfinder.com/data/icons/basicolor-arrows-checks/24/154_check_ok_sticker_success-512.png" : "http://www.clker.com/cliparts/H/Z/0/R/f/S/warning-icon-hi.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
            		   {
            		      "text":"1 - Test",
            		      "value":1
            		   },
            		   {
        			     "text":"7 - Digital Marketing",
        			     "value":7
        			   },
        			   {
        			      "text":"40 - Legal",
        			      "value":40
        			   },
        			   {
        			      "text":"43 - Innovation & Startups",
        			      "value":43
        			   },
        			   {
        			      "text":"66 - Journalism",
        			      "value":66
        			   },
        			   {
        			      "text":"76 - Ondernemen",
        			      "value":76
        			   },
        			   {
        			      "text":"82 - Market Trends",
        			      "value":82
        			   },
        			   {
        			      "text":"83 - 9x Awesome Content",
        			      "value":83
        			   },
        			   {
        			      "text":"84 - Business Practices",
        			      "value":84
        			   },
        			   {
        			      "text":"86 - Education Market",
        			      "value":86
        			   },
        			   {
        			      "text":"87 - Venture Capital & Startups",
        			      "value":87
        			   },
        			   {
        			      "text":"89 - Fintech",
        			      "value":89
        			   },
        			   {
        			      "text":"101 - Direct Marketing",
        			      "value":101
        			   },
        			   {
        			      "text":"109 - IT Business",
        			      "value":109
        			   },
        			   {
        			      "text":"116 - NN Algemeen",
        			      "value":116
        			   },
        			   {
        			      "text":"120 - Customer Insights",
        			      "value":120
        			   },
        			   {
        			      "text":"125 - CPS",
        			      "value":125
        			   },
        			   {
        			      "text":"126 - RMS",
        			      "value":126
        			   },
        			   {
        			      "text":"136 - IBM in the Media",
        			      "value":136
        			   },
        			   {
        			      "text":"151 - Randstad in the News",
        			      "value":151
        			   },
        			   {
        			      "text":"152 - Randstad Market Watch",
        			      "value":152
        			   },
        			   {
        			      "text":"170 - IBM Cloud Market Watch",
        			      "value":170
        			   },
        			   {
        			      "text":"219 - IBM Developer Advocates",
        			      "value":219
        			   },
        			   {
        			      "text":"250 - Achmea Transport",
        			      "value":250
        			   },
        			   {
        			      "text":"251 - Achmea Automotive",
        			      "value":251
        			   },
        			   {
        			      "text":"253 - Achmea Innovation",
        			      "value":253
        			   }
        			]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host;
      attachment.author_link = `http://${req.body.host}`;
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date) / 1000
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
    	if (!req.body.keywords.includes(", ")) {
    		req.body.keywords = req.body.keywords.replace(/,/g, ", ")
    	}
	    fields.push({
	    	title: "Keywords",
	    	short: false,
	    	value: req.body.keywords
	    })
    }
    if (req.body.companies) {
    	if (!req.body.companies.includes(", ")) {
    		req.body.companies = req.body.companies.replace(/,/g, ", ")
    	}
	    fields.push({
	        title: "Companies",
	        short: false,
	        value: req.body.companies
	    })
    }
    if (req.body.word_count) {
    	var length = req.body.word_count
    	var prefix = ""
    	if (length > 1000 )
    		prefix = ":snail: "
    	else if (length < 300)
    		prefix = ":fast_forward: "
    	fields.push({
    		title: "Length",
    		short: true,
    		value: `${prefix}${length} words`
    	})
    }
    if (req.body.shares) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.shares)
      })
    }
    if (req.body.sentiment) {
    	var sentiment
    	switch (req.body.sentiment) {
    		case "negative":
    			sentiment = ":rage: Negative";
    			break;
    		case "positive":
    			sentiment = ":smile: Positive";
    			break;
    		case "neutral":
    			sentiment = "Neutral"
    			break;
    	}
    	fields.push({
            title: "Sentiment",
            short: true,
            value: sentiment
          })
    }
//    Unsupported for now
//    fields.push({
//    	"title": "Sponsored",
//        "value": ":warning: Undetected",
//        "short": true
//    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
	var sharedInChannel = true
	if (!value) {
		sharedInChannel = false
		value = msg.body.actions[0].selected_options[0].value
	}
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
	addUrlToChannel(value, url)
		.then(() => {
			var attachment = {
				color: '#006600',
				text: `${url}
:postbox: Article posted to channel ${value} by <@${userId}>`
			}
			originalMsg.attachments = []
			if (!sharedInChannel) {
				originalMsg.attachments.push(chosenAttachment)
			}
			originalMsg.attachments.push(attachment)
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			console.log(err)
			chosenAttachment.color = '#ff9933'
			var lastAttachment = {
					pretext: `:exclamation: Error posting article to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{body: url}, (err, res, body) => {
				if (err) return reject(err);
				try {
					JSON.parse(body)[0]
				} catch (err) {
					return reject(JSON.stringify(body));
				}
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err2) return reject(err);
	    				try {
	    					var success = body2.success
	    					if (!success) return reject(JSON.stringify(body));
	    				} catch (err) {
	    					return reject(JSON.stringify(body));
	    				}
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var attachment = {
		color: '#800000',
		text: `${url}
:no_entry: Article discarded by <@${userId}>`,
	}
	originalMsg.attachments = [attachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
	var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
	var postfix = ""
	var prefix = ""
	if (magnitude >= 6) {
		prefix = ":fire: "
		magnitude -= 6
		postfix = "M"
	} else if (magnitude >= 3) {
		magnitude -= 3
		postfix = "k"
	}
	var first_digit = String(x).charAt(0);
	var rounded_significant = first_digit >= 5 ? 5 : 1;
	return `${prefix}${rounded_significant * Math.pow(10, magnitude)}${postfix}+`
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<commit_msg>cosmetic fix<commit_after>'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var channels = {}

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message.resource.SlackTeamName);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})
var app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "https://cdn3.iconfinder.com/data/icons/basicolor-arrows-checks/24/154_check_ok_sticker_success-512.png" : "http://www.clker.com/cliparts/H/Z/0/R/f/S/warning-icon-hi.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
            		   {
            		      "text":"1 - Test",
            		      "value":1
            		   },
            		   {
        			     "text":"7 - Digital Marketing",
        			     "value":7
        			   },
        			   {
        			      "text":"40 - Legal",
        			      "value":40
        			   },
        			   {
        			      "text":"43 - Innovation & Startups",
        			      "value":43
        			   },
        			   {
        			      "text":"66 - Journalism",
        			      "value":66
        			   },
        			   {
        			      "text":"76 - Ondernemen",
        			      "value":76
        			   },
        			   {
        			      "text":"82 - Market Trends",
        			      "value":82
        			   },
        			   {
        			      "text":"83 - 9x Awesome Content",
        			      "value":83
        			   },
        			   {
        			      "text":"84 - Business Practices",
        			      "value":84
        			   },
        			   {
        			      "text":"86 - Education Market",
        			      "value":86
        			   },
        			   {
        			      "text":"87 - Venture Capital & Startups",
        			      "value":87
        			   },
        			   {
        			      "text":"89 - Fintech",
        			      "value":89
        			   },
        			   {
        			      "text":"101 - Direct Marketing",
        			      "value":101
        			   },
        			   {
        			      "text":"109 - IT Business",
        			      "value":109
        			   },
        			   {
        			      "text":"116 - NN Algemeen",
        			      "value":116
        			   },
        			   {
        			      "text":"120 - Customer Insights",
        			      "value":120
        			   },
        			   {
        			      "text":"125 - CPS",
        			      "value":125
        			   },
        			   {
        			      "text":"126 - RMS",
        			      "value":126
        			   },
        			   {
        			      "text":"136 - IBM in the Media",
        			      "value":136
        			   },
        			   {
        			      "text":"151 - Randstad in the News",
        			      "value":151
        			   },
        			   {
        			      "text":"152 - Randstad Market Watch",
        			      "value":152
        			   },
        			   {
        			      "text":"170 - IBM Cloud Market Watch",
        			      "value":170
        			   },
        			   {
        			      "text":"219 - IBM Developer Advocates",
        			      "value":219
        			   },
        			   {
        			      "text":"250 - Achmea Transport",
        			      "value":250
        			   },
        			   {
        			      "text":"251 - Achmea Automotive",
        			      "value":251
        			   },
        			   {
        			      "text":"253 - Achmea Innovation",
        			      "value":253
        			   }
        			]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host;
      attachment.author_link = `http://${req.body.host}`;
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date) / 1000
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
    	if (!req.body.keywords.includes(", ")) {
    		req.body.keywords = req.body.keywords.replace(/,/g, ", ")
    	}
	    fields.push({
	    	title: "Keywords",
	    	short: false,
	    	value: req.body.keywords
	    })
    }
    if (req.body.companies) {
    	if (!req.body.companies.includes(", ")) {
    		req.body.companies = req.body.companies.replace(/,/g, ", ")
    	}
	    fields.push({
	        title: "Companies",
	        short: false,
	        value: req.body.companies
	    })
    }
    if (req.body.word_count) {
    	var length = req.body.word_count
    	var prefix = ""
    	if (length > 1000 )
    		prefix = ":snail: "
    	else if (length < 300)
    		prefix = ":fast_forward: "
    	fields.push({
    		title: "Length",
    		short: true,
    		value: `${prefix}${length} words`
    	})
    }
    if (req.body.shares) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.shares)
      })
    }
    if (req.body.sentiment) {
    	var sentiment
    	switch (req.body.sentiment) {
    		case "negative":
    			sentiment = ":rage: Negative";
    			break;
    		case "positive":
    			sentiment = ":smile: Positive";
    			break;
    		case "neutral":
    			sentiment = "Neutral"
    			break;
    	}
    	fields.push({
            title: "Sentiment",
            short: true,
            value: sentiment
          })
    }
//    Unsupported for now
//    fields.push({
//    	"title": "Sponsored",
//        "value": ":warning: Undetected",
//        "short": true
//    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
	var sharedInChannel = true
	if (!value) {
		sharedInChannel = false
		value = msg.body.actions[0].selected_options[0].value
	}
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
	addUrlToChannel(value, url)
		.then(() => {
			var attachment = {
				color: '#006600',
				text: `${url}
:postbox: Article posted to channel ${value} by <@${userId}>`
			}
			originalMsg.attachments = []
			if (!sharedInChannel) {
				originalMsg.attachments.push(chosenAttachment)
			}
			originalMsg.attachments.push(attachment)
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			console.log(err)
			chosenAttachment.color = '#ff9933'
			var lastAttachment = {
					pretext: `:exclamation: Error posting article to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{body: url}, (err, res, body) => {
				if (err) return reject(err);
				try {
					JSON.parse(body)[0]
				} catch (err) {
					return reject(JSON.stringify(body));
				}
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err2) return reject(err);
	    				try {
	    					var success = body2.success
	    					if (!success) return reject(JSON.stringify(body));
	    				} catch (err) {
	    					return reject(JSON.stringify(body));
	    				}
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var attachment = {
		color: '#800000',
		text: `${url}
:no_entry: Article discarded by <@${userId}>`,
	}
	originalMsg.attachments = [attachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
	var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
	var postfix = ""
	var prefix = ""
	if (magnitude >= 6) {
		prefix = ":fire: "
		magnitude -= 6
		postfix = "M"
	} else if (magnitude >= 3) {
		prefix = ":fire: "
		magnitude -= 3
		postfix = "k"
	}
	var first_digit = String(x).charAt(0);
	var rounded_significant = first_digit >= 5 ? 5 : 1;
	return `${prefix}${rounded_significant * Math.pow(10, magnitude)}${postfix}+`
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    http = require('http'),
    mongo = require('mongodb').MongoClient,
    app = express(),
    regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
    urls = {};

mongo.connect('mongodb://localhost:27017/urls', function(err, db) {
    if(err) {
        console.log("Can't connect to DB!");
    } else {
        console.log("Connected to DB!");
        var userCreated = db.collection('userCreated');
        app.use('/*', function (req, res) {
            // Determine if passed url is in database for forwarding
           var passedUrl = { "short url": req.protocol + "s://" + req.get('host') + "/" + req.params['0'] };

            userCreated.find(passedUrl).toArray(function(err,result) {
                if(err) { throw err; }
                console.log(passedUrl);
                if(result.length > 0) {
                res.redirect("http://www.google.com" );
                res.end();
                }
            });
        });

        /*

        app.use('/*', function(req, res) {

// If url submitted as param is in correct format, search in database
            if(req.params['0'].match(regex)) {
               userCreated.find({ "original url": req.params['0'] }).limit(1).toArray(function(err, result) {
                if (err) {
                    throw err;
                    }
// If url submitted as param is not found in database, create new short url
                if(result.length === 0) {
                    var shortUrl = "https://url-shortener-microservice-timrizzo.c9users.io/" + Math.floor(Math.random() * 100 + 1);
// If new short url is not found in database, insert both urls in a new document
                   if(userCreated.find({ "short url" : shortUrl }).toArray().length === undefined) {
                       userCreated.insert(
                        {
                            "original url": req.params['0'],
                            "short url": shortUrl
                        });
                    } else {
                        console.log("Duplicate!" + userCreated.find({ "short url" : shortUrl }).toArray().length);
                    }

                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": "Not in DB!"
                    };
                } else {
                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": result,
                        "url": req.protocol + "//:" + req.get('host')
                    };
                }
                res.send(urls);
                });
            } else {
                res.send("Not proper URL!");
            }
        });

        */
    }
});

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});

<commit_msg>got db functions and redirect working together<commit_after>'use strict';

var express = require('express'),
    http = require('http'),
    mongo = require('mongodb').MongoClient,
    app = express(),
    regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
    urls = {};

mongo.connect('mongodb://localhost:27017/urls', function(err, db) {
    if(err) {
        console.log("Can't connect to DB!");
    } else {
        console.log("Connected to DB!");
        var userCreated = db.collection('userCreated');

        app.use('/*', function(req, res) {

// Determine if passed url is in database for forwarding
           var passedUrl = { "short url": req.protocol + "s://" + req.get('host') + "/" + req.params['0'] };

            userCreated.find(passedUrl).toArray(function(err,result) {
                if(err) { throw err; }
                console.log(passedUrl);
                if(result.length > 0) {
                return res.redirect("http://www.google.com" );
                } else {

        // If url submitted as param is in correct format, search in database
                    if(req.params['0'].match(regex)) {
                       userCreated.find({ "original url": req.params['0'] }).limit(1).toArray(function(err, result) {
                        if (err) {
                            throw err;
                            }
        // If url submitted as param is not found in database, create new short url
                        if(result.length === 0) {
                            var shortUrl = "https://url-shortener-microservice-timrizzo.c9users.io/" + Math.floor(Math.random() * 100 + 1);
        // If new short url is not found in database, insert both urls in a new document
                           if(userCreated.find({ "short url" : shortUrl }).toArray().length === undefined) {
                               userCreated.insert(
                                {
                                    "original url": req.params['0'],
                                    "short url": shortUrl
                                });
                            } else {
                                console.log("Duplicate!" + userCreated.find({ "short url" : shortUrl }).toArray().length);
                            }

                            urls = {
                            	"original url": req.params['0'],
                                "short url": "",
                                "db": "Not in DB!"
                            };
                        } else {
                            urls = {
                            	"original url": req.params['0'],
                                "short url": "",
                                "db": result,
                                "url": req.protocol + "//:" + req.get('host')
                            };
                        }
                        res.send(urls);
                        });
                    } else {
                        res.send("Not proper URL!");
                    }
                }
            });
        });
    }
});

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});

<|endoftext|>


<commit_before>var express = require('express');
var morgan = require('morgan');
var path = require('path');

var app = express();
app.use(morgan('combined'));

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});
/*app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'ui','Profile.html'));
});*/
app.get('/ui/style.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style.css'));
});
/*app.get('/ui/style1.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style1.css'));
});*/

/*app.get('/ui/madi.png', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
});*/

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`IMAD course app listening on port ${port}!`);
});
<commit_msg>[imad-console] Updates server.js<commit_after>var express = require('express');
var morgan = require('morgan');
var path = require('path');

var app = express();
app.use(morgan('combined'));

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'ui','Profile.html'));
});
app.get('/ui/style.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style.css'));
});
app.get('/ui/style1.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style1.css'));
});

/*app.get('/ui/madi.png', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
});*/

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`IMAD course app listening on port ${port}!`);
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var datafiles = require('./datafiles');

module.exports = {
  dataFileVariables: function (config, path) {
    let dataVars = {};
    let scopes = _.filter(config.data_file_variables, function (v) {
      return (_.isEmpty(v.scope.path) || new RegExp(v.scope.path).test(path));
    });

    _.forEach(scopes, function (scope) {
      dataVars = _.merge(dataVars, scope.values);
    });

    return dataVars;
  },

  setupConfig: function (source, metadata) {
    let pageVars = _.isEmpty(source) ? {} : this.dataFileVariables(metadata.config, source)
    let config = {
      page: pageVars
    };

    return _.merge({
      'data': datafiles.data,
      'config': metadata.config
    }, config);
  }

};
<commit_msg>Fix crash in data reading<commit_after>var _ = require('lodash');
var datafiles = require('./datafiles');

module.exports = {
  dataFileVariables: function (config, path) {
    // There is no config.yml
    if (_.isUndefined(config)) {
      return {};
    }

    let dataVars = {};
    let scopes = _.filter(config.data_file_variables, function (v) {
      return (_.isEmpty(v.scope.path) || new RegExp(v.scope.path).test(path));
    });

    _.forEach(scopes, function (scope) {
      dataVars = _.merge(dataVars, scope.values);
    });

    return dataVars;
  },

  setupConfig: function (source, metadata) {
    let pageVars = _.isEmpty(source) ? {} : this.dataFileVariables(metadata.config, source)
    let config = {
      page: pageVars
    };

    return _.merge({
      'data': datafiles.data,
      'config': metadata.config
    }, config);
  }

};
<|endoftext|>


<commit_before>var zkLib       = require('./lib/ZooKeeper.js');
var kafkaLib    = require('./lib/Kafka.js');
var cache       = require('./lib/Cache.js').cache;
var logger      = require('./logger.js').logger;
var config      = require('./config');
var express     = require('express');
var app         = express();

var loadMetadata = function(callback) {
    zkLib.loadConsumerMetaData(callback);
};

var loadKafkaOffsets = function(callback) {
    kafkaLib.getTopicOffsets(callback);
};

var pollKafkaOffsets = function() {
    logger.trace('polling for the latest kafka offsets');
    setTimeout(function() {
        loadKafkaOffsets(pollKafkaOffsets);
    }, config.refreshInterval.lag);
};

var pollMetadata = function() {
    logger.trace('polling the latest metadata');
    setTimeout(function() {
        loadMetadata(pollMetadata);
    }, config.refreshInterval.metadata);
};

loadMetadata(function() {
    pollMetadata();
    loadKafkaOffsets(pollKafkaOffsets);
});

// CORS headers for external access from JS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/monitor/refresh', function(req, res) {
    logger.trace('load metadata called from external source');
    loadMetadata(function(err){
        if (err) {
            return res.status(500).json({'error_code': 500, 'message': err});
        }

        logger.trace('completed loading metadata');
        return res.status(200).send();
    });
});

app.get('/consumergroups', function(req, res){
    cache.keys(function(err, keys){
        logger.debug({keys: keys}, 'returned keys');
        res.status(200).send(keys);
    });
});

app.get('/consumers/:consumer/lag', function(req, res) {
    var consumer = req.params.consumer;

    cache.get(consumer, function(err, value){
        if (!err) {
            // TODO : sort the response here if required
            res.send(value);
        }
        else {
            res.status(500).send();
        }
    });
});

app.listen(config.server.port);
<commit_msg>fix merge issue<commit_after>var zkLib       = require('./lib/ZooKeeper.js');
var kafkaLib    = require('./lib/Kafka.js');
var cache       = require('./lib/Cache.js').cache;
var logger      = require('./logger.js').logger;
var config      = require('./config');
var express     = require('express');
var app         = express();

 var loadMetadata = function(callback) {
    zkLib.loadConsumerMetaData(callback);
};

var loadKafkaOffsets = function(callback) {
    kafkaLib.getTopicOffsets(callback);
};

var pollKafkaOffsets = function() {
    logger.trace('polling for the latest kafka offsets');
    setTimeout(function() {
        loadKafkaOffsets(pollKafkaOffsets);
    }, config.refreshInterval.lag);
};

var pollMetadata = function() {
    logger.trace('polling the latest metadata');
    setTimeout(function() {
        loadMetadata(pollMetadata);
    }, config.refreshInterval.metadata);
};

loadMetadata(function() {
    pollMetadata();
    loadKafkaOffsets(pollKafkaOffsets);
});

// CORS headers for external access from JS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/monitor/refresh', function(req, res) {
    logger.trace('load metadata called from external source');
    loadMetadata(function(err){
        if (err) {
            return res.status(500).json({'error_code': 500, 'message': err});
        }

        logger.trace('completed loading metadata');
        return res.status(200).send();
    });
});

app.get('/consumergroups', function(req, res){
    cache.keys(function(err, keys){
        logger.debug({keys: keys}, 'returned keys');
        res.status(200).send(keys);
    });
});

app.get('/consumers/:consumer/lag', function(req, res) {
    var consumer = req.params.consumer;

    cache.get(consumer, function(err, value){
        if (!err) {
            // TODO : sort the response here if required
            res.send(value);
        }
        else {
            res.status(500).send();
        }
    });
});

app.listen(config.server.port);
<|endoftext|>


<commit_before>var EXPRESS = require('express');
DELBID = EXPRESS();

DELBID.express   = EXPRESS;
DELBID.config    = require('./config.js');
DELBID.stylus    = require('stylus');
DELBID.db        = require('./server/schemas/mainDB.js');
DELBID.speakeasy = require('speakeasy-nlp');
DELBID.auth      = require('./server/auth.js')(DELBID);

//standard function for handling errors
//just prints the error to the console
//and executes a callback if one is provided
DELBID.handleErr = function(err, cb){
	if (err) { console.log(err); }
	if (cb ) { cb; }
}

//use stylus templates for CSS
DELBID.compile = function(str, path){ return DELBID.stylus(str).set('filename', path); }
DELBID.use(DELBID.stylus.middleware({ src: __dirname + '/' , compile: compile }));
DELBID.use(DELBID.express.static(__dirname + '/'));

DELBID.routes          = {};
DELBID.routes.auth     = require('./server/routes/auth.js'   )(DELBID);
DELBID.routes.views    = require('./server/routes/views.js'  )(DELBID);
DELBID.routes.queries  = require('./server/routes/queries.js')(DELBID);
DELBID.routes.other    = require('./server/routes/other.js'  )(DELBID);

//use socket.io and give it a location to listen on
DELBID.socketio = require('socket.io').listen(DELBID.listen(DELBID.config.SERVER_PORT, DELBID.config.SERVER_IP));
DELBID.socketio.set('log level', 1);
DELBID.socketio.set('browser client minification', true);
DELBID.socketio.set('browser client etag', true);

//use passport.socket.io to link passport sessions with a socket
DELBID.socketio.set('authorization', DELBID.auth.passportSIO.authorize({
	cookieParser: DELBID.express.cookieParser,
	key:          'delegate.bid.sid',
	secret:       DELBID.config.COOKIE_SECRET,
	store:        DELBID.auth.sessionStore.mongo,
	fail:         function(data, message, error, accept){ accept(null, true); }
}));

console.log('All systems are GO!');
console.log('listening at ' + DELBID.config.SERVER_IP + ' on port ' + DELBID.config.SERVER_PORT);

<commit_msg>removed speakeasy<commit_after>var EXPRESS = require('express');
DELBID = EXPRESS();

DELBID.express   = EXPRESS;
DELBID.config    = require('./config.js');
DELBID.stylus    = require('stylus');
DELBID.db        = require('./server/schemas/mainDB.js');
DELBID.auth      = require('./server/auth.js')(DELBID);

//standard function for handling errors
//just prints the error to the console
//and executes a callback if one is provided
DELBID.handleErr = function(err, cb){
	if (err) { console.log(err); }
	if (cb ) { cb; }
}

//use stylus templates for CSS
DELBID.compile = function(str, path){ return DELBID.stylus(str).set('filename', path); }
DELBID.use(DELBID.stylus.middleware({ src: __dirname + '/' , compile: compile }));
DELBID.use(DELBID.express.static(__dirname + '/'));

DELBID.routes          = {};
DELBID.routes.auth     = require('./server/routes/auth.js'   )(DELBID);
DELBID.routes.views    = require('./server/routes/views.js'  )(DELBID);
DELBID.routes.queries  = require('./server/routes/queries.js')(DELBID);
DELBID.routes.other    = require('./server/routes/other.js'  )(DELBID);

//use socket.io and give it a location to listen on
DELBID.socketio = require('socket.io').listen(DELBID.listen(DELBID.config.SERVER_PORT, DELBID.config.SERVER_IP));
DELBID.socketio.set('log level', 1);
DELBID.socketio.set('browser client minification', true);
DELBID.socketio.set('browser client etag', true);

//use passport.socket.io to link passport sessions with a socket
DELBID.socketio.set('authorization', DELBID.auth.passportSIO.authorize({
	cookieParser: DELBID.express.cookieParser,
	key:          'delegate.bid.sid',
	secret:       DELBID.config.COOKIE_SECRET,
	store:        DELBID.auth.sessionStore.mongo,
	fail:         function(data, message, error, accept){ accept(null, true); }
}));

console.log('All systems are GO!');
console.log('listening at ' + DELBID.config.SERVER_IP + ' on port ' + DELBID.config.SERVER_PORT);

<|endoftext|>


<commit_before>// NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');

// Custom Modules
var yans = require("./node_modules-custom/yans");
var twinglish = require("./node_modules-custom/twinglish.js");
var twetrics = require("./node_modules-custom/twetrics.js");
var csv = require("./node_modules-custom/csv.js");

var twitterClient;
var server;
async.waterfall([

  function(next) {

    // SERVER

    server = new yans({
      "directory": __dirname,
      "viewPath": "pages",
      "logging": true,
      "loggingFormat": ":method :url -> HTTP :status; :response-time ms",
      "staticDirectories": ["css", "fonts", "js", "static"]
    });

    server.resetDatabase = function(callback) {
      var _self = this;
      var blankData = fs.readFileSync("db-blank.json");
      fs.writeFileSync("db.json", blankData);
      _self.db = low("db.json");
      callback();
    };

    server.jsonError = function(text, res) {
      res.send({
        "error": text
      });
    };

    server.jsonSuccess = function(text, res) {
      res.send({
        "ok": text
      });
    };

    next();

  },

  function(next) {

    // DATABASE

    if (!fs.existsSync("db.json")) {
      server.resetDatabase(next);
    } else {
      server.db = low("db.json");
      next();
    }

  },

  function(next) {

    // TWITTER

    fs.readFile("twitter-credentials.json", function(error, data) {
      if (error) {
        console.error("twitter-credentials.json is missing or couldn't be read. I need this.");
        process.exit();
        return;
      }
      var twitterDetails = JSON.parse(data);
      twitterClient = new twitter(twitterDetails);
      next();
    });

  },

  function(next) {

    //
    // FRONTEND (UI) ROUTES
    //

    server.app.get("/", function(req, res) {
      res.render("index");
    });

    server.app.get("/twitter", function(req, res) {
      res.render("twitter");
    });

    server.app.get("/process/*", function(req, res) {
      console.log(req);
      res.render(
        "process",
        {
          "twitter": req.params[0]
        }
      );
    });

    server.app.get("/favicon.ico", function(req, res) {
      res.redirect(301, "static/favicon.ico");
    });

    //
    // BACKEND (API) ROUTES
    //

    server.app.get("/api/reset", function(req, res) {
      async.waterfall([
        function(next) {
          server.resetDatabase(next);
        },
        function(next) {
          server.jsonSuccess("The database was reset.", res);
        }
      ]);
    });

    server.app.get("/api/twitter/*", function(req, res) {

      var screenName = req.params[0];
      if (!screenName.length) {
        server.jsonError("The Twitter screen name was empty.", res);
        return;
      }

      async.waterfall([

        function(next) {

          // Account
          twitterClient.get(
            'users/show',
            {
              "screen_name": screenName,
            },
            function(error, data, raw) {
              if (error) {
                var errorText;
                switch(error.statusCode) {
                  case 404:
                    errorText = "That Twitter account doesn't exist.";
                    break;
                  default:
                    errorText = "The twitter account couldn't be accessed; that's all.";
                    break;
                }
                server.jsonError(errorText, res);
                return;
              }
              var newData = {
                "twitter": {
                  "account": {
                    "screenName": data.screen_name,
                    "name": data.name,
                    "location": data.location,
                    "description": data.description,
                    "language": data.lang,
                    "picture": data.profile_image_url
                  }
                }
              };
              next(null, newData);
            }
          );

        },

        function(passedData, next) {

          twitterClient.get(
            'statuses/user_timeline',
            {
              "screen_name": screenName,
              "trim_user": true,
              "count": 200,
              "include_rts": true
            },
            function(error, data, raw) {
              // console.log(error);
              if (error) {
                var errorText;
                switch(error.statusCode) {
                  case 401:
                    errorText = "That Twitter account is probably using ‘protected tweets’.";
                    break;
                  default:
                    errorText = "The tweets couldn't be retrieved; that's all.";
                    break;
                }
                server.jsonError(errorText, res);
                return;
              }
              var tweets = _.map(data, twinglish.cleanTweet);
              //some tweets may have been removed (annulled)
              tweets = _.filter(tweets, function(tweet) {
                return (tweet != null && tweet != undefined); //sorry
               });
              passedData["twitter"]["tweets"] = tweets;
              next(null, passedData);
            }
          );

        },

        function(passedData, next) {
          if ("metrics" in req.query) {
            passedData["metrics"] = _.map(twetrics.metrics, function(metric) {
              return metric.method(passedData["twitter"]["tweets"]);
            });
          }
          next(null, passedData);
        },

        function(passedData, next) {
          var format = (("format" in req.query) ? req.query.format : "json");
          var data;
          switch(format) {
            case "json":
              data = passedData;
              break;
            case "prettyjson":
              data = JSON.stringify(passedData, undefined, 2);
              break;
            case "csv":
              //return only tweets
              data = csv.fromObjects(
                passedData["twitter"]["tweets"],
                ["when", "text", "isRetweet"],
                true
              );
              break;
            default:
              data = [];
              break;
          }
          res.send(data);
          // to do: improve save code...
          // server.db("museums").push(passedData);
          // server.db.save();
        }

      ]);

    });

    //
    // ERROR CODE ROUTES
    //

    server.app.get("*", function(req, res) {
      res.status(404);
      res.render("404");
    });

  }

]);<commit_msg>Put metrics under Twitter JSON key. 'store' format for Twitter API.<commit_after>// NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');

// Custom Modules
var yans = require("./node_modules-custom/yans");
var twinglish = require("./node_modules-custom/twinglish.js");
var twetrics = require("./node_modules-custom/twetrics.js");
var csv = require("./node_modules-custom/csv.js");

var twitterClient;
var server;
async.waterfall([

  function(next) {

    // SERVER

    server = new yans({
      "directory": __dirname,
      "viewPath": "pages",
      "logging": true,
      "loggingFormat": ":method :url -> HTTP :status; :response-time ms",
      "staticDirectories": ["css", "fonts", "js", "static"]
    });

    server.resetDatabase = function(callback) {
      var _self = this;
      var blankData = fs.readFileSync("db-blank.json");
      fs.writeFileSync("db.json", blankData);
      _self.db = low("db.json");
      callback();
    };

    server.jsonError = function(text, res) {
      res.send({
        "error": text
      });
    };

    server.jsonSuccess = function(text, res) {
      res.send({
        "ok": text
      });
    };

    next();

  },

  function(next) {

    // DATABASE

    if (!fs.existsSync("db.json")) {
      server.resetDatabase(next);
    } else {
      server.db = low("db.json");
      next();
    }

  },

  function(next) {

    // TWITTER

    fs.readFile("twitter-credentials.json", function(error, data) {
      if (error) {
        console.error("twitter-credentials.json is missing or couldn't be read. I need this.");
        process.exit();
        return;
      }
      var twitterDetails = JSON.parse(data);
      twitterClient = new twitter(twitterDetails);
      next();
    });

  },

  function(next) {

    //
    // FRONTEND (UI) ROUTES
    //

    server.app.get("/", function(req, res) {
      res.render("index");
    });

    server.app.get("/twitter", function(req, res) {
      res.render("twitter");
    });

    server.app.get("/process/*", function(req, res) {
      res.render(
        "process",
        {
          "twitter": req.params[0]
        }
      );
    });

    server.app.get("/favicon.ico", function(req, res) {
      res.redirect(301, "static/favicon.ico");
    });

    //
    // BACKEND (API) ROUTES
    //

    server.app.get("/api/reset", function(req, res) {
      async.waterfall([
        function(next) {
          server.resetDatabase(next);
        },
        function(next) {
          server.jsonSuccess("The database was reset.", res);
        }
      ]);
    });

    server.app.get("/api/twitter/*", function(req, res) {

      var screenName = req.params[0];
      if (!screenName.length) {
        server.jsonError("The Twitter screen name was empty.", res);
        return;
      }

      async.waterfall([

        function(next) {

          // Account
          twitterClient.get(
            'users/show',
            {
              "screen_name": screenName,
            },
            function(error, data, raw) {
              if (error) {
                var errorText;
                switch(error.statusCode) {
                  case 404:
                    errorText = "That Twitter account doesn't exist.";
                    break;
                  default:
                    errorText = "The twitter account couldn't be accessed; that's all.";
                    break;
                }
                server.jsonError(errorText, res);
                return;
              }
              var newData = {
                "twitter": {
                  "account": {
                    "screenName": data.screen_name,
                    "name": data.name,
                    "location": data.location,
                    "description": data.description,
                    "language": data.lang,
                    "picture": data.profile_image_url
                  }
                }
              };
              next(null, newData);
            }
          );

        },

        function(passedData, next) {

          twitterClient.get(
            'statuses/user_timeline',
            {
              "screen_name": screenName,
              "trim_user": true,
              "count": 200,
              "include_rts": true
            },
            function(error, data, raw) {
              // console.log(error);
              if (error) {
                var errorText;
                switch(error.statusCode) {
                  case 401:
                    errorText = "That Twitter account is probably using ‘protected tweets’.";
                    break;
                  default:
                    errorText = "The tweets couldn't be retrieved; that's all.";
                    break;
                }
                server.jsonError(errorText, res);
                return;
              }
              var tweets = _.map(data, twinglish.cleanTweet);
              //some tweets may have been removed (annulled)
              tweets = _.filter(tweets, function(tweet) {
                return (tweet != null && tweet != undefined); //sorry
               });
              passedData["twitter"]["tweets"] = tweets;
              next(null, passedData);
            }
          );

        },

        function(passedData, next) {
          if ("metrics" in req.query) {
            passedData["twitter"]["metrics"] = _.map(twetrics.metrics, function(metric) {
              return metric.method(passedData["twitter"]["tweets"]);
            });
          }
          next(null, passedData);
        },

        function(passedData, next) {
          var format = (("format" in req.query) ? req.query.format : "json");
          var data;
          switch(format) {
            case "store":
              // if(ok) {
              //   server.jsonSuccess("The Twitter data was stored.", res);
              // } else {
              //   server.jsonError("The Twitter data was not stored.", res);
              // }
              server.jsonSuccess("The Twitter data was stored.", res);
              return;
              break;
            case "json":
              data = passedData;
              break;
            case "prettyjson":
              data = JSON.stringify(passedData, undefined, 2);
              break;
            case "csv":
              //return only tweets
              data = csv.fromObjects(
                passedData["twitter"]["tweets"],
                ["when", "text", "isRetweet"],
                true
              );
              break;
            default:
              data = [];
              break;
          }
          res.send(data);
        }

      ]);

    });

    //
    // ERROR CODE ROUTES
    //

    server.app.get("*", function(req, res) {
      res.status(404);
      res.render("404");
    });

  }

]);<|endoftext|>


<commit_before>const pathToRegexp = require('path-to-regexp');

class PublicMockPlugin {
    name() {
        return 'publicMock';
    }

    dependencies() {
        return ['server'];
    }

    service() {
        return {};
    }

    constructor({ publicMockList = [] }) {
        this.publicMockList = publicMockList;
    }

    init({ service }) {
        const use = service('server.use');
        const {publicMockList} = this;

        use(() => function *(next) {
            const reqPath = this.request.path;
            const dispatcher = this.dispatcher;

            if (!dispatcher) {
                return yield next;
            }

            dispatcher.extendData = publicMockList.reduce((extendData, {
                pattern, data, type = 'sync'
            }) => {
                if (isPathMatched({pattern,  reqPath}) && type === dispatcher.type ) {
                    return Object.assign(data, data);
                }
                return extendData;
            }, dispatcher.extendData);

            yield next;
        });
    }
}

function isPathMatched({ pattern, reqPath }) {
    return pathToRegexp(pattern).test(reqPath);
}

module.exports = PublicMockPlugin;
<commit_msg>chore: update public-mock some value's default function<commit_after>const pathToRegexp = require('path-to-regexp');

class PublicMockPlugin {
    name() {
        return 'publicMock';
    }

    dependencies() {
        return ['server'];
    }

    service() {
        return {};
    }

    constructor({ publicMockList = [] }) {
        this.publicMockList = publicMockList;
    }

    init({ service }) {
        const use = service('server.use');
        const {publicMockList} = this;

        use(() => function *(next) {
            const reqPath = this.request.path;
            const dispatcher = this.dispatcher;

            if (!dispatcher) {
                return yield next;
            }

            dispatcher.extendData = publicMockList.reduce((extendData, {
                pattern, data, type
            }) => {
                if (isPathMatched({pattern, reqPath})
                    && ( typeof type === 'undefined'
                    || type === dispatcher.type ) ) {
                    return Object.assign(data, data);
                }
                return extendData;
            }, dispatcher.extendData);

            yield next;
        });
    }
}

function isPathMatched({ pattern, reqPath }) {
    return pathToRegexp(pattern).test(reqPath);
}

module.exports = PublicMockPlugin;
<|endoftext|>


<commit_before>var http = require('http'),
    beeline = require('beeline'),
    port = process.env.PORT || 9000,
    latestData,
    lastCount,
    apiKey = require('./key.json'),
    pollRate = 3000;

function setNoCacheResponse(response){
   response.setHeader("Cache-Control", "no-cache, private, no-store, must-revalidate, max-age=0, max-stale=0, post-check=0, pre-check=0");
   response.setHeader("Pragma", "no-cache");
   response.setHeader("Expires", 0);
}

function updateCount(){
    http.get({
        host: 'api.change.org',
        path: '/v1/petitions/1292760?api_key=' + apiKey.key
    }, function(result) {
        if (result.statusCode === 200) {
            var body = [];
            result.setEncoding('utf8');
            result.on('data', function(chunk) {
                body.push(chunk);
            });
            result.on('end', function() {
                latestData = JSON.parse(body.join(''));
                if(lastCount){
                    latestData.rate = Math.max((latestData.signature_count - lastCount) / (pollRate/1000), 0.1);
                }
                lastCount = latestData.signature_count;
            });
        } else {
            console.log('Received non-ok response: ' + result.statusCode);
        }
    });
}

updateCount();

setInterval(updateCount, pollRate);

var router = beeline.route({
    '/signatures': function(request, response) {
        response.end(JSON.stringify({
            signatureCount:latestData.signature_count,
            rate: latestData.rate
        }));
    },
    '/': function(request, response){
        setNoCacheResponse(response);
        return beeline.staticFile('./public/index.html','text/html', 0)(request, response);
    },
    "/robots /robots.txt":  function(request, response, tokens, values){
        routeHelpers.setNoCacheResponse(response);
        bee.staticFile("./public/robots.txt", "text/plain", 0)(request, response, tokens, values);
    },
    '`path...`': beeline.staticDir('./public', {
        ".txt": "text/plain",
        ".html": "text/html",
        ".css": "text/css",
        ".ico": "image/x-icon",
        ".swf": "application/x-shockwave-flash",
        ".js": "application/javascript" }, 0)
});

var server = http.createServer(router);

server.listen(port);<commit_msg>added image handling<commit_after>var http = require('http'),
    beeline = require('beeline'),
    port = process.env.PORT || 9000,
    latestData,
    lastCount,
    apiKey = require('./key.json'),
    pollRate = 3000;

function setNoCacheResponse(response){
   response.setHeader("Cache-Control", "no-cache, private, no-store, must-revalidate, max-age=0, max-stale=0, post-check=0, pre-check=0");
   response.setHeader("Pragma", "no-cache");
   response.setHeader("Expires", 0);
}

function updateCount(){
    http.get({
        host: 'api.change.org',
        path: '/v1/petitions/1292760?api_key=' + apiKey.key
    }, function(result) {
        if (result.statusCode === 200) {
            var body = [];
            result.setEncoding('utf8');
            result.on('data', function(chunk) {
                body.push(chunk);
            });
            result.on('end', function() {
                latestData = JSON.parse(body.join(''));
                if(lastCount){
                    latestData.rate = Math.max((latestData.signature_count - lastCount) / (pollRate/1000), 0.1);
                }
                lastCount = latestData.signature_count;
            });
        } else {
            console.log('Received non-ok response: ' + result.statusCode);
        }
    });
}

updateCount();

setInterval(updateCount, pollRate);

var router = beeline.route({
    '/signatures': function(request, response) {
        response.end(JSON.stringify({
            signatureCount:latestData.signature_count,
            rate: latestData.rate
        }));
    },
    '/': function(request, response){
        setNoCacheResponse(response);
        return beeline.staticFile('./public/index.html','text/html', 0)(request, response);
    },
    "/robots /robots.txt":  function(request, response, tokens, values){
        routeHelpers.setNoCacheResponse(response);
        bee.staticFile("./public/robots.txt", "text/plain", 0)(request, response, tokens, values);
    },
    '`path...`': beeline.staticDir('./public', {
        ".txt": "text/plain",
        ".html": "text/html",
        ".css": "text/css",
        ".ico": "image/x-icon",
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".swf": "application/x-shockwave-flash",
        ".js": "application/javascript" }, 0)
});

var server = http.createServer(router);

server.listen(port);<|endoftext|>


<commit_before>import _ from 'lodash';
import { BehaviorSubject } from 'rxjs';
import pathToRegexp from 'path-to-regexp';

export default makeRouterService(createHistory) {
  class RouterService {
    constructor(options = {}) {
      this.options = options;
      this._history = createHistory(options);

      this._history$ = new BehaviorSubject({
        length: this._history.length,
        location: this._history.location,
        action: this._history.action,
      });

      this._listener = this._history.listen((location, action) => {
        this._history$.next({
          length: this._history.length,
          location: this._history.location,
          action: this._history.action,
        });
      });
    }

    getHistory$() {
      return this._history$;
    }

    getMatch$(path) {
      return this.getHistory$()
        .map((history) => {
          let keys = [];
          const re = pathToRegexp(path, keys);
          const matched = re.exec(history.location.pathname);

          const keyNames = keys.map(k => k.name);

          if (!matched) {
            return null;
          }

          const keyValues = _.tail(matched);

          return {
            keys,
            matched,
            params: _.zipObject(keyNames, keyValues),
          };
        });
    }

    destroy() {
      this._listener();
    }

    go(n) {
      return this._history.go(n);
    }

    push(path, state) {
      return this._history.push(path, state);
    }

    replace(path, state) {
      return this._history.replace(path, state);
    }

    goBack() {
      return this._history.goBack();
    }

    goForward() {
      return this._history.goForward();
    }
  }

  return RouterService;
}
<commit_msg>frint-router: logic for streaming parsed named params.<commit_after>import _ from 'lodash';
import { BehaviorSubject } from 'rxjs';
import pathToRegexp from 'path-to-regexp';

export default makeRouterService(createHistory) {
  class RouterService {
    constructor(options = {}) {
      this.options = options;
      this._history = createHistory(options);

      this._history$ = new BehaviorSubject({
        length: this._history.length,
        location: this._history.location,
        action: this._history.action,
      });

      this._listener = this._history.listen((location, action) => {
        this._history$.next({
          length: this._history.length,
          location: this._history.location,
          action: this._history.action,
        });
      });

      this._params = {};
      this._params$ = new BehaviorSubject(this._params);
    }

    getHistory$() {
      return this._history$;
    }

    getMatch$(path, updateParams = false) {
      return this.getHistory$()
        .map((history) => {
          let keys = [];
          const re = pathToRegexp(path, keys);
          const matched = re.exec(history.location.pathname);

          const keyNames = keys.map(k => k.name);

          if (!matched) {
            if (updateParams) {
              this._unsetParams(keyNames);
            }

            return null;
          }

          const keyValues = _.tail(matched);
          const params = _.zipObject(keyNames, keyValues);

          if (updateParams) {
            this._setParams(params);
          }

          return {
            keys,
            matched,
            params,
          };
        });
    }

    _unsetParams(names) {
      this._params = names.reduce(acc, (name) => {
        if (typeof acc[name] !== 'undefined') {
          delete acc[name];
        }

        return acc;
      }, this._params);

      this._params$.next(this._params);
    }

    _setParams(params) {
      this._params = Object.assign({}, this._params, params);

      this._params$.next(this._params);
    }

    getParams$() {
      return this._params$;
    }

    destroy() {
      this._listener();
    }

    go(n) {
      return this._history.go(n);
    }

    push(path, state) {
      return this._history.push(path, state);
    }

    replace(path, state) {
      return this._history.replace(path, state);
    }

    goBack() {
      return this._history.goBack();
    }

    goForward() {
      return this._history.goForward();
    }
  }

  return RouterService;
}
<|endoftext|>


<commit_before>'use strict'

if (!process.env.NEW_RELIC_LICENSE_KEY) process.env.NEW_RELIC_ENABLED = 'false'
process.env.NEW_RELIC_LOG = 'stdout'

let koa = require('koa')
let compress = require('koa-compress')
let r = require('koa-route')
let newrelic = require('newrelic')
let parse = require('co-body')
let fs = require('fs')
let packages = require('./lib/packages')
let tarballs = require('./lib/tarballs')
let config = require('./lib/config')
let user = require('./lib/user')
let rollbar = require('rollbar')
let path = require('path')
let app = koa()

if (config.rollbar) {
  rollbar.init(config.rollbar, {
    environment: process.env.NODE_ENV,
    codeVersion: process.env.HEROKU_SLUG_COMMIT,
    host: process.env.HEROKU_APP_NAME,
    scrubHeaders: ['authorization']
  })
  rollbar.handleUncaughtExceptions(config.rollbar)
}

app.name = 'elephant'
app.port = config.port

app.use(require('./logger'))
app.use(compress())

// static root page
app.use(r.get('/', function * () {
  newrelic.setTransactionName('')
  this.type = 'text/html'
  this.body = fs.createReadStream(path.join(__dirname, '/public/index.html'))
}))

// ping
app.use(r.get('/-/ping', function * () {
  newrelic.setTransactionName('-/ping')
  this.body = {}
}))

// error middleware
app.use(function * (next) {
  try { yield next } catch (err) {
    newrelic.noticeError(err)
    if (config.rollbar) rollbar.handleError(err, this.request)
    this.status = err.status || 500
    this.body = {error: err.message}
    this.app.emit('error', err, this)
  }
})

// get package metadata
app.use(r.get('/:name', function * (name) {
  newrelic.setTransactionName(':name')
  let etag = this.req.headers['if-none-match']
  let pkg = yield packages(this.metric).get(name, etag)
  if (pkg === 304) {
    this.status = 304
    return
  }
  if (pkg === 404) {
    this.status = 404
    this.body = {error: 'no such package available'}
    return
  }
  let cloudfront = this.headers['user-agent'] === 'Amazon CloudFront'
  packages(this.metric).rewriteTarballURLs(pkg, cloudfront ? config.cloudfrontHost : this.headers.host)
  this.set('ETag', pkg.etag)
  this.set('Cache-Control', `public, max-age=${config.cache.packageTTL}`)
  this.body = pkg
}))

// get package tarball with sha
app.use(r.get('/:name/-/:filename/:sha', function * (name, filename, sha) {
  newrelic.setTransactionName(':name/-/:filename/:sha')
  let tarball = yield tarballs(this.metric).get(name, filename, sha)
  if (!tarball) {
    this.status = 404
    this.body = {error: 'no tarball found'}
    return
  }
  this.set('Content-Length', tarball.size)
  this.set('Cache-Control', `public, max-age=${config.cache.tarballTTL}`)
  this.body = tarball
}))

// get package tarball with sha
app.use(r.get('/:scope/:name/-/:filename/:sha', function * (scope, name, filename, sha) {
  newrelic.setTransactionName(':scope/:name/-/:filename/:sha')
  let tarball = yield tarballs(this.metric).get(`${scope}/${name}`, filename, sha)
  if (!tarball) {
    this.status = 404
    this.body = {error: 'no tarball found'}
    return
  }
  this.set('Content-Length', tarball.size)
  this.set('Cache-Control', `public, max-age=${config.cache.tarballTTL}`)
  this.body = tarball
}))

// get package tarball without sha
app.use(r.get('/:name/-/:filename', function * (name, filename) {
  newrelic.setTransactionName(':name/-/:filename')
  let ext = path.extname(filename)
  filename = path.basename(filename, ext)
  this.redirect(`/${name}/-/${filename}/a${ext}`)
}))

// login
app.use(r.put('/-/user/:user', function * () {
  newrelic.setTransactionName('-/user/:user')
  let auth = yield user.authenticate(yield parse(this))
  if (auth) {
    this.status = 201
    this.body = {token: auth}
  } else {
    this.status = 401
    this.body = {error: 'invalid credentials'}
  }
}))

// authenticate
app.use(function * (next) {
  if (!this.headers.authorization) {
    this.status = 401
    this.body = {error: 'no credentials provided'}
    return
  }
  let token = this.headers.authorization.split(' ')[1]
  this.username = yield user.findByToken(token)
  if (!this.username) {
    this.status = 401
    this.body = {error: 'invalid credentials'}
    return
  }
  yield next
})

// whoami
app.use(r.get('/-/whoami', function * () {
  newrelic.setTransactionName('-/whoami')
  this.body = {username: this.username}
}))

// npm publish
app.use(r.put('/:name', function * () {
  newrelic.setTransactionName(':name')
  let pkg = yield parse(this)
  try {
    yield packages(this.metric).upload(pkg)
    this.body = yield packages(this.metric).get(pkg.name)
  } catch (err) {
    if (err === packages(this.metric).errors.versionExists) {
      this.body = {error: err.toString()}
      this.status = 409
    } else {
      throw err
    }
  }
}))

module.exports = app
if (!module.parent) {
  app.listen(app.port, function () {
    console.error(`${app.name} listening on port ${app.port} [${app.env}]`)
  })
}
<commit_msg>fix 404s<commit_after>'use strict'

if (!process.env.NEW_RELIC_LICENSE_KEY) process.env.NEW_RELIC_ENABLED = 'false'
process.env.NEW_RELIC_LOG = 'stdout'

let koa = require('koa')
let compress = require('koa-compress')
let r = require('koa-route')
let newrelic = require('newrelic')
let parse = require('co-body')
let fs = require('fs')
let packages = require('./lib/packages')
let tarballs = require('./lib/tarballs')
let config = require('./lib/config')
let user = require('./lib/user')
let rollbar = require('rollbar')
let path = require('path')
let app = koa()

if (config.rollbar) {
  rollbar.init(config.rollbar, {
    environment: process.env.NODE_ENV,
    codeVersion: process.env.HEROKU_SLUG_COMMIT,
    host: process.env.HEROKU_APP_NAME,
    scrubHeaders: ['authorization']
  })
  rollbar.handleUncaughtExceptions(config.rollbar)
}

app.name = 'elephant'
app.port = config.port

app.use(require('./logger'))
app.use(compress())

// static root page
app.use(r.get('/', function * () {
  newrelic.setTransactionName('')
  this.type = 'text/html'
  this.body = fs.createReadStream(path.join(__dirname, '/public/index.html'))
}))

// ping
app.use(r.get('/-/ping', function * () {
  newrelic.setTransactionName('-/ping')
  this.body = {}
}))

// error middleware
app.use(function * (next) {
  try { yield next } catch (err) {
    newrelic.noticeError(err)
    if (config.rollbar) rollbar.handleError(err, this.request)
    this.status = err.status || 500
    this.body = {error: err.message}
    this.app.emit('error', err, this)
  }
})

// get package metadata
app.use(r.get('/:name', function * (name) {
  newrelic.setTransactionName(':name')
  let etag = this.req.headers['if-none-match']
  let pkg = yield packages(this.metric).get(name, etag)
  if (pkg === 304) {
    this.status = 304
    return
  }
  if (pkg === 404) {
    this.status = 404
    this.body = {error: 'no such package available'}
    return
  }
  let cloudfront = this.headers['user-agent'] === 'Amazon CloudFront'
  packages(this.metric).rewriteTarballURLs(pkg, cloudfront ? config.cloudfrontHost : this.headers.host)
  this.set('ETag', pkg.etag)
  this.set('Cache-Control', `public, max-age=${config.cache.packageTTL}`)
  this.body = pkg
}))

// get package tarball with sha
app.use(r.get('/:name/-/:filename/:sha', function * (name, filename, sha) {
  newrelic.setTransactionName(':name/-/:filename/:sha')
  let tarball = yield tarballs(this.metric).get(name, filename, sha)
  if (!tarball) {
    this.status = 404
    this.body = {error: 'no tarball found'}
    return
  }
  this.set('Content-Length', tarball.size)
  this.set('Cache-Control', `public, max-age=${config.cache.tarballTTL}`)
  this.body = tarball
}))

// get package tarball with sha
app.use(r.get('/:scope/:name/-/:filename/:sha', function * (scope, name, filename, sha) {
  newrelic.setTransactionName(':scope/:name/-/:filename/:sha')
  let tarball = yield tarballs(this.metric).get(`${scope}/${name}`, filename, sha)
  if (!tarball) {
    this.status = 404
    this.body = {error: 'no tarball found'}
    return
  }
  this.set('Content-Length', tarball.size)
  this.set('Cache-Control', `public, max-age=${config.cache.tarballTTL}`)
  this.body = tarball
}))

// get package tarball without sha
app.use(r.get('/:name/-/:filename', function * (name, filename) {
  newrelic.setTransactionName(':name/-/:filename')
  let ext = path.extname(filename)
  filename = path.basename(filename, ext)
  this.redirect(`/${name}/-/${filename}/a${ext}`)
}))

// login
app.use(r.put('/-/user/:user', function * () {
  newrelic.setTransactionName('-/user/:user')
  let auth = yield user.authenticate(yield parse(this))
  if (auth) {
    this.status = 201
    this.body = {token: auth}
  } else {
    this.status = 401
    this.body = {error: 'invalid credentials'}
  }
}))

// authenticate
app.use(function * (next) {
  const unauthorized = new Error('unauthorized')
  if (this.headers.authorization) {
    let token = this.headers.authorization.split(' ')[1]
    this.username = yield user.findByToken(token)
  }
  this.authenticated = () => {
    if (!this.username) throw unauthorized
  }
  try {
    yield next
  } catch (err) {
    if (err !== unauthorized) throw err
    this.status = 401
    this.body = {error: 'invalid credentials'}
  }
})

// whoami
app.use(r.get('/-/whoami', function * () {
  this.authenticated()
  newrelic.setTransactionName('-/whoami')
  this.body = {username: this.username}
}))

// npm publish
app.use(r.put('/:name', function * () {
  this.authenticated()
  newrelic.setTransactionName(':name')
  let pkg = yield parse(this)
  try {
    yield packages(this.metric).upload(pkg)
    this.body = yield packages(this.metric).get(pkg.name)
  } catch (err) {
    if (err === packages(this.metric).errors.versionExists) {
      this.body = {error: err.toString()}
      this.status = 409
    } else {
      throw err
    }
  }
}))

module.exports = app
if (!module.parent) {
  app.listen(app.port, function () {
    console.error(`${app.name} listening on port ${app.port} [${app.env}]`)
  })
}
<|endoftext|>


<commit_before>var express = require('express'),
    stylus = require('stylus'),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');

var env = process.env.NODE_ENV || 'development';
var port = 3030;

var app = express();

app.set('view engine', 'jade');
app.set('views', __dirname + '/server/views/');

app.use(bodyParser());
app.use(stylus.middleware({
    src: __dirname + '/public',
    compile: function(str, path) {
        return stylus(str).set('filename', path);
    }
}));
app.use(express.static(__dirname + '/public'));

mongoose.connect('mongodb://localhost/novCraftDb');
var db = mongoose.connection;

db.once('open', function(err) {
    if(err) {
        console.log('Database could not be opened' + err);
        return;
    }

    console.log('Database up and running');
});

db.on('error', function(err) {
    console.log('Database error ' + err);
});

var messageSchema = mongoose.Schema({
    message: String
});

var Message = mongoose.model('Message', messageSchema);

var messageFromDatabase;

Message.remove({}).exec(function(err) {
    if (err) {
        console.log('Messages could not be cleared' + err);
        return;
    }

    // adds the message after everything is deleted
    Message.create({ message: 'Hi from Mongoose' })
        .then(function(model) {
            messageFromDatabase = model.message;
        });
});

app.get('/partials/:partialName', function(req, res) {
    res.render('partials/' + req.params.partialName);
});

app.get('*', function(req, res) {
    res.render('index', {message: messageFromDatabase});
});

console.log('Server running on port '+ port +' ...');
app.listen(port);<commit_msg>Check console commits<commit_after>var express = require('express'),
    stylus = require('stylus'),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');

var env = process.env.NODE_ENV || 'development';
var port = 3030;

var app = express();

app.set('view engine', 'jade');
app.set('views', __dirname + '/server/views/');

app.use(bodyParser());
app.use(stylus.middleware({
    src: __dirname + '/public',
    compile: function(str, path) {
        return stylus(str).set('filename', path);
    }
}));
app.use(express.static(__dirname + '/public'));

mongoose.connect('mongodb://localhost/novCraftDb');
var db = mongoose.connection;

db.once('open', function(err) {
    if(err) {
        console.log('Database could not be opened' + err);
        return;
    }

    console.log('Database up and running');
});

db.on('error', function(err) {
    console.log('Database error ' + err);
});

var messageSchema = mongoose.Schema({
    message: String
});

var Message = mongoose.model('Message', messageSchema);
var messageFromDatabase;

Message.remove({}).exec(function(err) {
    if (err) {
        console.log('Messages could not be cleared' + err);
        return;
    }

    // adds the message after everything is deleted
    Message.create({ message: 'Hi from Mongoose' })
        .then(function(model) {
            messageFromDatabase = model.message;
        });
});

app.get('/partials/:partialName', function(req, res) {
    res.render('partials/' + req.params.partialName);
});

app.get('*', function(req, res) {
    res.render('index', {message: messageFromDatabase});
});

console.log('Server running on port '+ port +' ...');
app.listen(port);<|endoftext|>


<commit_before>/**
 * @author vHawk / https://github.com/vHawk/
 */

import { Vector3, Matrix4 } from '../../../build/three.module.js';

const inverseProjectionMatrix = new Matrix4();

export default class Frustum {

	constructor( data ) {

		data = data || {};

		this.projectionMatrix = data.projectionMatrix;
		this.maxFar = data.maxFar || 10000;

		this.vertices = {
			near: [
				new Vector3(),
				new Vector3(),
				new Vector3(),
				new Vector3()
			],
			far: [
				new Vector3(),
				new Vector3(),
				new Vector3(),
				new Vector3()
			]
		};

	}

	getViewSpaceVertices() {

		const maxFar = this.maxFar;
		const projectionMatrix = this.projectionMatrix;
		const isOrthographic = projectionMatrix.elements[ 2 * 4 + 3 ] === 0;

		inverseProjectionMatrix.getInverse( this.projectionMatrix );

		// 3 --- 0  vertices.near/far order
		// |     |
		// 2 --- 1
		// clip space spans from [-1, 1]

		this.vertices.near[ 0 ] = new Vector3( 1, 1, - 1 );
		this.vertices.near[ 1 ] = new Vector3( 1, - 1, - 1 );
		this.vertices.near[ 2 ] = new Vector3( - 1, - 1, - 1 );
		this.vertices.near[ 3 ] = new Vector3( - 1, 1, - 1 );
		this.vertices.near.forEach( function( v ) {

			v.applyMatrix4( inverseProjectionMatrix );

		} );

		this.vertices.far[ 0 ] = new Vector3( 1, 1, 1 );
		this.vertices.far[ 1 ] = new Vector3( 1, - 1, 1 );
		this.vertices.far[ 2 ] = new Vector3( - 1, - 1, 1 );
		this.vertices.far[ 3 ] = new Vector3( - 1, 1, 1 );
		this.vertices.far.forEach( function( v ) {

			v.applyMatrix4( inverseProjectionMatrix );

			const absZ = Math.abs( v.z );
			if ( isOrthographic ) {

				v.z *= Math.min( maxFar / absZ, 1.0 );

			} else {

				v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) );

			}

		} );

		return this.vertices;

	}

	split( breaks ) {

		const result = [];

		for ( let i = 0; i < breaks.length; i ++ ) {

			const cascade = new Frustum();

			if ( i === 0 ) {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.near[ j ] = this.vertices.near[ j ].clone();

				}

			} else {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.near[ j ] = new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] );

				}

			}

			if ( i === breaks - 1 ) {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.far[ j ] = this.vertices.far[ j ].clone();

				}

			} else {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.far[ j ] = new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] );

				}

			}

			result.push( cascade );

		}

		return result;

	}

	toSpace( cameraMatrix ) {

		const result = new Frustum();
		const point = new Vector3();

		for ( var i = 0; i < 4; i ++ ) {

			point.set( this.vertices.near[ i ].x, this.vertices.near[ i ].y, this.vertices.near[ i ].z );
			point.applyMatrix4( cameraMatrix );
			result.vertices.near[ i ] = point.clone();

			point.set( this.vertices.far[ i ].x, this.vertices.far[ i ].y, this.vertices.far[ i ].z );
			point.applyMatrix4( cameraMatrix );
			result.vertices.far[ i ] = point.clone();

		}

		return result;

	}

}
<commit_msg>Use cached vectors<commit_after>/**
 * @author vHawk / https://github.com/vHawk/
 */

import { Vector3, Matrix4 } from '../../../build/three.module.js';

const inverseProjectionMatrix = new Matrix4();

export default class Frustum {

	constructor( data ) {

		data = data || {};

		this.projectionMatrix = data.projectionMatrix;
		this.maxFar = data.maxFar || 10000;

		this.vertices = {
			near: [
				new Vector3(),
				new Vector3(),
				new Vector3(),
				new Vector3()
			],
			far: [
				new Vector3(),
				new Vector3(),
				new Vector3(),
				new Vector3()
			]
		};

	}

	getViewSpaceVertices() {

		const maxFar = this.maxFar;
		const projectionMatrix = this.projectionMatrix;
		const isOrthographic = projectionMatrix.elements[ 2 * 4 + 3 ] === 0;

		inverseProjectionMatrix.getInverse( this.projectionMatrix );

		// 3 --- 0  vertices.near/far order
		// |     |
		// 2 --- 1
		// clip space spans from [-1, 1]

		this.vertices.near[ 0 ].set( 1, 1, - 1 );
		this.vertices.near[ 1 ].set( 1, - 1, - 1 );
		this.vertices.near[ 2 ].set( - 1, - 1, - 1 );
		this.vertices.near[ 3 ].set( - 1, 1, - 1 );
		this.vertices.near.forEach( function( v ) {

			v.applyMatrix4( inverseProjectionMatrix );

		} );

		this.vertices.far[ 0 ].set( 1, 1, 1 );
		this.vertices.far[ 1 ].set( 1, - 1, 1 );
		this.vertices.far[ 2 ].set( - 1, - 1, 1 );
		this.vertices.far[ 3 ].set( - 1, 1, 1 );
		this.vertices.far.forEach( function( v ) {

			v.applyMatrix4( inverseProjectionMatrix );

			const absZ = Math.abs( v.z );
			if ( isOrthographic ) {

				v.z *= Math.min( maxFar / absZ, 1.0 );

			} else {

				v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) );

			}

		} );

		return this.vertices;

	}

	split( breaks ) {

		const result = [];

		for ( let i = 0; i < breaks.length; i ++ ) {

			const cascade = new Frustum();

			if ( i === 0 ) {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.near[ j ].copy( this.vertices.near[ j ] );

				}

			} else {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.near[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] );

				}

			}

			if ( i === breaks - 1 ) {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.far[ j ].copy( this.vertices.far[ j ] );

				}

			} else {

				for ( let j = 0; j < 4; j ++ ) {

					cascade.vertices.far[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] );

				}

			}

			result.push( cascade );

		}

		return result;

	}

	toSpace( cameraMatrix ) {

		const result = new Frustum();
		const point = new Vector3();

		for ( var i = 0; i < 4; i ++ ) {

			point.set( this.vertices.near[ i ].x, this.vertices.near[ i ].y, this.vertices.near[ i ].z );
			point.applyMatrix4( cameraMatrix );
			result.vertices.near[ i ] = point.clone();

			point.set( this.vertices.far[ i ].x, this.vertices.far[ i ].y, this.vertices.far[ i ].z );
			point.applyMatrix4( cameraMatrix );
			result.vertices.far[ i ] = point.clone();

		}

		return result;

	}

}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var FlightAware = require('flightaware.js');

// Get access to the FlightAware 2.0 client API ...
// See http://flightaware.com/commercial/flightxml for username/apiKey ...
var username = 'your-flightaware-username';
var apiKey = 'your-flightaware-apiKey';
var client = new FlightAware(username, apiKey);

var app = express();
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/api/Arrived/:airport', function(req, res) {
    client.Arrived({
        airport: req.params.airport,
    }, function(err, result) {
        if (err) return res.send(err);
        res.json(result);
    });
});

var port = 8000;
app.listen(port, function() {
  console.log("Node app is running at http://localhost:" + port);
});

<commit_msg>Use a config file for the FlightAware keys.<commit_after>var express = require('express');
var path = require('path');
var FlightAware = require('flightaware.js');
var config = require('./config');

// Get access to the FlightAware 2.0 client API ...
// See http://flightaware.com/commercial/flightxml for username/apiKey ...
var client = new FlightAware(config.username, config.apiKey);

var app = express();
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/api/Arrived/:airport', function(req, res) {
    client.Arrived({
        airport: req.params.airport,
    }, function(err, result) {
        if (err) return res.send(err);
        res.json(result);
    });
});

var port = 8000;
app.listen(port, function() {
  console.log("Node app is running at http://localhost:" + port);
});

<|endoftext|>


<commit_before>var express = require('express');
var OAuth2  = require('oauth').OAuth2;
var Twitter = require('twitter');

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.OPENSHIFT_INTERNAL_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.OPENSHIFT_INTERNAL_PORT || 8080;
var app = express();
var client;

var twitterConsumerKey = process.env.TWITTER_CONSUMER_KEY;
var twitterConsumerSecret = process.env.TWITTER_CONSUMER_SECRET;

var oauth2 = new OAuth2(
    twitterConsumerKey,
    twitterConsumerSecret,
    'https://api.twitter.com/',
    null,
    'oauth2/token',
    null);

var access_options = { 'grant_type': 'client_credentials' };
oauth2.getOAuthAccessToken('', access_options, function (err, access_token) {
    if (err) throw err;

    client = new Twitter({
        consumer_key: process.env.TWITTER_CONSUMER_KEY,
        consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
        bearer_token: access_token
    });
});

app.get('/', function (req, res) {
    if (!client) return;

    client.get('search/tweets', {q: 'to:SH_IoT'}, function(error, tweets, response) {
        if (err) throw err;

        var texts = [];
        tweets.statuses.forEach(function (status) {
            texts.push(status.text);
        });
        res.json(texts);
    });
});

var server = app.listen(port, ipaddress, function () {
    console.log('Example app listening at http://%s:%s', ipaddress, port);
});

<commit_msg>Fix error handling for the client<commit_after>var express = require('express');
var OAuth2  = require('oauth').OAuth2;
var Twitter = require('twitter');

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.OPENSHIFT_INTERNAL_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.OPENSHIFT_INTERNAL_PORT || 8080;
var app = express();
var client;

var twitterConsumerKey = process.env.TWITTER_CONSUMER_KEY;
var twitterConsumerSecret = process.env.TWITTER_CONSUMER_SECRET;

var oauth2 = new OAuth2(
    twitterConsumerKey,
    twitterConsumerSecret,
    'https://api.twitter.com/',
    null,
    'oauth2/token',
    null);

var access_options = { 'grant_type': 'client_credentials' };
oauth2.getOAuthAccessToken('', access_options, function (err, access_token) {
    if (err) throw err;

    client = new Twitter({
        consumer_key: process.env.TWITTER_CONSUMER_KEY,
        consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
        bearer_token: access_token
    });
});

app.get('/', function (req, res) {
    if (!client) return;

    client.get('search/tweets', {q: 'to:SH_IoT'}, function(err, tweets, response) {
        if (err) throw err;

        var texts = [];
        tweets.statuses.forEach(function (status) {
            texts.push(status.text);
        });
        res.json(texts);
    });
});

var server = app.listen(port, ipaddress, function () {
    console.log('Example app listening at http://%s:%s', ipaddress, port);
});

<|endoftext|>


<commit_before>var http = require('http'),
    path = require('path'),
    os = require('os'),
    fs = require('fs'),
	url = require('url'),
    tty = require('tty'),
    colors = require('colors'),
    _ = require('underscore'),
    async = require('async'),
    extend = require('node.extend'),
    indexPath = path.resolve(path.join(__dirname, 'templates/index.mtpl'));

var contentType = {
    'html': 'text/html',
    'css': 'text/css',
    'js': 'application/javascript'
};

var defaultHeaders = {
    'Content-Type': 'text/plain',
    'Cache-Control': 'must-revalidate, no-cache'
};

var writeHead = function(req, resp, statusCode, headers) {
    var d = new Date(),
        seconds = d.getSeconds() < 10? '0' + d.getSeconds() : d.getSeconds(),
        datestring = d.getHours() + ':' + d.getMinutes() + ':' + seconds,
        line = datestring + ' [' + statusCode + ']: ' + req.url,
        colorized = line;
    if (tty.isatty(process.stdout.fd)) {
        colorized = (+statusCode) >= 500? line.red.bold :
                    (+statusCode) >= 400? line.red : line;
    }
    console.log(colorized);
    resp.writeHead(statusCode, headers);
};

var readIndex = (function() {
    var compiled, error;
    return function(req, resp, indexPath, callback) {
        if (typeof compiled === 'undefined') {
			fs.readFile(indexPath, 'utf8', function(err, file) {
				callback(error = err, compiled = _.template(file || ''));
			});
        } else {
			callback(error, compiled);
        }
    };
})();

var serveError = function(req, resp, err) {
    writeHead(req, resp, 500, defaultHeaders);
    resp.write(err + '\n');
    resp.end();
};

var serve404 = function(req, resp) {
    writeHead(req, resp, 404, defaultHeaders);
    resp.end('not found');
};

var serveFile = function(req, resp, filename) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            serveError(req, resp, err);
            return;
        }
        writeHead(req, resp, 200, _.extend({}, defaultHeaders, {
            'Content-Type': contentType[path.extname(filename).slice(1)],
            'Content-Length': data.length
        }));
        resp.write(data);
        resp.end();
    });
};

var serveIndex = function(req, resp, filename, config, extra) {
    readIndex(req, resp, indexPath, function(err, compiled) {
        var content, csiPath = path.join(config.baseUrl, config.paths.csi),
			isTest = /test/i.test(req.url.split('?')[0]);

        if (err) {
            serveError(req, resp, err);
			return;
        }

		content = compiled({
			isTest: isTest,
			qunitCss: path.join(csiPath, 'qunit.css'),
			qunitJs: path.join(csiPath, 'qunit.js'),
			requireJs: path.join(csiPath, 'require.js'),
			extra: extra || '',
			config: JSON.stringify(config, null, " "),
			jsPath: filename
		});

        writeHead(req, resp, 200, _.extend({}, defaultHeaders, {
            'Content-Type': contentType.html,
            'Content-Length': Buffer.byteLength(content)
        }));
        resp.write(content);
        resp.end();
    });
};

exports.createServer = function(staticDir, config, extra) {
	staticDir = typeof staticDir === 'undefined'? './' : staticDir;
	config = extend(true, {
		baseUrl: '/' + path.basename(path.resolve(staticDir))
	}, config || {});
	return http.createServer(function(req, resp) {
		var filename, u = url.parse(req.url, true),
			requested = path.join(config.baseUrl || '', u.pathname + '.js');
		if (!/\.[a-z0-9]+$/i.test(u.pathname)) {
			filename = path.join(path.dirname(staticDir), requested);
			path.exists(filename, function(exists) {
				if (exists) {
					serveIndex(req, resp, requested, config, extra);
				} else {
					serve404(req, resp);
				}
			});
		} else {
			filename = path.join(path.dirname(staticDir), u.pathname);
			serveFile(req, resp, filename);
		}
	});
};
<commit_msg>fixed server bug where 404 was reported as 500<commit_after>var http = require('http'),
    path = require('path'),
    os = require('os'),
    fs = require('fs'),
	url = require('url'),
    tty = require('tty'),
    colors = require('colors'),
    _ = require('underscore'),
    async = require('async'),
    extend = require('node.extend'),
    indexPath = path.resolve(path.join(__dirname, 'templates/index.mtpl'));

var contentType = {
    'html': 'text/html',
    'css': 'text/css',
    'js': 'application/javascript'
};

var defaultHeaders = {
    'Content-Type': 'text/plain',
    'Cache-Control': 'must-revalidate, no-cache'
};

var writeHead = function(req, resp, statusCode, headers) {
    var d = new Date(),
        seconds = d.getSeconds() < 10? '0' + d.getSeconds() : d.getSeconds(),
        datestring = d.getHours() + ':' + d.getMinutes() + ':' + seconds,
        line = datestring + ' [' + statusCode + ']: ' + req.url,
        colorized = line;
    if (tty.isatty(process.stdout.fd)) {
        colorized = (+statusCode) >= 500? line.red.bold :
                    (+statusCode) >= 400? line.red : line;
    }
    console.log(colorized);
    resp.writeHead(statusCode, headers);
};

var readIndex = (function() {
    var compiled, error;
    return function(req, resp, indexPath, callback) {
        if (typeof compiled === 'undefined') {
			fs.readFile(indexPath, 'utf8', function(err, file) {
				callback(error = err, compiled = _.template(file || ''));
			});
        } else {
			callback(error, compiled);
        }
    };
})();

var serveError = function(req, resp, err) {
    writeHead(req, resp, 500, defaultHeaders);
    resp.write(err + '\n');
    resp.end();
};

var serve404 = function(req, resp) {
    writeHead(req, resp, 404, defaultHeaders);
    resp.end('not found');
};

var serveFile = function(req, resp, filename) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            if (err.code === 'ENOENT') {
                serve404(req, resp);
            } else {
                serveError(req, resp, err);
            }
            return;
        }
        writeHead(req, resp, 200, _.extend({}, defaultHeaders, {
            'Content-Type': contentType[path.extname(filename).slice(1)],
            'Content-Length': data.length
        }));
        resp.write(data);
        resp.end();
    });
};

var serveIndex = function(req, resp, filename, config, extra) {
    readIndex(req, resp, indexPath, function(err, compiled) {
        var content, csiPath = path.join(config.baseUrl, config.paths.csi),
			isTest = /test/i.test(req.url.split('?')[0]);

        if (err) {
            serveError(req, resp, err);
			return;
        }

		content = compiled({
			isTest: isTest,
			qunitCss: path.join(csiPath, 'qunit.css'),
			qunitJs: path.join(csiPath, 'qunit.js'),
			requireJs: path.join(csiPath, 'require.js'),
			extra: extra || '',
			config: JSON.stringify(config, null, " "),
			jsPath: filename
		});

        writeHead(req, resp, 200, _.extend({}, defaultHeaders, {
            'Content-Type': contentType.html,
            'Content-Length': Buffer.byteLength(content)
        }));
        resp.write(content);
        resp.end();
    });
};

exports.createServer = function(staticDir, config, extra) {
	staticDir = typeof staticDir === 'undefined'? './' : staticDir;
	config = extend(true, {
		baseUrl: '/' + path.basename(path.resolve(staticDir))
	}, config || {});
	return http.createServer(function(req, resp) {
		var filename, u = url.parse(req.url, true),
			requested = path.join(config.baseUrl || '', u.pathname + '.js');
		if (!/\.[a-z0-9]+$/i.test(u.pathname)) {
			filename = path.join(path.dirname(staticDir), requested);
			path.exists(filename, function(exists) {
				if (exists) {
					serveIndex(req, resp, requested, config, extra);
				} else {
					serve404(req, resp);
				}
			});
		} else {
			filename = path.join(path.dirname(staticDir), u.pathname);
			serveFile(req, resp, filename);
		}
	});
};
<|endoftext|>


<commit_before>const log = require('electron-log/main');
const { Util } = require('./util');

const megabyte = 1048576;

log.transports.file.format = "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.console.format = "{text}";
log.transports.file.maxSize = 4 * megabyte;

if (Util.isDevMode()) {
    log.transports.file.level = 'debug';
    log.transports.console.level = 'debug';
} else {
    log.transports.file.level = 'warn';
    log.transports.console.level = false;
}

log.filename = function() {
    return log.transports.file.findLogPath();
}

// Use log.info("message")
//     log.warn("message")
//     log.error("message")
//     log.debug("message")

module.exports = log;
<commit_msg>Set log level to info outside of dev<commit_after>const log = require('electron-log/main');
const { Util } = require('./util');

const megabyte = 1048576;

log.transports.file.format = "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.console.format = "{text}";
log.transports.file.maxSize = 4 * megabyte;

if (Util.isDevMode()) {
    log.transports.file.level = 'debug';
    log.transports.console.level = 'debug';
} else {
    log.transports.file.level = 'info';
    log.transports.console.level = false;
}

log.filename = function() {
    return log.transports.file.findLogPath();
}

// Use log.info("message")
//     log.warn("message")
//     log.error("message")
//     log.debug("message")

module.exports = log;
<|endoftext|>