<commit_before>var ws = require("nodejs-websocket");
var https = require("https");
var crypto = require("crypto");
var winston = require('winston');

// User credentials
var gameonUID = (process.env.GAMEONUID|| '');
var gameonAPIKey = (process.env.GAMEONUID|| '');

// Room Details
// Your room's name
var theRoomName = '';
var fullName = 'This is a CF in bluemix';
// The hostname of your CF applicaiton
var endpointip = ('yourhostname' || 'localhost');
// Automatically retrieves the port of your CF
var port = (process.env.CF_INSTANCE_PORT || 3000);

var logger = new winston.Logger({
  level: 'debug',
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: './access.log' })
  ]
});

var registration = {
  "fullName": fullName,
  "name": theRoomName,
  "connectionDetails": {
    "type": "websocket",
    "target": "ws://"+ endpointip,
  },
  "doors":
    {
      "n": "North",
      "s": "South",
      "e": "East",
      "w": "West",
    },
}

function register()
{
  logger.info("Registering with the concierge...")

  var body = JSON.stringify(registration)
  var now = new Date()
  var timestamp = new Date(now - 75000).toISOString()
  var uidParams = 'id=' + gameonUID
  var queryParams = 'stamp=' + timestamp
  logger.info("Now!: " + now)
  logger.info("Timestamp: " + timestamp)
  logger.info("Query Parameters: " + queryParams)

  logger.debug("Registration object: " + JSON.stringify(registration))

  var bodyHash = crypto.createHash('sha256')
  bodyHash = bodyHash.update(body).digest('base64')
  console.log("BODY HASH " + bodyHash)

  var allParams = gameonUID+timestamp+bodyHash
  var hash = crypto.createHmac('sha256', gameonAPIKey).update(allParams).digest('base64')

  console.log("HASH : " + hash)

  var options = {
    host: 'game-on.org',
    path: '/map/v1/sites',
    method: 'POST',
    headers: {
      'Content-Type':'application/json',
      'gameon-id':gameonUID,
      'gameon-date': timestamp,
      'gameon-sig-body': bodyHash,
      'gameon-signature': hash
    }
  };

  logger.debug("Options: " + JSON.stringify(options))

  callback = function(response) {
    var str = ''
    response.on('data', function (chunk) {
      str += chunk;
    });

    response.on('end', function () {
      logger.debug("Received response: " + str);
    });
  }
  var req = https.request(options, callback);

  req.write(JSON.stringify(registration));
  req.end();
}

setInterval(register, 60000)
register()

var wsServer = ws.createServer(function (conn) {
  conn.on("text", function (incoming) {
    logger.debug("RECEIVED: " + incoming)
    var typeEnd = incoming.indexOf(',')
    var targetEnd = incoming.indexOf(',', typeEnd+1)

    var messageType = incoming.substr(0,typeEnd)
    var target = incoming.substr(typeEnd+1, targetEnd-typeEnd-1)
    var objectStr = incoming.substr(targetEnd+1)
    var object = {}
    try
    {
      object = JSON.parse(objectStr)
    }
    catch (err)
    {
      logger.error("Got improper json: " + objectStr)
    }

    logger.info("Parsed a message of type \"" + messageType + "\" sent to target \"" + target + "\".")

    //if (target != theRoomName)
    //  return

    if (messageType === "roomHello")
    {
      logger.debug("In roomHello")
      sayHello(conn, object.userId, object.username)
    }
    else if (messageType === "room")
    {
      if (object.content.indexOf('/') == 0)
      {
        parseCommand(conn, object.userId, object.username, object.content)
      }
      else
      {
        sendChatMessage(conn, object.username, object.content)
      }
    }
    else if (messageType === "roomGoodbye")
    {
      sayGoodbye(conn, object.userId, object.username)
    }
    else
    {
      sendUnknownType(conn, object.userId, object.username, messageType)
    }
  })
  conn.on("close", function (code, reason) {
    logger.debug("Connection closed.")
  })
}).listen(port);

function sendUnknownType(conn, target, username, messageType)
{
  logger.debug("Target \"" + target + "\" sent unknown message type \"" + messageType + "\".")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 225,
    content: {
    }
  }

  messageObject.content[target] = "'" + messageType +"' is not a known message type!"

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendChatMessage(conn, username, content) {
  logger.info(username + " sent chat message \"" + content + "\"")
  var responseObject = {
          type: "chat",
          username: username,
          content: content,
          bookmark: 92
        }

        var sendMessageType = "player"
        var sendTarget = "*"

        var messageText = sendMessageType + "," +
                  sendTarget + "," +
                  JSON.stringify(responseObject)

    broadcast(messageText)
}

function parseCommand(conn, target, username, content) {

  if (content.substr(1,3) == "go ")
  {
    parseGoCommand(conn, target, username, content)
  }
  /*else if (content.substr(1, 5) == "exits")
  {
    sendExits(conn, target, username)
  }
  else if (content.substr(1, 4) == "help")
  {
    sendHelp(conn, target, username)
  }*/
  else if (content.substr(1, 9) == "inventory")
  {
    sendInventory(conn, target, username)
  }
  else if (content.substr(1, 7) == "examine")
  {
    sendExamine(conn, target, username)
  }
  else
  {
    sendUnknownCommand(conn, target, content)
  }
}

function sendExits(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for exits.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "exits",
    bookmark: 2222,
    content: {
      W: "You see a door to the wally west that looks like it goes somewhere."
    }
  }

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendHelp(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for info.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "The following commands are supported: [/help, /go, /exits, /inventory, /examine]"

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendInventory(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for inventory.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "You may have been carrying something, but you lost it cause everything is so asynchronous."

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendExamine(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for examination.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "There's nothing in here to really examine."

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function parseGoCommand(conn, target, username, content)
{
  var exitName = content.substr(4)

  logger.info("Player \"" + username + "\" wants to go direction \"" + exitName + "\"")

  if(exitName.toUpperCase() === "NORTH"){
    exitId = 'n'
  }
  else if(exitName.toUpperCase() == "SOUTH"){
    exitId = 's'
  }
  else if(exitName.toUpperCase() == "EAST"){
    exitId = 'e'
  }
  else if(exitName.toUpperCase() == "WEST"){
    exitId = 'w'
  }

  logger.debug("Registration: " + registration.doors[exitId])

  if(registration.doors[exitId]){
    logger.info("That direction exists, telling \"" + username + "\" that they've gone that direction.")
    var sendTarget = target
    var sendMessageType = "playerLocation"
    var messageObject = {
      "type": "exit",
      "exitId": exitId,
      "content": "You head " + exitName,
      "bookmark": 6019
    }

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(messageObject)

    conn.sendText(messageText)

  }
  else
  {
    logger.info("That direction wasn't found; we're telling the user.")
    var sendTarget = target
    var sendMessageType = "player"
    var messageObject = {
      type: "event",
      content: {

      },
      bookmark: 5302
    }

    messageObject.content[target] = "There isn't an exit with that name, genius."

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(messageObject)

    conn.sendText(messageText)
  }

}

function sendUnknownCommand(conn, target, content) {
  logger.info("Unknown command from user: " + content)
  var responseObject = {
          type: "event",
          "content": {
          }
        }

    responseObject.content[target] = "Node.js looked at your command, and barfed."
        var sendMessageType = "player"
        var sendTarget = target

        var messageText = sendMessageType + "," +
                  sendTarget + "," +
                  JSON.stringify(responseObject)

    conn.sendText(messageText)
}

function sayGoodbye(conn, target, username) {
  logger.debug("Announcing that \"" + username + "\" has left the room.")
  var broadcastMessageType = "player"
  var broadcastMessageTarget = "*"
  var broadcastMessageObject = {
    type: "event",
    content: {
      "*": username + " leaves the room."
    },
    bookmark: 1001
  }
  var broadcastMessage = broadcastMessageType + "," +
              broadcastMessageTarget + "," +
              JSON.stringify(broadcastMessageObject)

  broadcast(broadcastMessage)
}

function sayHello(conn, target, username) {

  logger.info("Saying hello to \"" + target + "\"")
  var responseObject = {
      "type": "location",
      "name": theRoomName,
      "fullName": fullName,
      "description": "This room is filled with little JavaScripts running around everywhere.",
    }

    var sendMessageType = "player"
    var sendTarget = target

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(responseObject)

  conn.sendText(messageText)

  logger.debug("And announcing that \"" + username + "\" has arrived.")
  var broadcastMessageType = "player"
  var broadcastMessageTarget = "*"
  var broadcastMessageObject = {
    type: "event",
    content: {
      "*": username + " enters the room."
    },
    bookmark: 51
  }
  var broadcastMessage = broadcastMessageType + "," +
              broadcastMessageTarget + "," +
              JSON.stringify(broadcastMessageObject)

  broadcast(broadcastMessage)
}

function broadcast(message) {
  wsServer.connections.forEach(function (conn) {
        conn.sendText(message)
    })
}

process.on('uncaughtException', function(err) {
    // handle the error safely
    console.log("UNCAUGHT EXCEPTION! " + err)
})

logger.info("The WebSocket server is listening...")
<commit_msg>API key env variable<commit_after>var ws = require("nodejs-websocket");
var https = require("https");
var crypto = require("crypto");
var winston = require('winston');

// User credentials
var gameonUID = (process.env.GAMEONUID|| '');
var gameonAPIKey = (process.env.GAMEONAPIKEY|| '');

// Room Details
// Your room's name
var theRoomName = '';
var fullName = 'This is a CF in bluemix';
// The hostname of your CF applicaiton
var endpointip = ('yourhostname' || 'localhost');
// Automatically retrieves the port of your CF
var port = (process.env.CF_INSTANCE_PORT || 3000);

var logger = new winston.Logger({
  level: 'debug',
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: './access.log' })
  ]
});

var registration = {
  "fullName": fullName,
  "name": theRoomName,
  "connectionDetails": {
    "type": "websocket",
    "target": "ws://"+ endpointip,
  },
  "doors":
    {
      "n": "North",
      "s": "South",
      "e": "East",
      "w": "West",
    },
}

function register()
{
  logger.info("Registering with the concierge...")

  var body = JSON.stringify(registration)
  var now = new Date()
  var timestamp = new Date(now - 75000).toISOString()
  var uidParams = 'id=' + gameonUID
  var queryParams = 'stamp=' + timestamp
  logger.info("Now!: " + now)
  logger.info("Timestamp: " + timestamp)
  logger.info("Query Parameters: " + queryParams)

  logger.debug("Registration object: " + JSON.stringify(registration))

  var bodyHash = crypto.createHash('sha256')
  bodyHash = bodyHash.update(body).digest('base64')
  console.log("BODY HASH " + bodyHash)

  var allParams = gameonUID+timestamp+bodyHash
  var hash = crypto.createHmac('sha256', gameonAPIKey).update(allParams).digest('base64')

  console.log("HASH : " + hash)

  var options = {
    host: 'game-on.org',
    path: '/map/v1/sites',
    method: 'POST',
    headers: {
      'Content-Type':'application/json',
      'gameon-id':gameonUID,
      'gameon-date': timestamp,
      'gameon-sig-body': bodyHash,
      'gameon-signature': hash
    }
  };

  logger.debug("Options: " + JSON.stringify(options))

  callback = function(response) {
    var str = ''
    response.on('data', function (chunk) {
      str += chunk;
    });

    response.on('end', function () {
      logger.debug("Received response: " + str);
    });
  }
  var req = https.request(options, callback);

  req.write(JSON.stringify(registration));
  req.end();
}

setInterval(register, 60000)
register()

var wsServer = ws.createServer(function (conn) {
  conn.on("text", function (incoming) {
    logger.debug("RECEIVED: " + incoming)
    var typeEnd = incoming.indexOf(',')
    var targetEnd = incoming.indexOf(',', typeEnd+1)

    var messageType = incoming.substr(0,typeEnd)
    var target = incoming.substr(typeEnd+1, targetEnd-typeEnd-1)
    var objectStr = incoming.substr(targetEnd+1)
    var object = {}
    try
    {
      object = JSON.parse(objectStr)
    }
    catch (err)
    {
      logger.error("Got improper json: " + objectStr)
    }

    logger.info("Parsed a message of type \"" + messageType + "\" sent to target \"" + target + "\".")

    //if (target != theRoomName)
    //  return

    if (messageType === "roomHello")
    {
      logger.debug("In roomHello")
      sayHello(conn, object.userId, object.username)
    }
    else if (messageType === "room")
    {
      if (object.content.indexOf('/') == 0)
      {
        parseCommand(conn, object.userId, object.username, object.content)
      }
      else
      {
        sendChatMessage(conn, object.username, object.content)
      }
    }
    else if (messageType === "roomGoodbye")
    {
      sayGoodbye(conn, object.userId, object.username)
    }
    else
    {
      sendUnknownType(conn, object.userId, object.username, messageType)
    }
  })
  conn.on("close", function (code, reason) {
    logger.debug("Connection closed.")
  })
}).listen(port);

function sendUnknownType(conn, target, username, messageType)
{
  logger.debug("Target \"" + target + "\" sent unknown message type \"" + messageType + "\".")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 225,
    content: {
    }
  }

  messageObject.content[target] = "'" + messageType +"' is not a known message type!"

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendChatMessage(conn, username, content) {
  logger.info(username + " sent chat message \"" + content + "\"")
  var responseObject = {
          type: "chat",
          username: username,
          content: content,
          bookmark: 92
        }

        var sendMessageType = "player"
        var sendTarget = "*"

        var messageText = sendMessageType + "," +
                  sendTarget + "," +
                  JSON.stringify(responseObject)

    broadcast(messageText)
}

function parseCommand(conn, target, username, content) {

  if (content.substr(1,3) == "go ")
  {
    parseGoCommand(conn, target, username, content)
  }
  /*else if (content.substr(1, 5) == "exits")
  {
    sendExits(conn, target, username)
  }
  else if (content.substr(1, 4) == "help")
  {
    sendHelp(conn, target, username)
  }*/
  else if (content.substr(1, 9) == "inventory")
  {
    sendInventory(conn, target, username)
  }
  else if (content.substr(1, 7) == "examine")
  {
    sendExamine(conn, target, username)
  }
  else
  {
    sendUnknownCommand(conn, target, content)
  }
}

function sendExits(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for exits.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "exits",
    bookmark: 2222,
    content: {
      W: "You see a door to the wally west that looks like it goes somewhere."
    }
  }

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendHelp(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for info.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "The following commands are supported: [/help, /go, /exits, /inventory, /examine]"

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendInventory(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for inventory.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "You may have been carrying something, but you lost it cause everything is so asynchronous."

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function sendExamine(conn, target, username)
{
  logger.debug("Target \"" + target + "\" asked for examination.")
  var sendTarget = target
  var sendMessageType = "player"
  var messageObject = {
    type: "event",
    bookmark: 2223,
    content: {
    }
  }

  messageObject.content[target] = "There's nothing in here to really examine."

  var messageToSend = sendMessageType + "," +
            sendTarget + "," +
            JSON.stringify(messageObject)

  conn.sendText(messageToSend)
}

function parseGoCommand(conn, target, username, content)
{
  var exitName = content.substr(4)

  logger.info("Player \"" + username + "\" wants to go direction \"" + exitName + "\"")

  if(exitName.toUpperCase() === "NORTH"){
    exitId = 'n'
  }
  else if(exitName.toUpperCase() == "SOUTH"){
    exitId = 's'
  }
  else if(exitName.toUpperCase() == "EAST"){
    exitId = 'e'
  }
  else if(exitName.toUpperCase() == "WEST"){
    exitId = 'w'
  }

  logger.debug("Registration: " + registration.doors[exitId])

  if(registration.doors[exitId]){
    logger.info("That direction exists, telling \"" + username + "\" that they've gone that direction.")
    var sendTarget = target
    var sendMessageType = "playerLocation"
    var messageObject = {
      "type": "exit",
      "exitId": exitId,
      "content": "You head " + exitName,
      "bookmark": 6019
    }

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(messageObject)

    conn.sendText(messageText)

  }
  else
  {
    logger.info("That direction wasn't found; we're telling the user.")
    var sendTarget = target
    var sendMessageType = "player"
    var messageObject = {
      type: "event",
      content: {

      },
      bookmark: 5302
    }

    messageObject.content[target] = "There isn't an exit with that name, genius."

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(messageObject)

    conn.sendText(messageText)
  }

}

function sendUnknownCommand(conn, target, content) {
  logger.info("Unknown command from user: " + content)
  var responseObject = {
          type: "event",
          "content": {
          }
        }

    responseObject.content[target] = "Node.js looked at your command, and barfed."
        var sendMessageType = "player"
        var sendTarget = target

        var messageText = sendMessageType + "," +
                  sendTarget + "," +
                  JSON.stringify(responseObject)

    conn.sendText(messageText)
}

function sayGoodbye(conn, target, username) {
  logger.debug("Announcing that \"" + username + "\" has left the room.")
  var broadcastMessageType = "player"
  var broadcastMessageTarget = "*"
  var broadcastMessageObject = {
    type: "event",
    content: {
      "*": username + " leaves the room."
    },
    bookmark: 1001
  }
  var broadcastMessage = broadcastMessageType + "," +
              broadcastMessageTarget + "," +
              JSON.stringify(broadcastMessageObject)

  broadcast(broadcastMessage)
}

function sayHello(conn, target, username) {

  logger.info("Saying hello to \"" + target + "\"")
  var responseObject = {
      "type": "location",
      "name": theRoomName,
      "fullName": fullName,
      "description": "This room is filled with little JavaScripts running around everywhere.",
    }

    var sendMessageType = "player"
    var sendTarget = target

    var messageText = sendMessageType + "," +
              sendTarget + "," +
              JSON.stringify(responseObject)

  conn.sendText(messageText)

  logger.debug("And announcing that \"" + username + "\" has arrived.")
  var broadcastMessageType = "player"
  var broadcastMessageTarget = "*"
  var broadcastMessageObject = {
    type: "event",
    content: {
      "*": username + " enters the room."
    },
    bookmark: 51
  }
  var broadcastMessage = broadcastMessageType + "," +
              broadcastMessageTarget + "," +
              JSON.stringify(broadcastMessageObject)

  broadcast(broadcastMessage)
}

function broadcast(message) {
  wsServer.connections.forEach(function (conn) {
        conn.sendText(message)
    })
}

process.on('uncaughtException', function(err) {
    // handle the error safely
    console.log("UNCAUGHT EXCEPTION! " + err)
})

logger.info("The WebSocket server is listening...")
<|endoftext|>


<commit_before>
"use strict";

/*global module, require, process*/

var sharejs = require('share'),
    _ = require("lodash"),
    livedb = sharejs.db,
    express = require('express'),
    server = express(),
    Duplex = require('stream').Duplex,
    browserChannel = require('browserchannel').server,
    liveDBMongo = require('livedb-mongo'),
    mongoConnect = liveDBMongo('mongodb://localhost:27017/share?auto_reconnect', {safe:true}),
    backend = livedb.client(mongoConnect),
    share = sharejs.server.createClient({backend: backend}),
    port = function() {
	if (process.argv.length === 3) {
	    return parseInt(process.argv[2]);
	} else {
	    return 8080;
	}
    }(),
    newRegex = /new-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;

/*
 Add an HTTP handler for querying. This must happen first.
 */
server.get(
    "/channel/search/:collection",
    function(req, res, next) {
	if (req.query.q === undefined) {
	    res.status(400).send("Expected a query string parameter q containing a search term.");
	} else {
	    backend.queryFetch(
		req.params.collection,
		{
		    _id:
		    {
			$regex: req.query.q
		    }
		},
		{},
		function(error, results) {
		    if (error) {
			next(error);
		    } else {
			res.send(
			    _.pluck(results, "docName")
				.filter(function(name) {
				    /*
				     We've stored out temporary documents with the prefix 'new-' followed by a GUID.
				     We don't want to return these as search results here.
				     */
				    return !newRegex.test(name);
				})
			);
		    }
		}
	    );
	}
    }
);

/*
 Add our ShareJS middleware. This is used for long running XHR communication with the browser.

 It lets us keep our documents syncrhonized.
 */
server.use(
    browserChannel(
	function(client) {
	    var stream = new Duplex({objectMode: true});

	    stream._read = function() {};
	    stream._write = function(chunk, encoding, callback) {
		if (client.state !== 'closed') {
		    client.send(chunk);
		}
		callback();
	    };

	    client.on('message', function(data) {
		stream.push(data);
	    });

	    client.on('close', function(reason) {
		stream.push(null);
		stream.emit('close');
	    });

	    stream.on('end', function() {
		client.close();
	    });

	    return share.listen(stream);
	}));

server.listen(port);

<commit_msg>Removed the filtering from the search results - we're no longer saving documents until the user gives them a name.<commit_after>
"use strict";

/*global module, require, process*/

var sharejs = require('share'),
    _ = require("lodash"),
    livedb = sharejs.db,
    express = require('express'),
    server = express(),
    Duplex = require('stream').Duplex,
    browserChannel = require('browserchannel').server,
    liveDBMongo = require('livedb-mongo'),
    mongoConnect = liveDBMongo('mongodb://localhost:27017/share?auto_reconnect', {safe:true}),
    backend = livedb.client(mongoConnect),
    share = sharejs.server.createClient({backend: backend}),
    port = function() {
	if (process.argv.length === 3) {
	    return parseInt(process.argv[2]);
	} else {
	    return 8080;
	}
    }();

/*
 Add an HTTP handler for querying. This must happen first.
 */
server.get(
    "/channel/search/:collection",
    function(req, res, next) {
	if (req.query.q === undefined) {
	    res.status(400).send("Expected a query string parameter q containing a search term.");
	} else {
	    backend.queryFetch(
		req.params.collection,
		{
		    _id:
		    {
			$regex: req.query.q
		    }
		},
		{},
		function(error, results) {
		    if (error) {
			next(error);
		    } else {
			res.send(
			    _.pluck(results, "docName")
			);
		    }
		}
	    );
	}
    }
);

/*
 Add our ShareJS middleware. This is used for long running XHR communication with the browser.

 It lets us keep our documents syncrhonized.
 */
server.use(
    browserChannel(
	function(client) {
	    var stream = new Duplex({objectMode: true});

	    stream._read = function() {};
	    stream._write = function(chunk, encoding, callback) {
		if (client.state !== 'closed') {
		    client.send(chunk);
		}
		callback();
	    };

	    client.on('message', function(data) {
		stream.push(data);
	    });

	    client.on('close', function(reason) {
		stream.push(null);
		stream.emit('close');
	    });

	    stream.on('end', function() {
		client.close();
	    });

	    return share.listen(stream);
	}));

server.listen(port);

<|endoftext|>


<commit_before>var
  express = require('express'),
  cookieParser = require('cookie-parser'),
  bodyParser = require('body-parser'),
  expressSession = require('express-session'),
  fs = require('fs'),
  browserSync = require('browser-sync'),
  passport = require('passport'),
  GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
  app = express(),
  users = {},
  devices = [],
  instances = [],
  config = require('./config.json'),
  childProcesses = {},
  fork = require('child_process').fork;

if (fs.existsSync('./data/devices.json')) {
  devices = require('./data/devices.json');
}

if (fs.existsSync('./data/instances.json')) {
  instances = require('./data/instances.json');
}

app.use(cookieParser());
app.use(expressSession({secret: config.sessionKey, resave: true, saveUninitialized: true}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(passport.initialize());
app.use(passport.session());

app.on('update-devices', function () {
  fs.writeFileSync('./data/devices.json', JSON.stringify(devices));
  console.log('Updated devices.json');
});

app.on('update-instances', function () {
  fs.writeFileSync('./data/instances.json', JSON.stringify(instances));
  console.log('Updated instances.json');
});

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  done(null, users[id]);
});

passport.use(new GoogleStrategy(
  {
    clientID: config.GOOGLE_CLIENT_ID,
    clientSecret: config.GOOGLE_CLIENT_SECRET,
    callbackURL:config.GOOGLE_CALLBACK_URL
  },
  function (accessToken, refreshToken, profile, done) {
    var
      userId = profile.id,
      user = {
        id: userId,
        displayName: profile.displayName,
        emails: profile.emails
      };
    users[userId] = user;
    return done(null, user);
  }
));

app.get('/auth/google', passport.authenticate('google', {scope: 'openid profile email'}));

app.get('/auth/google/callback',
  passport.authenticate('google', {failureRedirect: '/'}),
  function (req, res) {
    res.redirect('/');
  }
);

app.get('/user', function (req, res) {
  res.set('Cache-Control', 'no-cache');
  res.json({user: req.user});
});

app.get('/devices', function (req, res) {
  devices.sort(function (a, b) {
    if (a.location > b.location) {
      return 1;
    } else if (a.location < b.location) {
      return -1;
    } else {
      if (a.label > b.label) {
        return 1;
      } else if (a.label < b.label) {
        return -1;
      }
    }
    return 0;
  });

  res.set('Cache-Control', 'no-cache');
  res.json(devices);
});

app.post('/identify', function (req, res) {
  var label = req.body.label;

  if (!label) {
    res.json({message: 'Label missing.'});
    return;
  }

  var updated = false;

  devices.forEach(function (device, index) {

    if (device.label == label) {
      device.updated = +new Date();
      updated = true;
    }

  });

  if (!updated) {
    devices.push({
      label: label,
      updated: +new Date()
    });
  }

  app.emit('update-devices');

  res.json({message: 'Identified succesfully.'});
});

app.get('/ping', function (req, res) {
  var
    label = req.query.label,
    userId = req.query.user_id,
    message = {};

  instances.forEach(function (instance, index) {
    if (label) {
      if (instance.labels.indexOf(label) >= 0 && instance.browserSync && instance.updated + 10000 > (+new Date())) {
        message.address = instance.browserSync;
      }
    } else if (userId) {
      if (instance.userId == userId && instance.browserSync) {
        message.address = instance.browserSync;
      }
    }
  });

  res.json(message);

});

app.post('/save', function (req, res) {
  var
    uuid = req.body.uuid,
    key = req.body.key,
    value = req.body.value;

  // Update device

  devices.forEach(function (device, index) {
    if (device.uuid == uuid) {
      device[key] = value;
    }
  });

  app.emit('update-devices');

  res.json({message: 'Saved value'});

});

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

var server = app.listen(process.argv[2] || 80, function () {
  console.log('Express server listening on port %d', server.address().port);
});

// Socket.io server
var
  io = require('socket.io')(server),
  nsApp = io.of('/devicewallapp'),
  ns = io.of('/devicewall');

// Namespace "devicewallapp"
nsApp.on('connection', function (socket) {

  console.log('DeviceWall device connected!');

  // Update device status
  socket.on('update', function (data) {

    var uuid = data.uuid,
        model = data.model,
        batteryStatus = data.batteryStatus,
        platform = data.platform,
        version = data.version,
        updated = false;

    devices.forEach(function (device, index) {
      if (device.uuid === uuid) {
        device.model = model;
        device.platform = platform;
        device.version = version;
        device.batteryStatus = batteryStatus;
        device.updated = +new Date();
        updated = true;
      }
    });

    if (!updated) {

    	// Determine label for the device

    	var label = 0;

	    devices.forEach(function (device, index) {
	    	var currentLabel = parseInt(device.label.replace(/[^0-9]/, ''), 10);
	      if (currentLabel > label) {
	      	label = currentLabel;
	      }
	    });

	    label = 'P' + ('00' + (label + 1)).substr(-3, 3); // P stands for "phone", default format is for example "P001"

      devices.push({
        uuid: uuid,
        label: label,
        model: model,
        platform: platform,
        version: version,
        batteryStatus: batteryStatus,
        updated: +new Date()
      });

    }

    app.emit('update-devices');

    ns.emit('update', devices);

  });

  socket.on('disconnect', function () {
    console.log('DeviceWall device disconnected.');
  });

});

// Namespace "devicewall"
ns.on('connection', function (socket) {

  console.log('DeviceWall control panel connected!');

  // Start
  socket.on('start', function (data) {

    console.log('DeviceWall control panel start.');

    var user = data.user,
        url = data.url,
        uuids = data.uuids || [];

    // Updating devices
    devices.forEach(function (device, deviceIndex) {
      uuids.forEach(function (uuid, uuidIndex) {
        // Check that there's no user or same user tries to use device
        if (device.uuid === uuid && (!device.userId || device.userId === user.id)) {
          device.userId = user.id;
          device.userName = user.displayName;
          device.lastUsed = +new Date();
        }
      });
    });

    app.emit('update-devices');

    // Updating instances
    var updated = false;

    instances.forEach(function (instance, index) {
      if (instance.userId === user.id) {
        updated = true;
        instance.url = url;
        instance.uuids = uuids;
        instance.browserSync = null;
        instance.updated = +new Date();
      }
    });

    if (!updated) {
      instances.push({
        userId: user.id,
        url: url,
        uuids: uuids,
        browserSync: null,
        updated: +new Date()
      });
    }

    app.emit('update-instances');

    if (childProcesses[user.id]) {
      childProcesses[user.id].send({type: 'exit'});
      delete childProcesses[user.id];
    }

    childProcesses[user.id] = fork('./server-browsersync');
    childProcesses[user.id].send({type: 'init', url: url});
    childProcesses[user.id].on('message', function(message) {
      if (message.type === 'browserSyncInit') {
        instances.forEach(function(instance, index) {
          if (instance.userId === user.id) {
            instance.browserSync = message.browserSync;
            instance.updated = +new Date();
          }
        });
        data.url = message.browserSync;
        app.emit('update-devices');
        ns.emit('update', devices);
        ns.emit('start', data);
        nsApp.emit('start', data);
      }
    });

  });

  // Stop
	socket.on('stop', function (data) {

	  console.log('DeviceWall control panel stop.');

	  var uuids = data.uuids,
	      user = data.user;

	  // Update device
	  devices.forEach(function (device, index) {
	    uuids.forEach(function (uuid, index) {
  	    if (device.uuid === uuid) {
  	      device.userId = null;
  	      device.userName = null;
  	    }
	    });
	  });

	  app.emit('update-devices');
    ns.emit('update', devices);

    if (user && childProcesses[user.id]) {
      childProcesses[user.id].send({type: 'location', url: config.deviceWallAppURL});
      childProcesses[user.id].send({type: 'exit'});
      delete childProcesses[user.id];
    }
	});

	// List devices

	socket.on('list', function (data, fn) {
	  devices.sort(function (a, b) {
	    if (a.location > b.location) {
	      return 1;
	    } else if (a.location < b.location) {
	      return -1;
	    } else {
	      if (a.label > b.label) {
	        return 1;
	      } else if (a.label < b.label) {
	        return -1;
	      }
	    }
	    return 0;
	  });

		fn(devices);
	});

  socket.on('disconnect', function () {
    console.log('DeviceWall control panel disconnected.');
  });

});

// Start server
io.listen(3000);
console.log('Socket.io server listening on port 3000');
<commit_msg>Remove deprecated code<commit_after>var
  express = require('express'),
  cookieParser = require('cookie-parser'),
  bodyParser = require('body-parser'),
  expressSession = require('express-session'),
  fs = require('fs'),
  browserSync = require('browser-sync'),
  passport = require('passport'),
  GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
  app = express(),
  users = {},
  devices = [],
  instances = [],
  config = require('./config.json'),
  childProcesses = {},
  fork = require('child_process').fork;

if (fs.existsSync('./data/devices.json')) {
  devices = require('./data/devices.json');
}

if (fs.existsSync('./data/instances.json')) {
  instances = require('./data/instances.json');
}

app.use(cookieParser());
app.use(expressSession({secret: config.sessionKey, resave: true, saveUninitialized: true}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(passport.initialize());
app.use(passport.session());

app.on('update-devices', function () {
  fs.writeFileSync('./data/devices.json', JSON.stringify(devices));
  console.log('Updated devices.json');
});

app.on('update-instances', function () {
  fs.writeFileSync('./data/instances.json', JSON.stringify(instances));
  console.log('Updated instances.json');
});

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  done(null, users[id]);
});

passport.use(new GoogleStrategy(
  {
    clientID: config.GOOGLE_CLIENT_ID,
    clientSecret: config.GOOGLE_CLIENT_SECRET,
    callbackURL:config.GOOGLE_CALLBACK_URL
  },
  function (accessToken, refreshToken, profile, done) {
    var
      userId = profile.id,
      user = {
        id: userId,
        displayName: profile.displayName,
        emails: profile.emails
      };
    users[userId] = user;
    return done(null, user);
  }
));

app.get('/auth/google', passport.authenticate('google', {scope: 'openid profile email'}));

app.get('/auth/google/callback',
  passport.authenticate('google', {failureRedirect: '/'}),
  function (req, res) {
    res.redirect('/');
  }
);

app.get('/user', function (req, res) {
  res.set('Cache-Control', 'no-cache');
  res.json({user: req.user});
});

app.get('/devices', function (req, res) {
  devices.sort(function (a, b) {
    if (a.location > b.location) {
      return 1;
    } else if (a.location < b.location) {
      return -1;
    } else {
      if (a.label > b.label) {
        return 1;
      } else if (a.label < b.label) {
        return -1;
      }
    }
    return 0;
  });

  res.set('Cache-Control', 'no-cache');
  res.json(devices);
});

app.post('/save', function (req, res) {
  var
    uuid = req.body.uuid,
    key = req.body.key,
    value = req.body.value;

  // Update device

  devices.forEach(function (device, index) {
    if (device.uuid == uuid) {
      device[key] = value;
    }
  });

  app.emit('update-devices');

  res.json({message: 'Saved value'});

});

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

var server = app.listen(process.argv[2] || 80, function () {
  console.log('Express server listening on port %d', server.address().port);
});

// Socket.io server
var
  io = require('socket.io')(server),
  nsApp = io.of('/devicewallapp'),
  ns = io.of('/devicewall');

// Namespace "devicewallapp"
nsApp.on('connection', function (socket) {

  console.log('DeviceWall device connected!');

  // Update device status
  socket.on('update', function (data) {

    var uuid = data.uuid,
        model = data.model,
        batteryStatus = data.batteryStatus,
        platform = data.platform,
        version = data.version,
        updated = false;

    devices.forEach(function (device, index) {
      if (device.uuid === uuid) {
        device.model = model;
        device.platform = platform;
        device.version = version;
        device.batteryStatus = batteryStatus;
        device.updated = +new Date();
        updated = true;
      }
    });

    if (!updated) {

    	// Determine label for the device

    	var label = 0;

	    devices.forEach(function (device, index) {
	    	var currentLabel = parseInt(device.label.replace(/[^0-9]/, ''), 10);
	      if (currentLabel > label) {
	      	label = currentLabel;
	      }
	    });

	    label = 'P' + ('00' + (label + 1)).substr(-3, 3); // P stands for "phone", default format is for example "P001"

      devices.push({
        uuid: uuid,
        label: label,
        model: model,
        platform: platform,
        version: version,
        batteryStatus: batteryStatus,
        updated: +new Date()
      });

    }

    app.emit('update-devices');

    ns.emit('update', devices);

  });

  socket.on('disconnect', function () {
    console.log('DeviceWall device disconnected.');
  });

});

// Namespace "devicewall"
ns.on('connection', function (socket) {

  console.log('DeviceWall control panel connected!');

  // Start
  socket.on('start', function (data) {

    console.log('DeviceWall control panel start.');

    var user = data.user,
        url = data.url,
        uuids = data.uuids || [];

    // Updating devices
    devices.forEach(function (device, deviceIndex) {
      uuids.forEach(function (uuid, uuidIndex) {
        // Check that there's no user or same user tries to use device
        if (device.uuid === uuid && (!device.userId || device.userId === user.id)) {
          device.userId = user.id;
          device.userName = user.displayName;
          device.lastUsed = +new Date();
        }
      });
    });

    app.emit('update-devices');

    // Updating instances
    var updated = false;

    instances.forEach(function (instance, index) {
      if (instance.userId === user.id) {
        updated = true;
        instance.url = url;
        instance.uuids = uuids;
        instance.browserSync = null;
        instance.updated = +new Date();
      }
    });

    if (!updated) {
      instances.push({
        userId: user.id,
        url: url,
        uuids: uuids,
        browserSync: null,
        updated: +new Date()
      });
    }

    app.emit('update-instances');

    if (childProcesses[user.id]) {
      childProcesses[user.id].send({type: 'exit'});
      delete childProcesses[user.id];
    }

    childProcesses[user.id] = fork('./server-browsersync');
    childProcesses[user.id].send({type: 'init', url: url});
    childProcesses[user.id].on('message', function(message) {
      if (message.type === 'browserSyncInit') {
        instances.forEach(function(instance, index) {
          if (instance.userId === user.id) {
            instance.browserSync = message.browserSync;
            instance.updated = +new Date();
          }
        });
        data.url = message.browserSync;
        app.emit('update-devices');
        ns.emit('update', devices);
        ns.emit('start', data);
        nsApp.emit('start', data);
      }
    });

  });

  // Stop
	socket.on('stop', function (data) {

	  console.log('DeviceWall control panel stop.');

	  var uuids = data.uuids,
	      user = data.user;

	  // Update device
	  devices.forEach(function (device, index) {
	    uuids.forEach(function (uuid, index) {
  	    if (device.uuid === uuid) {
  	      device.userId = null;
  	      device.userName = null;
  	    }
	    });
	  });

	  app.emit('update-devices');
    ns.emit('update', devices);

    if (user && childProcesses[user.id]) {
      childProcesses[user.id].send({type: 'location', url: config.deviceWallAppURL});
      childProcesses[user.id].send({type: 'exit'});
      delete childProcesses[user.id];
    }
	});

	// List devices

	socket.on('list', function (data, fn) {
	  devices.sort(function (a, b) {
	    if (a.location > b.location) {
	      return 1;
	    } else if (a.location < b.location) {
	      return -1;
	    } else {
	      if (a.label > b.label) {
	        return 1;
	      } else if (a.label < b.label) {
	        return -1;
	      }
	    }
	    return 0;
	  });

		fn(devices);
	});

  socket.on('disconnect', function () {
    console.log('DeviceWall control panel disconnected.');
  });

});

// Start server
io.listen(3000);
console.log('Socket.io server listening on port 3000');
<|endoftext|>


<commit_before>import {express} from 'express';
import methodOverride from 'method-override';
import path from 'path';
import serveStatic from 'serve-static';

// web app middleware
const app = express();

// bootstrap public/index.html
app.use(methodOverride());

app.use(serveStatic(__dirname + '/public'));

app.get('*', function (req, res) {
  res.sendFile(path.resolve(__dirname, 'public',
    ['index.html', 'styles.css', 'favicon.ico', '05d72bd616722f39afef30004839ce08.eot',
      '6ef18e62928bfbe78057f6604702062a.woff', 'd3b5827e4faf0b034d4b2bcaa6d43724.ttf']));
});

let port = 80;

app.set('port', process.env.PORT || port);
<commit_msg>put server back, made linter angry<commit_after>var express = require('express');
var methodOverride = require('method-override');
var path = require('path');
var serveStatic = require('serve-static')

// web app middleware
var app = express();

// bootstrap public/index.html
app.use(methodOverride());

// server-side router
var router = express.Router();

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.use(serveStatic(__dirname + '/public'))
app.get('*', function(req, res) {
    res.sendFile(path.resolve(__dirname, 'public',
      ['index.html', 'styles.css', 'favicon.ico', '05d72bd616722f39afef30004839ce08.eot',
      '6ef18e62928bfbe78057f6604702062a.woff', 'd3b5827e4faf0b034d4b2bcaa6d43724.ttf']))
})

var url = process.env.IP || '0.0.0.0'
var port = 80;
app.set('port', process.env.PORT || port)

function listening() {
    // NODE_ENV=production node index.js
    if (process.env.NODE_ENV == 'production') {
        console.log('Static server listening url %s on port %s', url, server.address().port);
    }
}

var server = app.listen(port, listening);<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser');
var connect = require('connect');

var app = connect();
require('dotenv').load();
require('./app/config/passport')(passport);

mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

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

app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});
<commit_msg>saving polls<commit_after>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser');
var connect = require('connect');

var app = connect();
require('dotenv').load();
require('./app/config/passport')(passport);

mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

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

//app.use(express.json());       // to support JSON-encoded bodies
//app.use(express.urlencoded()); // to support URL-encoded bodies

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

routes(app, passport);

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


<commit_before>var path = require('path');
var webpack = require('webpack');
var express = require('express');
var fs = require('fs');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static('public'));

app.get('/api/assets/', function (req, res) {
  const svgPath = 'public/svg/';
  const svgFolders = [
    {
      id: 'Beards',
      colors: [
        {
          id: 'default',
        },
        {
          id: 'blond',
        },
        {
          id: 'brown-haired person',
        },
        {
          id: 'brunet',
        },
        {
          id: 'white'
        }
      ],
      sortOrder: 4
    },
    {
      id: 'Body',
      colors: [
        {
          id: 'default',
        }
      ],
      sortOrder: 0
    },
    {
      id: 'Glasses',
      colors: [
        {
          id: 'default',
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Hairstyles',
      colors: [
        {
          id: 'default',
        },
        {
          id: 'blond',
        },
        {
          id: 'brown-haired person',
        },
        {
          id: 'brunet',
        },
        {
          id: 'white'
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Scarfes',
      colors: [
        {
          id: 'default',
        }
      ],
      sortOrder: 3
    },
    {
      id: 'Shirts',
      colors: [
        {
          id: 'default',
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Tie',
      colors: [
        {
          id: 'default',
        }
      ],
      sortOrder: 2
    }
  ];
  const data = svgFolders.map(folder => {
    const colors = folder.colors.map(color => {
      return Object.assign({}, color, {
        files: fs.readdirSync(path.join(svgPath, folder.id, color.id))
      });
    });

    return Object.assign({}, folder, {
      colors
    });
  });
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(data));
});

app.listen(3000, function(err) {
  if (err) {
    return console.error(err);
  }

  console.log('Listening at http://localhost:3000/');
});
<commit_msg>Fix comma<commit_after>var path = require('path');
var webpack = require('webpack');
var express = require('express');
var fs = require('fs');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static('public'));

app.get('/api/assets/', function (req, res) {
  const svgPath = 'public/svg/';
  const svgFolders = [
    {
      id: 'Beards',
      colors: [
        {
          id: 'default'
        },
        {
          id: 'blond'
        },
        {
          id: 'brown-haired person'
        },
        {
          id: 'brunet'
        },
        {
          id: 'white'
        }
      ],
      sortOrder: 4
    },
    {
      id: 'Body',
      colors: [
        {
          id: 'default'
        }
      ],
      sortOrder: 0
    },
    {
      id: 'Glasses',
      colors: [
        {
          id: 'default'
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Hairstyles',
      colors: [
        {
          id: 'default'
        },
        {
          id: 'blond'
        },
        {
          id: 'brown-haired person'
        },
        {
          id: 'brunet'
        },
        {
          id: 'white'
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Scarfes',
      colors: [
        {
          id: 'default'
        }
      ],
      sortOrder: 3
    },
    {
      id: 'Shirts',
      colors: [
        {
          id: 'default'
        }
      ],
      sortOrder: 1
    },
    {
      id: 'Tie',
      colors: [
        {
          id: 'default'
        }
      ],
      sortOrder: 2
    }
  ];
  const data = svgFolders.map(folder => {
    const colors = folder.colors.map(color => {
      return Object.assign({}, color, {
        files: fs.readdirSync(path.join(svgPath, folder.id, color.id))
      });
    });

    return Object.assign({}, folder, {
      colors
    });
  });
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(data));
});

app.listen(3000, function(err) {
  if (err) {
    return console.error(err);
  }

  console.log('Listening at http://localhost:3000/');
});
<|endoftext|>


<commit_before>var addressPoints = [
  [
    "Troy NY, USA",
    42.7284,
    73.6918
  ],
  [
    "London, UK",
    51.5073219,
    -0.1276473
  ],
  [
    "San Francisco, California",
    37.7792808,
    -122.4192362
  ],
  [
    "Los Angeles, CA",
    34.0543942,
    -118.2439408
  ]
];
<commit_msg>Update org-locations.js<commit_after>var addressPoints = [
  [
    "Troy NY, USA",
    42.7284,
    73.6918
  ],
  [
    "Yorktown Heights NY, USA",
    41.2709,
    -0.1276473
  ],
  [
    "San Francisco, California",
    37.7792808,
    73.7776
  ],
  [
    "Los Angeles, CA",
    34.0543942,
    -118.2439408
  ]
];
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

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

app.get('/tetris', function(req, res) {
  res.sendFile(path.join(__dirname, 'tetris.html'));
});

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<commit_msg>Update server to potentially work with more files<commit_after>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');

var app = express();
var compiler = webpack(config);

app.use(express.static('.'));

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

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

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<|endoftext|>


<commit_before>const fs                = require('fs')
const aawait            = require('asyncawait/await')
const aasync            = require('asyncawait/async')
const express           = require('express')
const exphbs            = require('express-handlebars')
const cookieSession     = require('cookie-session')
const cookieParser      = require('cookie-parser')
const passport          = require('passport')
const FitbitStrategy    = require('passport-fitbit-oauth2').FitbitOAuth2Strategy
const RunKeeperStrategy = require('passport-runkeeper').Strategy
const uuid              = require('node-uuid')
const rp                = require('request-promise')
const moment            = require('moment')

const config = require('./config.json')

const cache = {}

const oldUsers   = fs.readFileSync('data/users.json')
const users      = (oldUsers.length > 0) ? JSON.parse(oldUsers) : {}
const writeUsers = () => fs.writeFileSync('data/users.json', JSON.stringify(users))
const newUser    = () => {
  const id = uuid.v4()
  users[id] = {}
  users[id].id = id
  users[id].accounts = {}
  writeUsers()
  return id
}
const setAccount = (id, profile) => {
  users[id].accounts[profile.provider] = profile.id
  writeUsers()
}

// accounts[provider][id]
//   user
//   displayName
const oldAccounts = fs.readFileSync('data/accounts.json')
const accounts    = (oldAccounts.length > 0) ? JSON.parse(oldAccounts) : {}
const addAccount  = (profile, userId, accessToken, refreshToken) => {
  if (accounts[profile.provider] === undefined) accounts[profile.provider] = {}

  accounts[profile.provider][profile.id]              = profile
  accounts[profile.provider][profile.id].user         = userId
  accounts[profile.provider][profile.id].accessToken  = accessToken
  accounts[profile.provider][profile.id].refreshToken = refreshToken

  fs.writeFileSync('data/accounts.json', JSON.stringify(accounts))
}
const updateAccount = (profile, accessToken, refreshToken) => {
  accounts[profile.provider][profile.id].accessToken = accessToken
  accounts[profile.provider][profile.id].refreshToken = refreshToken
  fs.writeFileSync('data/accounts.json', JSON.stringify(accounts))
}

const app = express()
app.engine('.hbs', exphbs({ defaultLayout: 'main', extname: '.hbs' }))
app.set('view engine', '.hbs')
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'af092mnvaz9' }))
app.use(passport.initialize())
app.use(passport.session())

const onAuthenticated = (req, accessToken, refreshToken, profile, done) => {
  if (req.user) {
    // Connect the new account to logged in user.
    setAccount(req.user.id, profile)
    updateAccount(profile, accessToken, refreshToken)
    done(null, req.user)
  } else {
    const userId = (accounts[profile.provider] === undefined ||
                    accounts[profile.provider][profile.id] === undefined) ?
          newUser() : accounts[profile.provider][profile.id].user

    addAccount(profile, userId, accessToken, refreshToken)
    setAccount(userId, profile)
    done(null, users[userId])
  }
}

passport.use(new FitbitStrategy(
  {
    clientID:          config.fitbit.clientID,
    clientSecret:      config.fitbit.clientSecret,
    callbackURL:       `http://${config.server.host}:${config.server.port}/auth/fitbit/callback`,
    passReqToCallback: true,
  },
  onAuthenticated
))
app.get(
  '/auth/fitbit',
  passport.authenticate('fitbit', {
    scope: ['activity', 'heartrate', 'location', 'profile', 'weight'],
  })
)
app.get(
  '/auth/fitbit/callback',
  passport.authenticate(
    'fitbit', { successRedirect: '/', failureRedirect: '/auth/fitbit/failure' }
  )
)

passport.use(new RunKeeperStrategy(
  {
    clientID:          config.runkeeper.clientID,
    clientSecret:      config.runkeeper.clientSecret,
    callbackURL:       `http://${config.server.host}:${config.server.port}/auth/runkeeper/callback`,
    passReqToCallback: true,
  },
  onAuthenticated
))
app.get('/auth/runkeeper', passport.authenticate('runkeeper'))
app.get(
  '/auth/runkeeper/callback',
  passport.authenticate(
    'runkeeper', { successRedirect: '/', failureRedirect: '/auth/runkeeper/failure' }
  )
)

passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => done(null, users[id]))

app.get('/', (req, res) => {
  const connectHtml =
    `Connect FitBit

     Connect RunKeeper

     Go home

    `

  if (req.user) {
    res.send(
      `
      Hello ${req.user.id}

      You are connected with: ${JSON.stringify(req.user.accounts)}

      ${connectHtml}
      `
    )
  } else {
    res.send(`Please login<br/>${connectHtml}`)
  }
})

const getFromFitbit = require('./lib/getFromFitbit')(rp)
const getFitbitTcx  = require('./lib/getFbTcx')(rp, config.fitbit)
const convertFb2Hg  = require('./lib/convertFb2Hg')(cache)

app.get(
  '/home', aasync((req, res) => {
    console.log('Logged in', req.user)

    const activitiesUrl =
          `https://api.fitbit.com/1/user/-/activities/list.json?beforeDate=${moment().format('YYYY-MM-DD')}&sort=desc&limit=10&offset=0`

    const data = aawait(getFromFitbit(activitiesUrl, accounts.fitbit[req.user.accounts.fitbit]))

    data.activities.forEach(activity => (cache[activity.logId] = activity))

    // res.json(data)
    res.render('listfb', data)
  })
)

app.get('/fitbit/tcx/:logId', aasync((req, res) => {
  res.send(aawait(getFitbitTcx(accounts.fitbit[req.user.accounts.fitbit])(req.params.logId)))
}))

app.get('/fitbit/cp/:logId', aasync((req, res) => {
  const newHgActivity = aawait(
    convertFb2Hg(
      getFitbitTcx(accounts.fitbit[req.user.accounts.fitbit])
    )(req.params.logId)
  )

  const runkeeperUri = 'https://api.runkeeper.com/fitnessActivities'
  const runkeeperAccess =
        accounts.runkeeper[req.user.accounts.runkeeper].accessToken

  const response = aawait(rp({
    uri:     runkeeperUri,
    method:  'POST',
    json:    true,
    body:    newHgActivity,
    headers: {
      Authorization:  `Bearer ${runkeeperAccess}`,
      'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
    },
  }))

  res.render('exported', { activityJson: JSON.stringify(newHgActivity, null, 2) })
}))

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send(err.message)
})

app.listen(config.server.port, () => {
  console.log(`Fitbit2runkeeper listening on port ${config.server.port}!`)
})
<commit_msg>Listing from tomorrow to get all, and correct config to getFromFitbit.<commit_after>const fs                = require('fs')
const aawait            = require('asyncawait/await')
const aasync            = require('asyncawait/async')
const express           = require('express')
const exphbs            = require('express-handlebars')
const cookieSession     = require('cookie-session')
const cookieParser      = require('cookie-parser')
const passport          = require('passport')
const FitbitStrategy    = require('passport-fitbit-oauth2').FitbitOAuth2Strategy
const RunKeeperStrategy = require('passport-runkeeper').Strategy
const uuid              = require('node-uuid')
const rp                = require('request-promise')
const moment            = require('moment')

const config = require('./config.json')

const cache = {}

const oldUsers   = fs.readFileSync('data/users.json')
const users      = (oldUsers.length > 0) ? JSON.parse(oldUsers) : {}
const writeUsers = () => fs.writeFileSync('data/users.json', JSON.stringify(users))
const newUser    = () => {
  const id = uuid.v4()
  users[id] = {}
  users[id].id = id
  users[id].accounts = {}
  writeUsers()
  return id
}
const setAccount = (id, profile) => {
  users[id].accounts[profile.provider] = profile.id
  writeUsers()
}

// accounts[provider][id]
//   user
//   displayName
const oldAccounts = fs.readFileSync('data/accounts.json')
const accounts    = (oldAccounts.length > 0) ? JSON.parse(oldAccounts) : {}
const addAccount  = (profile, userId, accessToken, refreshToken) => {
  if (accounts[profile.provider] === undefined) accounts[profile.provider] = {}

  accounts[profile.provider][profile.id]              = profile
  accounts[profile.provider][profile.id].user         = userId
  accounts[profile.provider][profile.id].accessToken  = accessToken
  accounts[profile.provider][profile.id].refreshToken = refreshToken

  fs.writeFileSync('data/accounts.json', JSON.stringify(accounts))
}
const updateAccount = (profile, accessToken, refreshToken) => {
  accounts[profile.provider][profile.id].accessToken = accessToken
  accounts[profile.provider][profile.id].refreshToken = refreshToken
  fs.writeFileSync('data/accounts.json', JSON.stringify(accounts))
}

const app = express()
app.engine('.hbs', exphbs({ defaultLayout: 'main', extname: '.hbs' }))
app.set('view engine', '.hbs')
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'af092mnvaz9' }))
app.use(passport.initialize())
app.use(passport.session())

const onAuthenticated = (req, accessToken, refreshToken, profile, done) => {
  if (req.user) {
    // Connect the new account to logged in user.
    setAccount(req.user.id, profile)
    updateAccount(profile, accessToken, refreshToken)
    done(null, req.user)
  } else {
    const userId = (accounts[profile.provider] === undefined ||
                    accounts[profile.provider][profile.id] === undefined) ?
          newUser() : accounts[profile.provider][profile.id].user

    addAccount(profile, userId, accessToken, refreshToken)
    setAccount(userId, profile)
    done(null, users[userId])
  }
}

passport.use(new FitbitStrategy(
  {
    clientID:          config.fitbit.clientID,
    clientSecret:      config.fitbit.clientSecret,
    callbackURL:       `http://${config.server.host}:${config.server.port}/auth/fitbit/callback`,
    passReqToCallback: true,
  },
  onAuthenticated
))
app.get(
  '/auth/fitbit',
  passport.authenticate('fitbit', {
    scope: ['activity', 'heartrate', 'location', 'profile', 'weight'],
  })
)
app.get(
  '/auth/fitbit/callback',
  passport.authenticate(
    'fitbit', { successRedirect: '/', failureRedirect: '/auth/fitbit/failure' }
  )
)

passport.use(new RunKeeperStrategy(
  {
    clientID:          config.runkeeper.clientID,
    clientSecret:      config.runkeeper.clientSecret,
    callbackURL:       `http://${config.server.host}:${config.server.port}/auth/runkeeper/callback`,
    passReqToCallback: true,
  },
  onAuthenticated
))
app.get('/auth/runkeeper', passport.authenticate('runkeeper'))
app.get(
  '/auth/runkeeper/callback',
  passport.authenticate(
    'runkeeper', { successRedirect: '/', failureRedirect: '/auth/runkeeper/failure' }
  )
)

passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => done(null, users[id]))

app.get('/', (req, res) => {
  const connectHtml =
    `Connect FitBit

     Connect RunKeeper

     Go home

    `

  if (req.user) {
    res.send(
      `
      Hello ${req.user.id}

      You are connected with: ${JSON.stringify(req.user.accounts)}

      ${connectHtml}
      `
    )
  } else {
    res.send(`Please login<br/>${connectHtml}`)
  }
})

const getFromFitbit = require('./lib/getFromFitbit')(rp, config.fitbit)
const getFitbitTcx  = require('./lib/getFbTcx')(rp)
const convertFb2Hg  = require('./lib/convertFb2Hg')(cache)

app.get(
  '/home', aasync((req, res) => {
    console.log('Logged in', req.user)

    const activitiesUrl =
          `https://api.fitbit.com/1/user/-/activities/list.json?beforeDate=${moment().add(1, 'd').format('YYYY-MM-DD')}&sort=desc&limit=10&offset=0`

    const data = aawait(getFromFitbit(activitiesUrl, accounts.fitbit[req.user.accounts.fitbit]))

    data.activities.forEach(activity => (cache[activity.logId] = activity))

    // res.json(data)
    res.render('listfb', data)
  })
)

app.get('/fitbit/tcx/:logId', aasync((req, res) => {
  res.send(aawait(getFitbitTcx(accounts.fitbit[req.user.accounts.fitbit])(req.params.logId)))
}))

app.get('/fitbit/cp/:logId', aasync((req, res) => {
  const newHgActivity = aawait(
    convertFb2Hg(
      getFitbitTcx(accounts.fitbit[req.user.accounts.fitbit])
    )(req.params.logId)
  )

  const runkeeperUri = 'https://api.runkeeper.com/fitnessActivities'
  const runkeeperAccess =
        accounts.runkeeper[req.user.accounts.runkeeper].accessToken

  const response = aawait(rp({
    uri:     runkeeperUri,
    method:  'POST',
    json:    true,
    body:    newHgActivity,
    headers: {
      Authorization:  `Bearer ${runkeeperAccess}`,
      'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
    },
  }))

  res.render('exported', { activityJson: JSON.stringify(newHgActivity, null, 2) })
}))

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send(err.message)
})

app.listen(config.server.port, () => {
  console.log(`Fitbit2runkeeper listening on port ${config.server.port}!`)
})
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
var Users = require('./app/models/users.js');
var Books = require('./app/models/books.js');
var gBooks = require ('google-books-search');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var session = require('express-session');
require('dotenv').load();
var app = express();

mongoose.connect(process.env.MONGO_URI);

//configure passport

passport.use(new Strategy({
    clientID: process.env.FACEBOOK_KEY,
    clientSecret: process.env.FACEBOOK_SECRET,
    callbackURL: "https://fcc-booktrader-jessjo.c9users.io/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, cb) {

        //check user table for anyone with a facebook ID of profile.id
        Users.findOne({
            'id': profile.id
        }, function(err, user) {
            if (err) {
                return cb(err);
            }
            //No user was found... so create a new user with values from Facebook (all the profile. stuff)
            if (!user) {
            	console.log(profile);
                user = new Users({
                	id:profile.id,
                    name: profile.displayName,
                    username: profile.username,

                });
                user.save(function(err) {
                    if (err) console.log(err);
                    return cb(err, user);
                });
            } else {
                //found user. Return
                return cb(err, user);
            }
        });
    }

));

app.set('views', __dirname + '/app/views');
app.set('view engine', 'ejs');
app.use(session({ secret: 'ilovebunnyrabbits' }));
app.use(passport.initialize());
app.use(passport.session());

app.get('/',
  function(req, res) {

    res.render('index', { user: req.user, search: "", book: "", owned: "" });

  });

  app.get('/allbooks',
  function(req, res) {
   var thesebooks =[];
    Books.find({ "owners.0": { "$exists": true } },function(err,books) {
      if (err) throw err;
        console.log(books.length);
        res.render('allbooks', { user: req.user, books: books });
    })

  });

  app.get('/books/:bookID',
  function(req, res) {
   var thisBook =req.params.bookID;
        Books.findOne({
            		  'bookid': thisBook
        		  }, function(err, book) {
        		    if(err) throw err;
        		     res.render('book', { book: book });
        		  });

  });

  app.get('/mybooks',
  function(req, res) {
    var books = [];
    //find a user, get their book list.

    //look up each book add to book array
    console.log(req.user);
     Users.findOne({
            		  'id': req.user.id
        		  }, function(err, user) {
            	  	if (err) {
                	  	return err;
            	  	}
            	  	console.log(user);
        if (user.books.length ==0){
             res.render('mybooks', { user: user, books: "" });
        }
        var z =0;
    		for (var i=0; i<user.books.length; i++){

    		  Books.findOne({
            		  'bookid': user.books[i]
        		  }, function(err, book) {
            	  	if (err) {
                	  	return err;
            	  	}
            	  	if (book){
            	  	  books[z] = book;
            	  	  z++;
            	  	}
            	  	console.log("i "+ i + "books.length " + user.books.length + "books" + books.length);
            	  	if (books.length == user.books.length){
            	  	    console.log ("Number of books:" + user.books.length);
            	        res.render('mybooks', { user: user, books: books });
            	  	}
        		});
    		}

        		  });

  });

  app.post('/findBook', upload.array(),
  	function(req,res){
		returnBookInfo(res, req, displayPage);
  })

  app.post('/addBook', upload.array(),
  	 function(req,res){
  	 	var user = req.user;
  	 	var thisBookID = req.body.bookID;
  	 	       	Users.findOneAndUpdate(
    					  {id: user.id},
    					  {$push: {status: "owned"}},
    				  	{safe: true, upsert: true},
    					  function(err, model) {
    					    if (err) throw err;
    					});
  			   	Books.findOneAndUpdate(
    					{bookid: req.body.bookID},
    					{$push: {owners: req.user.id}},
    					{safe: true, upsert: true},
    					function(err, model) {
        					if (err) console.log(err);
			                	Users.findOneAndUpdate(
			    					{id: user.id},
			    					{$push: {books: thisBookID}},
			    					{safe: true, upsert: true},
			    					function(err, model2) {
			    						console.log ("user update:" + model2)
			    						console.log(user);
			        					if (err) console.log(err);
			        					res.render('index', { user: user, search: req.body.title, book: "", owned: true });

			    					}
			    				);

			    					}
			    	);

        		});

passport.serializeUser(function(user, cb) {
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});

app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

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

//function to check if the user owns a given book
function checkOwnership(bookID, user, res, req, book, owned){
	console.log(bookID + " is the bookID");
	console.log(user.books.indexOf(bookID) + " is the index of bookID");
	if(user.books.indexOf(bookID) >= 0){

		owned = true;
		console.log ("the owned status is "+ owned);
        res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });

	} else {
		 res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });

	}

}

function returnBookInfo(res, req, displayPage){
  var searchlimit = 5;
  		console.log("search term: " + req.body.title);

  		//set to only return 1 best match book

  	    var options = {
    		field: 'title',
    		offset: 0,
 			limit: searchlimit,
    		type: 'books',
    		order: 'relevance',
    		lang: 'en'
		};
		var allbooks = [];
		var allowned = [];

    	var thisBook = gBooks.search(req.body.title, options, function(error, results) {
    			if ( ! error ) {

     			//book found in google books api, search our data base to see if it exists or add
      for (var i=0; i< searchlimit; i++){
          console.log ( "search limit: " + searchlimit + "i: " + i);
     			Books.findOne({
            		'bookid': results[i].id
        		}, function(err, book) {
            		if (err) {
                		return err;
            		}
            		//no book found, create one.
        			 if (!book && i <searchlimit) {

                	 book = new Books({
                			  bookid: results[i].id,
                	 		  title: results[i].title,
                	 	    author: results[i].authors,
                    		rating: results[i].averageRating,
                    		thumbnail: results[i].thumbnail

                		});
                	book.save(function(err) {
                    	if (err) console.log(err);
                    	//console.log(book);
                    	allbooks.push(book);
                    	allowned.push(true);
                    	console.log(allbooks);
                      if (i==results.length-1){
                          console.log("allbooks: " + allbooks);
                    	   // res.render('index', { user: req.user, search: req.body.title, book: book, owned: "" });
                    	    return allbooks;
                      }
                  //

                	});

            	} else {
                	//found book. Return. The only time to check if owned is if we know it's in collection.
                	console.log(book + "is the book status and i is " + i);
                	var owned = false;
                	if (req.user){
                		console.log(req.user);
                		owned = checkOwnership(book.bookid, req.user, res, req, book, owned);
                		allowned.push(owned);
                	} else {
                		console.log ("the owned status is "+ owned);
                		//res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });
          				return book;
                	}
            }
        });
        }

    		} else {
        		console.log(error);
        		//what to do if error in searching for book
        		res.render('index', { user: req.user, search: req.body.title, book: "", owned: "" });
    		}
		});
  displayPage(res,req, allowned[0], allbooks);
}

function displayPage(res, req, owned, allbooks){
  console.log("here");
  console.log (allbooks);
  res.render('index', { user: req.user, search: req.body.title, book: allbooks[0], owned: owned });
}<commit_msg>fixing callbacks<commit_after>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
var Users = require('./app/models/users.js');
var Books = require('./app/models/books.js');
var gBooks = require ('google-books-search');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var session = require('express-session');
require('dotenv').load();
var app = express();

mongoose.connect(process.env.MONGO_URI);

//configure passport

passport.use(new Strategy({
    clientID: process.env.FACEBOOK_KEY,
    clientSecret: process.env.FACEBOOK_SECRET,
    callbackURL: "https://fcc-booktrader-jessjo.c9users.io/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, cb) {

        //check user table for anyone with a facebook ID of profile.id
        Users.findOne({
            'id': profile.id
        }, function(err, user) {
            if (err) {
                return cb(err);
            }
            //No user was found... so create a new user with values from Facebook (all the profile. stuff)
            if (!user) {
            	console.log(profile);
                user = new Users({
                	id:profile.id,
                    name: profile.displayName,
                    username: profile.username,

                });
                user.save(function(err) {
                    if (err) console.log(err);
                    return cb(err, user);
                });
            } else {
                //found user. Return
                return cb(err, user);
            }
        });
    }

));

app.set('views', __dirname + '/app/views');
app.set('view engine', 'ejs');
app.use(session({ secret: 'ilovebunnyrabbits' }));
app.use(passport.initialize());
app.use(passport.session());

app.get('/',
  function(req, res) {

    res.render('index', { user: req.user, search: "", book: "", owned: "" });

  });

  app.get('/allbooks',
  function(req, res) {
   var thesebooks =[];
    Books.find({ "owners.0": { "$exists": true } },function(err,books) {
      if (err) throw err;
        console.log(books.length);
        res.render('allbooks', { user: req.user, books: books });
    })

  });

  app.get('/books/:bookID',
  function(req, res) {
   var thisBook =req.params.bookID;
        Books.findOne({
            		  'bookid': thisBook
        		  }, function(err, book) {
        		    if(err) throw err;
        		     res.render('book', { book: book });
        		  });

  });

  app.get('/mybooks',
  function(req, res) {
    var books = [];
    //find a user, get their book list.

    //look up each book add to book array
    console.log(req.user);
     Users.findOne({
            		  'id': req.user.id
        		  }, function(err, user) {
            	  	if (err) {
                	  	return err;
            	  	}
            	  	console.log(user);
        if (user.books.length ==0){
             res.render('mybooks', { user: user, books: "" });
        }
        var z =0;
    		for (var i=0; i<user.books.length; i++){

    		  Books.findOne({
            		  'bookid': user.books[i]
        		  }, function(err, book) {
            	  	if (err) {
                	  	return err;
            	  	}
            	  	if (book){
            	  	  books[z] = book;
            	  	  z++;
            	  	}
            	  	console.log("i "+ i + "books.length " + user.books.length + "books" + books.length);
            	  	if (books.length == user.books.length){
            	  	    console.log ("Number of books:" + user.books.length);
            	        res.render('mybooks', { user: user, books: books });
            	  	}
        		});
    		}

        		  });

  });

  app.post('/findBook', upload.array(),
  	function(req,res){
		returnBookInfo(res, req, displayPage);
  })

  app.post('/addBook', upload.array(),
  	 function(req,res){
  	 	var user = req.user;
  	 	var thisBookID = req.body.bookID;
  	 	       	Users.findOneAndUpdate(
    					  {id: user.id},
    					  {$push: {status: "owned"}},
    				  	{safe: true, upsert: true},
    					  function(err, model) {
    					    if (err) throw err;
    					});
  			   	Books.findOneAndUpdate(
    					{bookid: req.body.bookID},
    					{$push: {owners: req.user.id}},
    					{safe: true, upsert: true},
    					function(err, model) {
        					if (err) console.log(err);
			                	Users.findOneAndUpdate(
			    					{id: user.id},
			    					{$push: {books: thisBookID}},
			    					{safe: true, upsert: true},
			    					function(err, model2) {
			    						console.log ("user update:" + model2)
			    						console.log(user);
			        					if (err) console.log(err);
			        					res.render('index', { user: user, search: req.body.title, book: "", owned: true });

			    					}
			    				);

			    					}
			    	);

        		});

passport.serializeUser(function(user, cb) {
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});

app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

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

//function to check if the user owns a given book
function checkOwnership(bookID, user, res, req, book, owned){
	console.log(bookID + " is the bookID");
	console.log(user.books.indexOf(bookID) + " is the index of bookID");
	if(user.books.indexOf(bookID) >= 0){

		owned = true;
		console.log ("the owned status is "+ owned);
        res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });

	} else {
		 res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });

	}

}

function returnBookInfo(res, req, displayPage){
      var searchlimit = 5;
  		console.log("search term: " + req.body.title);

  		//set to only return 1 best match book

  	   var options = {
    		  field: 'title',
    	  	offset: 0,
 			    limit: searchlimit,
    	  	type: 'books',
    		  order: 'relevance',
    		  lang: 'en'
	  	};
		  var allbooks = [];
	  	var allowned = [];
	  	var lookup = 0;

    	var thisBook = gBooks.search(req.body.title, options, function(error, results) {
    			if ( ! error ) {
     		  results.forEach(function(result) {
     			//book found in google books api, search our data base to see if it exists or add

     			  Books.findOne({
            		'bookid': result.id
        		  }, function(err, book) {
            		if (err) {
                		return err;
            		}
            		//no book found, create one.
        			 if (!book) {

                	 book = new Books({
                			  bookid: result.id,
                	 		  title: result.title,
                	 	    author: result.authors,
                    		rating: result.averageRating,
                    		thumbnail: result.thumbnail

                		});
                	book.save(function(err) {
                    	if (err) console.log(err);
                    	//console.log(book);
                    	allbooks.push(book);
                    	allowned.push(true);
                    	console.log(allbooks);
                      if (++lookup == results.length){
                          console.log("allbooks: " + allbooks);
                    	   // res.render('index', { user: req.user, search: req.body.title, book: book, owned: "" });
                    	    return allbooks;
                      }
                  //

                	});

            	} else {
                	//found book. Return. The only time to check if owned is if we know it's in collection.
                	console.log("found book: " + book );
                	var owned = false;
                	if (req.user){
                		console.log(req.user);
                		owned = checkOwnership(book.bookid, req.user, res, req, book, owned);
                		allowned.push(owned);
                	} else {
                		console.log ("the owned status is "+ owned);
                		//res.render('index', { user: req.user, search: req.body.title, book: book, owned: owned });
          				return book;
                	}
            }
        });

    			});
    			}
});

}

function displayPage(res, req, owned, allbooks){
  console.log("here");
  console.log (allbooks);
  res.render('index', { user: req.user, search: req.body.title, book: allbooks[0], owned: owned });
}<|endoftext|>


<commit_before>var questionnaire = angular.module('questionnaire', ['ui.router', 'formListCtrl', 'editPageCtrl', 'displayDataCtrl', 'surveyFormCtrl', 'thankyouCtl']);

questionnaire.config(function($stateProvider) {
  $stateProvider
    .state('index', {
      url: "",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/formList.html" }
      }
    })
    .state('formList', {
      url: "/formList",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/formList.html" }
      }
    })
    .state('editPage', {
      url: "/editPage",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/editPage.html" }
      }
    })
    .state('newForm', {
      url: "/newForm",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/newForm.html" }
      }
    })
    .state('surveyForm', {
      url: "/surveyForm",
      views: {
        "content": { templateUrl: "page/surveyForm.html" }
      }
    })
    .state('thankyou', {
      url: "/thankyou",
      views: {
        "content": { templateUrl: "page/thankyou.html" }
      }
    })
    .state('displayData', {
      url: "/displayData",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/displayData.html" }
      }
    });
});

questionnaire.controller('appCtrl', ['$rootScope', '$scope', '$http', 'locals', function($rootScope, $scope, $http, locals) {
  // 请求数据，返回到$rootScope
  $http({
    method: 'GET',
    url: 'dummyData.json'
  }).then(function successCallback(response) {
    if(typeof(Storage) !== undefined) {
      console.log(locals.getObject('forms'));
      var localForms = locals.getObject('forms');
      if (localForms !== undefined || !Array.isArray(localForms)) {
        $rootScope.forms = localForms;
      } else {
        $rootScope.forms = response.data.forms;
        locals.setObject('forms', $rootScope.forms);
      }
    } else {
    }
  }, function errorCallback(response) {
  });
}]);

<commit_msg>Update app.js<commit_after>var questionnaire = angular.module('questionnaire', ['ui.router', 'formListCtrl', 'editPageCtrl', 'displayDataCtrl', 'surveyFormCtrl', 'thankyouCtl']);

questionnaire.config(function($stateProvider) {
  $stateProvider
    .state('index', {
      url: "",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/formList.html" }
      }
    })
    .state('formList', {
      url: "/formList",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/formList.html" }
      }
    })
    .state('editPage', {
      url: "/editPage",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/editPage.html" }
      }
    })
    .state('newForm', {
      url: "/newForm",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/newForm.html" }
      }
    })
    .state('surveyForm', {
      url: "/surveyForm",
      views: {
        "content": { templateUrl: "page/surveyForm.html" }
      }
    })
    .state('thankyou', {
      url: "/thankyou",
      views: {
        "content": { templateUrl: "page/thankyou.html" }
      }
    })
    .state('displayData', {
      url: "/displayData",
      views: {
        "topBar": { templateUrl: "page/header.html"},
        "content": { templateUrl: "page/displayData.html" }
      }
    });
});

questionnaire.controller('appCtrl', ['$rootScope', '$scope', '$http', 'locals', function($rootScope, $scope, $http, locals) {
  // 请求数据，返回到$rootScope
  $http({
    method: 'GET',
    url: 'dummyData.json'
  }).then(function successCallback(response) {
    if(typeof(Storage) !== undefined) {
      console.log(locals.getObject('forms'));
      var localForms = locals.getObject('forms');
      if (Array.isArray(localForms)) {
        $rootScope.forms = localForms;
      } else {
        $rootScope.forms = response.data.forms;
        locals.setObject('forms', $rootScope.forms);
      }
    } else {
    }
  }, function errorCallback(response) {
  });
}]);

<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const API = require(path.join(__dirname, 'api/db_api.js'));
const port = 4000;
const name = '229th Server Stats';

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({limit:'5mb'}));
app.use('/js', express.static(path.join(__dirname, 'views/js')));
app.use('/css', express.static(path.join(__dirname, 'views/css')));
app.use('/assets', express.static(path.join(__dirname, 'views/assets')));
app.set('view engine', 'ejs');

//index page
app.get('/', (req, res) => {
    var title = "S3 229th";
    res.render('html/index', {
        title: title,
        name: name
    });
});
//about page
app.get('/about', (req, res) => {
  var title = "S3 About";
  res.render('html/about', {
      title: title,
      name: name
  });
});

//API for WEB View
app.post('/api/web/fetch', (req, res) => {
  console.log('POST /api/web/fetch');
   res.json(API.getJson()); //send them the data they need
});

//API for DCS node_children
//update the database with new info
app.post('/api/dcs/slmod/update', (req, res) => {
  console.log('POST MISSION SERVER UPDATE:');
  console.log('Server: ' + req.body['name'] + ' id:' + req.body['id']);
  console.log('Access Token: ' + req.body['token']);
  //send it the stats and server info
  var error = API.update(req.body);
  if (error) {
    console.log('UPDATE FAILED!');
    console.log('ERROR: ' + error);
    res.end('fail'); //end transmission
  } else {
    console.log('Update Successful');
    res.end('pass'); //end transmission
  }

});

//serve app
app.listen(port, function() {
  console.log('listening on '+port);
});
<commit_msg>relative path instead of dir, so i can run from /var/local sh file<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const API = require(path.join(__dirname, 'api/db_api.js'));
const port = 4000;
const name = '229th Server Stats';

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({limit:'5mb'}));
app.use('/js', express.static('views/js'));
app.use('/css', express.static('views/css'));
app.use('/assets', express.static('views/assets'));
app.set('view engine', 'ejs');

//index page
app.get('/', (req, res) => {
    var title = "S3 229th";
    res.render('html/index', {
        title: title,
        name: name
    });
});
//about page
app.get('/about', (req, res) => {
  var title = "S3 About";
  res.render('html/about', {
      title: title,
      name: name
  });
});

//API for WEB View
app.post('/api/web/fetch', (req, res) => {
  console.log('POST /api/web/fetch');
   res.json(API.getJson()); //send them the data they need
});

//API for DCS node_children
//update the database with new info
app.post('/api/dcs/slmod/update', (req, res) => {
  console.log('POST MISSION SERVER UPDATE:');
  console.log('Server: ' + req.body['name'] + ' id:' + req.body['id']);
  console.log('Access Token: ' + req.body['token']);
  //send it the stats and server info
  var error = API.update(req.body);
  if (error) {
    console.log('UPDATE FAILED!');
    console.log('ERROR: ' + error);
    res.end('fail'); //end transmission
  } else {
    console.log('Update Successful');
    res.end('pass'); //end transmission
  }

});

//serve app
app.listen(port, function() {
  console.log('listening on '+port);
});
<|endoftext|>