<commit_before>var mongo = require('mongodb');
var crypto = require('crypto');
var nodemailer = require("nodemailer");

var Server = mongo.Server,
	Db = mongo.Db,
	BSON = mongo.BSONPure;
	ObjectID = mongo.ObjectID;

//https://accounts.google.com/DisplayUnlockCaptcha // Libera GMAIL
var smtpTransport = nodemailer.createTransport("SMTP", {
	service: "Gmail",
    auth: {
        user: "arquitetaweb@gmail.com",
        pass: "pass"
    }
});

encrypt = function(text){
  var cipher = crypto.createCipher('aes-256-cbc','d6F3Efeq')
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted;
}

decrypt = function(text){
  var decipher = crypto.createDecipher('aes-256-cbc','d6F3Efeq')
  var dec = decipher.update(text,'hex','utf8')
  dec += decipher.final('utf8');
  return dec;
}

sendEmail = function(lat, lng) {
	var latEncrypt = encrypt(lat);
	var lngEncrypt = encrypt(lng);
	var textLink = "https://feiralivre.herokuapp.com/#authenticated/" + latEncrypt + "/" + lngEncrypt;
	var gMapsLink = "https://www.google.com/maps/preview?q=" + lat + "," + lng + "";

	var mailOptions = {
        from: "FeiraLivre ArquitetaWeb <arquitetaweb@gmail.com>", // sender address
        to: "marcos.tomazini@gmail.com",
        subject: "FeiraLivre - Adicionado Local",
        html: 'Adicionado Local de Alguma Feira :D
'
				+ 'Clique Aqui Para Liberar.

'
				+ 'Local Adicionado - Preview'
				+ '
'
    }

    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
        }else{
            console.log("Message sent: " + response.message);
        }
        //smtpTransport.close(); // shut down the connection pool, no more messages
    });
}

// DATA OBJECT
var	tabelaData = require('./data/tabelas');

var stringConexao = "ds027419.mongolab.com";
var portaConexao = 27419;

var server = new Server(stringConexao, portaConexao, {auto_reconnect: true});
db = new Db('heroku_app27553602', server, {safe: true});

db.open(function(err, db) {
	console.log("opening connection...");

	if(err) { return console.log("erro aqui -> " + err); }

	console.log("Connected to 'ArquitetaWeb Observatorio Social' database");

	if (stringConexao == "localhost") {
		console.log("MONGO Authorized");
		db.collection('tabelaA', {safe:true}, function(err, collection) {
			if (err) {
				console.log(err);
				console.log("The 'tabela A' collection doesn't exist. Creating data...");
				populateTabelas();
			}
		});
	} else {
		db.authenticate("arquitetaweb", "arqw3b", {}, function(err,success){
			if (err) {
				console.warn("MONGO ERROR: unauthorized "+ err.message);
			} else {
				console.log("MONGO Authorized");
				verifyTables();
			}
		});
	}
});

exports.recriar = function(req, res) {
	dropTables();
	verifyTables();
	res.send({'success':'recreate datatables success!'});
};

exports.adddata = function(req, res) {
	var consumoObject = req.body;
	var consumoStr =  JSON.stringify(consumoObject);
	console.log('objeto: ' +consumoStr);
	console.log('description: ' +consumoObject.description);
	db.collection('dados', function(err, collection) {
		if (consumoStr == "{}") {
			console.log('Error insert dados: object invalid retry');
			res.send(500, {'error': 'Invalid object.'});
			return;
		}

		if (err) {
			console.log('Error insert feiras: ' + err);
			res.send(500, {'error': 'An error has occurred'});
		} else {
			collection.insert(consumoObject, function (err, inserted) {
				if (err) {
					console.log('Error insert dados: ' + err);
					res.send(500, {'error': 'An error has occurred'});
				} else {
					sendEmail(consumoObject.latitude.toString(), consumoObject.longitude.toString());
					console.log('success inserted consumomesa: ' + inserted);
					res.send(inserted);
				}
			});
		}
	});
};

exports.observatorio = function(req, res) {
	db.collection('dados', function(err, collection) {
		collection.find({'confirmed': true, 'ads': false}).toArray(function(err, items) {
			res.setHeader('content-type', 'application/json');
			res.send(items);
		});
	});
};

exports.observatorioCodigo = function(req, res) {
	var codigo = req.param("codigo");
	console.log('Retrieving codigo ' + codigo););
	db.collection('dados', function(err, collection) {
		//collection.find({'codigo': codigo}).sort({DataHoraPedido: -1}).limit(parseInt(qtdeRegistros)).toArray(function(err, items) {
		collection.find({'codigo': codigo}).toArray(function(err, items) {
			res.send(items);
		});
	});
};

dropTables = function() {
	db.collection('tabelaA').drop();
	db.collection('tabelaB').drop();
	db.collection('tabelaC').drop();
	db.collection('tabelaD').drop();
	db.collection('dados').drop();
}

verifyTables = function() {
	db.collection('tabelaA', {safe:true}, function(err, collection) {
		if (err) {
			console.log(err);
			console.log("The 'tabelas' collection doesn't exist. Creating data...");
			populateTabelas();
		}
	});
};

populateTabelas = function() {
	console.log("populando tabelas");

    db.collection('tabelaA', function(err, collection) {
		console.log("inserindo tabela A");
        collection.insert(tabelaData.tabelaA(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaB', function(err, collection) {
		console.log("inserindo tabela B");
        collection.insert(tabelaData.tabelaB(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaC', function(err, collection) {
		console.log("inserindo tabela C");
        collection.insert(tabelaData.tabelaC(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaD', function(err, collection) {
		console.log("inserindo tabela D");
        collection.insert(tabelaData.tabelaD(), {safe:true}, function(err, result) {});
    });

	db.collection('dados', function(err, collection) {
		console.log("inserindo dados");
        collection.insert(tabelaData.dadosCidade(), {safe:true}, function(err, result) {});
    });
};<commit_msg>#160820142155<commit_after>var mongo = require('mongodb');
var crypto = require('crypto');
var nodemailer = require("nodemailer");

var Server = mongo.Server,
	Db = mongo.Db,
	BSON = mongo.BSONPure;
	ObjectID = mongo.ObjectID;

//https://accounts.google.com/DisplayUnlockCaptcha // Libera GMAIL
var smtpTransport = nodemailer.createTransport("SMTP", {
	service: "Gmail",
    auth: {
        user: "arquitetaweb@gmail.com",
        pass: "pass"
    }
});

encrypt = function(text){
  var cipher = crypto.createCipher('aes-256-cbc','d6F3Efeq')
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted;
}

decrypt = function(text){
  var decipher = crypto.createDecipher('aes-256-cbc','d6F3Efeq')
  var dec = decipher.update(text,'hex','utf8')
  dec += decipher.final('utf8');
  return dec;
}

sendEmail = function(lat, lng) {
	var latEncrypt = encrypt(lat);
	var lngEncrypt = encrypt(lng);
	var textLink = "https://feiralivre.herokuapp.com/#authenticated/" + latEncrypt + "/" + lngEncrypt;
	var gMapsLink = "https://www.google.com/maps/preview?q=" + lat + "," + lng + "";

	var mailOptions = {
        from: "FeiraLivre ArquitetaWeb <arquitetaweb@gmail.com>", // sender address
        to: "marcos.tomazini@gmail.com",
        subject: "FeiraLivre - Adicionado Local",
        html: 'Adicionado Local de Alguma Feira :D
'
				+ 'Clique Aqui Para Liberar.

'
				+ 'Local Adicionado - Preview'
				+ '
'
    }

    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
        }else{
            console.log("Message sent: " + response.message);
        }
        //smtpTransport.close(); // shut down the connection pool, no more messages
    });
}

// DATA OBJECT
var	tabelaData = require('./data/tabelas');

var stringConexao = "ds063449.mongolab.com";
var portaConexao = 63449;

var server = new Server(stringConexao, portaConexao, {auto_reconnect: true});
db = new Db('heroku_app28571941', server, {safe: true});

db.open(function(err, db) {
	console.log("opening connection...");

	if(err) { return console.log("erro aqui -> " + err); }

	console.log("Connected to 'ArquitetaWeb Observatorio Social' database");

	if (stringConexao == "localhost") {
		console.log("MONGO Authorized");
		db.collection('tabelaA', {safe:true}, function(err, collection) {
			if (err) {
				console.log(err);
				console.log("The 'tabela A' collection doesn't exist. Creating data...");
				populateTabelas();
			}
		});
	} else {
		db.authenticate("arquitetaweb", "arqw3b", {}, function(err,success){
			if (err) {
				console.warn("MONGO ERROR: unauthorized "+ err.message);
			} else {
				console.log("MONGO Authorized");
				verifyTables();
			}
		});
	}
});

exports.recriar = function(req, res) {
	dropTables();
	verifyTables();
	res.send({'success':'recreate datatables success!'});
};

exports.adddata = function(req, res) {
	var consumoObject = req.body;
	var consumoStr =  JSON.stringify(consumoObject);
	console.log('objeto: ' +consumoStr);
	console.log('description: ' +consumoObject.description);
	db.collection('dados', function(err, collection) {
		if (consumoStr == "{}") {
			console.log('Error insert dados: object invalid retry');
			res.send(500, {'error': 'Invalid object.'});
			return;
		}

		if (err) {
			console.log('Error insert feiras: ' + err);
			res.send(500, {'error': 'An error has occurred'});
		} else {
			collection.insert(consumoObject, function (err, inserted) {
				if (err) {
					console.log('Error insert dados: ' + err);
					res.send(500, {'error': 'An error has occurred'});
				} else {
					sendEmail(consumoObject.latitude.toString(), consumoObject.longitude.toString());
					console.log('success inserted consumomesa: ' + inserted);
					res.send(inserted);
				}
			});
		}
	});
};

exports.observatorio = function(req, res) {
	db.collection('dados', function(err, collection) {
		collection.find({'confirmed': true, 'ads': false}).toArray(function(err, items) {
			res.setHeader('content-type', 'application/json');
			res.send(items);
		});
	});
};

exports.observatorioCodigo = function(req, res) {
	var codigo = req.param("codigo");
	console.log('Retrieving codigo ' + codigo););
	db.collection('dados', function(err, collection) {
		//collection.find({'codigo': codigo}).sort({DataHoraPedido: -1}).limit(parseInt(qtdeRegistros)).toArray(function(err, items) {
		collection.find({'codigo': codigo}).toArray(function(err, items) {
			res.send(items);
		});
	});
};

dropTables = function() {
	db.collection('tabelaA').drop();
	db.collection('tabelaB').drop();
	db.collection('tabelaC').drop();
	db.collection('tabelaD').drop();
	db.collection('dados').drop();
}

verifyTables = function() {
	db.collection('tabelaA', {safe:true}, function(err, collection) {
		if (err) {
			console.log(err);
			console.log("The 'tabelas' collection doesn't exist. Creating data...");
			populateTabelas();
		}
	});
};

populateTabelas = function() {
	console.log("populando tabelas");

    db.collection('tabelaA', function(err, collection) {
		console.log("inserindo tabela A");
        collection.insert(tabelaData.tabelaA(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaB', function(err, collection) {
		console.log("inserindo tabela B");
        collection.insert(tabelaData.tabelaB(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaC', function(err, collection) {
		console.log("inserindo tabela C");
        collection.insert(tabelaData.tabelaC(), {safe:true}, function(err, result) {});
    });

	db.collection('tabelaD', function(err, collection) {
		console.log("inserindo tabela D");
        collection.insert(tabelaData.tabelaD(), {safe:true}, function(err, result) {});
    });

	db.collection('dados', function(err, collection) {
		console.log("inserindo dados");
        collection.insert(tabelaData.dadosCidade(), {safe:true}, function(err, result) {});
    });
};<|endoftext|>


<commit_before>module.exports = function (app) {

    var remoteFileSize = require("remote-file-size");
    var Util = require("../util");
    var http = require('http');
    var https = require('https');
    var fs = require('fs');
    var fileType = require("file-type");
    var imageSize = require("image-size");
    var tmp = require("tmp");
    var md5 = require("md5");
    var uuid = require("uuid/v4");
    var mongoose = require("mongoose");

    var authentication = require("../generator/authentication");
    var dataFetcher = require("../generator/dataFetcher");
    var skinChanger = require("../generator/skinChanger");

    // Schemas
    var Account = require("../db/schemas/account").Account;
    var Skin = require("../db/schemas/skin").Skin;
    var Traffic = require("../db/schemas/traffic").Traffic;

    app.post("/generate/url", function (req, res) {
        var url = req.body.url || req.query.url;
        var model = req.body.model || req.query.model || "steve";
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";

        console.log(req.body)
        console.log(req.query)

        console.log(("URL:        " + url).debug);
        console.log(("Model:      " + model).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        if (!url) {
            res.status(400).json({error: "URL is required"});
            return;
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;

            remoteFileSize(url, function (err, remoteSize) {
                if (remoteSize <= 0 || remoteSize > 102400) {
                    res.status(400).json({error: "Invalid file size"});
                    return;
                }

                tmp.file(function (err, path, fd, fileCleanup) {
                    if (err) return console.log(err);

                    var file = fs.createWriteStream(path);
                    https.get(url, function (response) {
                        response.pipe(file);

                        fs.readFile(path, function (err, buf) {
                            if (err) return console.log(err);
                            var fileHash = md5(buf);
                            console.log("Hash: " + fileHash)

                            skinChanger.findExistingSkin(fileHash, name, model, visibility, function (existingSkin) {
                                if (existingSkin) {
                                    res.json(Util.skinToJson(existingSkin, generatorDelay));
                                } else {
                                    var validImage = Util.validateImage(req, res, path);
                                    // cleanup();
                                    if (validImage) {
                                        skinChanger.getAvailableAccount(req, res, function (account) {
                                            skinChanger.generateUrl(account, url, model, function (result) {
                                                fileCleanup();
                                                if (result === true) {
                                                    account.errorCounter = 0;
                                                    account.save(function (err, account) {
                                                        if (err) return console.log(err);
                                                        Traffic.update({ip: req.realAddress}, {lastRequest: Date.now() / 1000}, {upsert: true}, function (err, traffic) {
                                                            if (err) return console.log(err);

                                                            getAndSaveSkinData(account, {
                                                                type: "url",
                                                                model: model,
                                                                visibility: visibility,
                                                                name: name,
                                                                via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                                                            }, fileHash, uuid(), genStart, function (err, skin) {
                                                                if (err) {
                                                                    res.status(500).json({error: "Failed to get skin data", err: err, accountId: account.id});
                                                                    console.log(("Failed to download skin data").warn)

                                                                    console.log("=> FAIL\n".red);
                                                                } else {
                                                                    res.json(Util.skinToJson(skin, generatorDelay));

                                                                    console.log("=> SUCCESS\n".green);
                                                                }
                                                            })
                                                        })
                                                    })
                                                } else {
                                                    res.status(500).json({error: "Failed to generate skin data", err: result, accountId: account.id});
                                                    console.log(("Failed to generate skin data").warn)

                                                    console.log("=> FAIL\n".red);
                                                }
                                            })
                                        })
                                    }
                                }
                            })
                        })
                    });
                })
            });
        })
    })

    app.post("/generate/upload", function (req, res) {
        if (!req.files) {
            res.status(400).json({error: "Missing files"});
            return;
        }
        var model = req.body.model || req.query.model || "steve";
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";

        console.log(req.body)
        console.log(req.query)

        console.log(("FILE:       " + req.files.file).debug);
        console.log(("Model:      " + model).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        var fileUpload = req.files.file;
        if (!fileUpload) {
            res.status(400).json({error: "Missing file"});
            return;
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;

            tmp.file(function (err, path, fd, fileCleanup) {
                if (err) return console.log(err);

                fileUpload.mv(path, function (err) {
                    if (err) return console.log(err);

                    fs.readFile(path, function (err, buf) {
                        if (err) return console.log(err);
                        var fileHash = md5(buf);

                        skinChanger.findExistingSkin(fileHash, name, model, visibility, function (existingSkin) {
                            if (existingSkin) {
                                res.json(Util.skinToJson(existingSkin, generatorDelay));
                            } else {
                                var validImage = Util.validateImage(req, res, path);
                                // cleanup();
                                if (validImage) {
                                    skinChanger.getAvailableAccount(req, res, function (account) {
                                        skinChanger.generateUpload(account, buf, model, function (result) {
                                            fileCleanup();
                                            if (result === true) {
                                                account.errorCounter = 0;
                                                account.save(function (err, account) {
                                                    if (err) return console.log(err);
                                                    Traffic.update({ip: req.realAddress}, {lastRequest: Date.now() / 1000}, {upsert: true}, function (err, traffic) {
                                                        if (err) return console.log(err);

                                                        getAndSaveSkinData(account, {
                                                            type: "upload",
                                                            model: model,
                                                            visibility: visibility,
                                                            name: name,
                                                            via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                                                        }, fileHash, uuid(), genStart, function (err, skin) {
                                                            if (err) {
                                                                res.status(500).json({error: "Failed to get skin data", err: err, accountId: account.id});
                                                                console.log(("Failed to download skin data").warn)

                                                                console.log("=> FAIL\n".red);
                                                            } else {
                                                                res.json(Util.skinToJson(skin, generatorDelay));

                                                                console.log("=> SUCCESS\n".green);
                                                            }
                                                        });
                                                    })
                                                })
                                            } else {
                                                res.status(500).json({error: "Failed to upload skin data (" + result + ")", err: result, accountId: account.id});
                                                console.log(("Failed to upload skin data").warn)

                                                console.log("=> FAIL\n".red);
                                            }
                                        })
                                    })
                                }
                            }
                        })
                    })
                })
            })
        })
    });

    app.get("/generate/user/:uuid", function (req, res) {
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";
        var uuid = req.params.uuid;

        console.log(("USER:       " + uuid).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        var shortUuid = uuid;
        var longUuid = uuid;
        if (shortUuid.indexOf("-") > -1) {
            shortUuid = shortUuid.replace(/-/g, "");
        }
        if (longUuid.indexOf("-") < 0) {
            longUuid = longUuid.substring(0, 8) + "-" + longUuid.substring(8, 8 + 4) + "-" + longUuid.substring(12, 12 + 4) + "-" + longUuid.substring(16, 16 + 4) + "-" + longUuid.substring(20, 20 + 12);
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;
            Skin.findOne({uuid: longUuid, name: name, visibility: visibility}, function (err, skin) {
                if (err) return console.log(err);
                if (skin) {// Skin already generated
                    var time = Date.now() / 1000;
                    if (skin.time > time - 1800) {// Wait 30 minutes before generating again
                        skin.duplicate += 1;
                        skin.save(function (err, skin) {
                            if (err) return console.log(err);

                            res.json(Util.skinToJson(skin, generatorDelay));
                        })
                        return;
                    }
                }

                // Don't generate anything, just need to get the user's live skin data

                getAndSaveSkinData({uuid: shortUuid}, {
                    type: "user",
                    model: "unknown",
                    visibility: visibility,
                    name: name,
                    via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                }, function (skinTexture, cb) {// Generate the file hash from the skin's texture url
                    tmp.file(function (err, path, fd, fileCleanup) {
                        if (err) return console.log(err);

                        var file = fs.createWriteStream(path);
                        https.get(skinTexture.url, function (response) {
                            response.pipe(file);

                            fs.readFile(path, function (err, buf) {
                                if (err) return console.log(err);
                                var fileHash = md5(buf);

                                cb(fileHash);
                                fileCleanup();
                            })
                        })
                    })
                }, longUuid, genStart, function (err, skin) {
                    if (err) {
                        res.status(500).json({error: "Failed to get skin data", err: err});
                        console.log(("Failed to download skin data").warn)

                        console.log("=> FAIL\n".red);
                    } else {
                        res.json(Util.skinToJson(skin, generatorDelay));

                        console.log("=> SUCCESS\n".green);
                    }
                })
            })
        })
    });

    // fileHash can either be the hash, or a callback to get the hash
    function getAndSaveSkinData(account, options, fileHash, uuid, genStart, cb) {
        Skin.findOne({}).sort({id: -1}).exec(function (err, last) {
            if (err) return console.log(err);
            var lastId = last.id;
            dataFetcher.getSkinData(account, function (err, skinData) {
                if (err) {
                    cb(err, null);
                    return console.log(err);
                }

                var textures = JSON.parse(new Buffer(skinData.value, 'base64').toString('utf8')).textures;
                console.log(JSON.stringify(textures).debug);
                var skinTexture = textures.SKIN;

                var fileHashCallback = function (fileHash) {
                    var skin = new Skin({
                        // '_id': mongoose.Types.ObjectId(md5(fileHash + options.name + Date.now())),
                        id: lastId + 1,
                        hash: fileHash,
                        name: options.name,
                        model: options.model,
                        visibility: options.visibility,
                        uuid: uuid,
                        value: skinData.value,
                        signature: skinData.signature,
                        url: skinTexture.url,
                        time: Date.now() / 1000,
                        generateDuration: Date.now() - genStart,
                        account: account.id,
                        type: options.type,
                        duplicate: 0,
                        views: 1,
                        via: options.via || "api",//TODO,
                        apiVer: "node"
                    });
                    skin.save(function (err, skin) {
                        if (err) return console.log(err);
                        console.log(("[Generator] New Skin saved (#" + skin.id + "). Generated in " + (Date.now() - genStart) + "ms").info);
                        cb(null, skin);
                    })
                };

                if (typeof fileHash === "function") {
                    fileHash(skinTexture, fileHashCallback);
                } else {
                    fileHashCallback(fileHash);
                }
            })
        })
    }

}<commit_msg>use http<commit_after>module.exports = function (app) {

    var remoteFileSize = require("remote-file-size");
    var Util = require("../util");
    var http = require('http');
    var https = require('https');
    var fs = require('fs');
    var fileType = require("file-type");
    var imageSize = require("image-size");
    var tmp = require("tmp");
    var md5 = require("md5");
    var uuid = require("uuid/v4");
    var mongoose = require("mongoose");

    var authentication = require("../generator/authentication");
    var dataFetcher = require("../generator/dataFetcher");
    var skinChanger = require("../generator/skinChanger");

    // Schemas
    var Account = require("../db/schemas/account").Account;
    var Skin = require("../db/schemas/skin").Skin;
    var Traffic = require("../db/schemas/traffic").Traffic;

    app.post("/generate/url", function (req, res) {
        var url = req.body.url || req.query.url;
        var model = req.body.model || req.query.model || "steve";
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";

        console.log(req.body)
        console.log(req.query)

        console.log(("URL:        " + url).debug);
        console.log(("Model:      " + model).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        if (!url) {
            res.status(400).json({error: "URL is required"});
            return;
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;

            remoteFileSize(url, function (err, remoteSize) {
                if (remoteSize <= 0 || remoteSize > 102400) {
                    res.status(400).json({error: "Invalid file size"});
                    return;
                }

                tmp.file(function (err, path, fd, fileCleanup) {
                    if (err) return console.log(err);

                    var file = fs.createWriteStream(path);
                    https.get(url, function (response) {
                        response.pipe(file);

                        fs.readFile(path, function (err, buf) {
                            if (err) return console.log(err);
                            var fileHash = md5(buf);
                            console.log("Hash: " + fileHash)

                            skinChanger.findExistingSkin(fileHash, name, model, visibility, function (existingSkin) {
                                if (existingSkin) {
                                    res.json(Util.skinToJson(existingSkin, generatorDelay));
                                } else {
                                    var validImage = Util.validateImage(req, res, path);
                                    // cleanup();
                                    if (validImage) {
                                        skinChanger.getAvailableAccount(req, res, function (account) {
                                            skinChanger.generateUrl(account, url, model, function (result) {
                                                fileCleanup();
                                                if (result === true) {
                                                    account.errorCounter = 0;
                                                    account.save(function (err, account) {
                                                        if (err) return console.log(err);
                                                        Traffic.update({ip: req.realAddress}, {lastRequest: Date.now() / 1000}, {upsert: true}, function (err, traffic) {
                                                            if (err) return console.log(err);

                                                            getAndSaveSkinData(account, {
                                                                type: "url",
                                                                model: model,
                                                                visibility: visibility,
                                                                name: name,
                                                                via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                                                            }, fileHash, uuid(), genStart, function (err, skin) {
                                                                if (err) {
                                                                    res.status(500).json({error: "Failed to get skin data", err: err, accountId: account.id});
                                                                    console.log(("Failed to download skin data").warn)

                                                                    console.log("=> FAIL\n".red);
                                                                } else {
                                                                    res.json(Util.skinToJson(skin, generatorDelay));

                                                                    console.log("=> SUCCESS\n".green);
                                                                }
                                                            })
                                                        })
                                                    })
                                                } else {
                                                    res.status(500).json({error: "Failed to generate skin data", err: result, accountId: account.id});
                                                    console.log(("Failed to generate skin data").warn)

                                                    console.log("=> FAIL\n".red);
                                                }
                                            })
                                        })
                                    }
                                }
                            })
                        })
                    });
                })
            });
        })
    })

    app.post("/generate/upload", function (req, res) {
        if (!req.files) {
            res.status(400).json({error: "Missing files"});
            return;
        }
        var model = req.body.model || req.query.model || "steve";
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";

        console.log(req.body)
        console.log(req.query)

        console.log(("FILE:       " + req.files.file).debug);
        console.log(("Model:      " + model).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        var fileUpload = req.files.file;
        if (!fileUpload) {
            res.status(400).json({error: "Missing file"});
            return;
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;

            tmp.file(function (err, path, fd, fileCleanup) {
                if (err) return console.log(err);

                fileUpload.mv(path, function (err) {
                    if (err) return console.log(err);

                    fs.readFile(path, function (err, buf) {
                        if (err) return console.log(err);
                        var fileHash = md5(buf);

                        skinChanger.findExistingSkin(fileHash, name, model, visibility, function (existingSkin) {
                            if (existingSkin) {
                                res.json(Util.skinToJson(existingSkin, generatorDelay));
                            } else {
                                var validImage = Util.validateImage(req, res, path);
                                // cleanup();
                                if (validImage) {
                                    skinChanger.getAvailableAccount(req, res, function (account) {
                                        skinChanger.generateUpload(account, buf, model, function (result) {
                                            fileCleanup();
                                            if (result === true) {
                                                account.errorCounter = 0;
                                                account.save(function (err, account) {
                                                    if (err) return console.log(err);
                                                    Traffic.update({ip: req.realAddress}, {lastRequest: Date.now() / 1000}, {upsert: true}, function (err, traffic) {
                                                        if (err) return console.log(err);

                                                        getAndSaveSkinData(account, {
                                                            type: "upload",
                                                            model: model,
                                                            visibility: visibility,
                                                            name: name,
                                                            via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                                                        }, fileHash, uuid(), genStart, function (err, skin) {
                                                            if (err) {
                                                                res.status(500).json({error: "Failed to get skin data", err: err, accountId: account.id});
                                                                console.log(("Failed to download skin data").warn)

                                                                console.log("=> FAIL\n".red);
                                                            } else {
                                                                res.json(Util.skinToJson(skin, generatorDelay));

                                                                console.log("=> SUCCESS\n".green);
                                                            }
                                                        });
                                                    })
                                                })
                                            } else {
                                                res.status(500).json({error: "Failed to upload skin data (" + result + ")", err: result, accountId: account.id});
                                                console.log(("Failed to upload skin data").warn)

                                                console.log("=> FAIL\n".red);
                                            }
                                        })
                                    })
                                }
                            }
                        })
                    })
                })
            })
        })
    });

    app.get("/generate/user/:uuid", function (req, res) {
        var visibility = parseInt(req.body.visibility || req.query.visibility) || 0;
        var name = req.body.name || req.query.name || "";
        var uuid = req.params.uuid;

        console.log(("USER:       " + uuid).debug);
        console.log(("Visibility: " + visibility).debug);
        console.log(("Name:       " + name).debug);

        var shortUuid = uuid;
        var longUuid = uuid;
        if (shortUuid.indexOf("-") > -1) {
            shortUuid = shortUuid.replace(/-/g, "");
        }
        if (longUuid.indexOf("-") < 0) {
            longUuid = longUuid.substring(0, 8) + "-" + longUuid.substring(8, 8 + 4) + "-" + longUuid.substring(12, 12 + 4) + "-" + longUuid.substring(16, 16 + 4) + "-" + longUuid.substring(20, 20 + 12);
        }

        var genStart = Date.now();

        Util.checkTraffic(req, res).then(function (allowed, generatorDelay) {
            if (!allowed) return;
            Skin.findOne({uuid: longUuid, name: name, visibility: visibility}, function (err, skin) {
                if (err) return console.log(err);
                if (skin) {// Skin already generated
                    var time = Date.now() / 1000;
                    if (skin.time > time - 1800) {// Wait 30 minutes before generating again
                        skin.duplicate += 1;
                        skin.save(function (err, skin) {
                            if (err) return console.log(err);

                            res.json(Util.skinToJson(skin, generatorDelay));
                        })
                        return;
                    }
                }

                // Don't generate anything, just need to get the user's live skin data

                getAndSaveSkinData({uuid: shortUuid}, {
                    type: "user",
                    model: "unknown",
                    visibility: visibility,
                    name: name,
                    via: (req.headers["referer"] && req.headers["referer"].indexOf("mineskin.org") > -1) ? "website" : "api"
                }, function (skinTexture, cb) {// Generate the file hash from the skin's texture url
                    tmp.file(function (err, path, fd, fileCleanup) {
                        if (err) return console.log(err);

                        var file = fs.createWriteStream(path);
                        http.get(skinTexture.url, function (response) {
                            response.pipe(file);

                            fs.readFile(path, function (err, buf) {
                                if (err) return console.log(err);
                                var fileHash = md5(buf);

                                cb(fileHash);
                                fileCleanup();
                            })
                        })
                    })
                }, longUuid, genStart, function (err, skin) {
                    if (err) {
                        res.status(500).json({error: "Failed to get skin data", err: err});
                        console.log(("Failed to download skin data").warn)

                        console.log("=> FAIL\n".red);
                    } else {
                        res.json(Util.skinToJson(skin, generatorDelay));

                        console.log("=> SUCCESS\n".green);
                    }
                })
            })
        })
    });

    // fileHash can either be the hash, or a callback to get the hash
    function getAndSaveSkinData(account, options, fileHash, uuid, genStart, cb) {
        Skin.findOne({}).sort({id: -1}).exec(function (err, last) {
            if (err) return console.log(err);
            var lastId = last.id;
            dataFetcher.getSkinData(account, function (err, skinData) {
                if (err) {
                    cb(err, null);
                    return console.log(err);
                }

                var textures = JSON.parse(new Buffer(skinData.value, 'base64').toString('utf8')).textures;
                console.log(JSON.stringify(textures).debug);
                var skinTexture = textures.SKIN;

                var fileHashCallback = function (fileHash) {
                    var skin = new Skin({
                        // '_id': mongoose.Types.ObjectId(md5(fileHash + options.name + Date.now())),
                        id: lastId + 1,
                        hash: fileHash,
                        name: options.name,
                        model: options.model,
                        visibility: options.visibility,
                        uuid: uuid,
                        value: skinData.value,
                        signature: skinData.signature,
                        url: skinTexture.url,
                        time: Date.now() / 1000,
                        generateDuration: Date.now() - genStart,
                        account: account.id,
                        type: options.type,
                        duplicate: 0,
                        views: 1,
                        via: options.via || "api",//TODO,
                        apiVer: "node"
                    });
                    skin.save(function (err, skin) {
                        if (err) return console.log(err);
                        console.log(("[Generator] New Skin saved (#" + skin.id + "). Generated in " + (Date.now() - genStart) + "ms").info);
                        cb(null, skin);
                    })
                };

                if (typeof fileHash === "function") {
                    fileHash(skinTexture, fileHashCallback);
                } else {
                    fileHashCallback(fileHash);
                }
            })
        })
    }

}<|endoftext|>


<commit_before>/**
 * Created by adi on 1/20/2017.
 */
House = function (game, x, y, resource, agents) {
    this.type = "House";
    this.game = game
    this.agents = agents;
    this.agentRate =  1;// Utils.randomInt(6,12);
    Building.call(this, game, x, y, resource);
}

House.prototype = Object.create(Building.prototype);
House.prototype.constructor = House;

House.prototype.setAgentNum = function (num) {
    this.agentNum = num;
}

House.prototype.emit = function(){
    this.game.levelState.emittedAgents++;
    var agent = new Agent(this.game, this.x +30 , this.y  , 0.3, 1, 0);
    this.game.add.existing(agent);
    agents.push(agent);
}

House.prototype.doTick = function(time) {
    var emittedAgents = this.game.levelState.emittedAgents;
    var totalAgentNumber = gameLevelParams.totalAgentNumber;
    if (emittedAgents >= totalAgentNumber) {
        return;
    }
    var leftToEmit = totalAgentNumber - emittedAgents;
    if (((time/1000 - this.lastWavesSentTime / 1000) > this.agentRate) && leftToEmit > 0) {
        this.emit();
        this.lastWavesSentTime = time;
    }
}

House.prototype.getRoad = function () {
    var roads = Utils.getAdjacentRoads(Utils.locToTile(this.x, this.y));
    return roads;
}

<commit_msg>agent emit rate<commit_after>/**
 * Created by adi on 1/20/2017.
 */
House = function (game, x, y, resource, agents) {
    this.type = "House";
    this.game = game
    this.agents = agents;
    this.agentRate = Utils.randomInt(2,8);
    Building.call(this, game, x, y, resource);
}

House.prototype = Object.create(Building.prototype);
House.prototype.constructor = House;

House.prototype.setAgentNum = function (num) {
    this.agentNum = num;
}

House.prototype.emit = function(){
    this.game.levelState.emittedAgents++;
    var agent = new Agent(this.game, this.x +30 , this.y  , 0.3, 1, 0);
    this.game.add.existing(agent);
    agents.push(agent);
}

House.prototype.doTick = function(time) {
    var emittedAgents = this.game.levelState.emittedAgents;
    var totalAgentNumber = gameLevelParams.totalAgentNumber;
    if (emittedAgents >= totalAgentNumber) {
        return;
    }
    var leftToEmit = totalAgentNumber - emittedAgents;
    if (((time/1000 - this.lastWavesSentTime / 1000) > this.agentRate) && leftToEmit > 0) {
        this.emit();
        this.lastWavesSentTime = time;
    }
}

House.prototype.getRoad = function () {
    var roads = Utils.getAdjacentRoads(Utils.locToTile(this.x, this.y));
    return roads;
}

<|endoftext|>


<commit_before>var request = require('request');
var passport = {};
var os = require('os');

passport.getIP = function (port) {
    var self = this;

    self.ip = getIpAddress(port);
    return self.ip;

};

function getIpAddress(port) {
    var ifaces = os.networkInterfaces();
    var ipAddress = 'localhost';
    for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (details.family == 'IPv4' && !details.internal) {
                ipAddress = details.address;
            }
        });
    }
    var link = 'http://' + ipAddress + ':' + port;
    return link;
}

passport.authorize = function (req, res, next) {
  console.log("req.session.passportToken"+req.session.passportToken)
    if (req.session.passportToken) {
        next(req, res);
    } else {
        res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
    }
};

passport.init = function (router, opt) {
    passport.opt = opt;

    router.get('/passportAuth', function (req, res) {
        var code = req.query.code;
        request(passport.opt.passport + '/token', {
            method: 'POST',
            form: {code: code}
        }, function (re, rs, obj) {
          console.log("tokenobj"+obj)
            obj = JSON.parse(obj);
            req.session.passportToken = obj.model.token;
            passport.login(req, res, function () {
                res.redirect(passport.opt.backUrl);
            });

        });
    });
};

passport.login = function (req, res, cb) {
    var passportToken = req.session.passportToken;
  console.log("~~~~passportToken~~~~~"+passportToken)
    request(passport.opt.passport + '/user', {
        method: 'GET',
        form: {token: passportToken}
    }, function (re, rs, obj) {
        console.log("~~~~obj~~~~~"+obj)
        obj = JSON.parse(obj);
        if (obj.success) {
            if(obj.model.user.__v!=undefined){
                delete obj.model.user.__v;
            }
            req.session.user = obj.model.user;
            cb(obj);
        } else {
            req.session.passportToken = null;
            res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
        }

    });
};

passport.logout = function (req, res, cb) {
    req.session.destroy(function (err) {
        if (err) {
            res.status(500).send({
                success: false,
                model: {
                    error: '注销失败'
                }
            });
        } else {
            res.status(200).send({
                success: true
            });
        }
    });
};

module.exports = passport;
<commit_msg>debgger<commit_after>var request = require('request');
var passport = {};
var os = require('os');

passport.getIP = function (port) {
    var self = this;

    self.ip = getIpAddress(port);
    return self.ip;

};

function getIpAddress(port) {
    var ifaces = os.networkInterfaces();
    var ipAddress = 'localhost';
    for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (details.family == 'IPv4' && !details.internal) {
                ipAddress = details.address;
            }
        });
    }
    var link = 'http://' + ipAddress + ':' + port;
    return link;
}

passport.authorize = function (req, res, next) {
  console.log(req.session.passportToken)
    if (req.session.passportToken) {
        next(req, res);
    } else {
        res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
    }
};

passport.init = function (router, opt) {
    passport.opt = opt;

    router.get('/passportAuth', function (req, res) {
        var code = req.query.code;
        request(passport.opt.passport + '/token', {
            method: 'POST',
            form: {code: code}
        }, function (re, rs, obj) {
          console.log(obj)
            obj = JSON.parse(obj);
            req.session.passportToken = obj.model.token;
            passport.login(req, res, function () {
                res.redirect(passport.opt.backUrl);
            });

        });
    });
};

passport.login = function (req, res, cb) {
    var passportToken = req.session.passportToken;
  console.log(passportToken)
    request(passport.opt.passport + '/user', {
        method: 'GET',
        form: {token: passportToken}
    }, function (re, rs, obj) {
        console.log(obj)
        obj = JSON.parse(obj);
        if (obj.success) {
            if(obj.model.user.__v!=undefined){
                delete obj.model.user.__v;
            }
            req.session.user = obj.model.user;
            cb(obj);
        } else {
            req.session.passportToken = null;
            res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
        }

    });
};

passport.logout = function (req, res, cb) {
    req.session.destroy(function (err) {
        if (err) {
            res.status(500).send({
                success: false,
                model: {
                    error: '注销失败'
                }
            });
        } else {
            res.status(200).send({
                success: true
            });
        }
    });
};

module.exports = passport;
<|endoftext|>


<commit_before>var Project = require('../models/project');
var User = require('../models/user');
var ProjectUser = require('../models/projectUser');
var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/projects').post(createProject);
router.route('/projects').get(getProjects);
router.route('/projects/:project_id').get(getProject);
router.route('/projects/:project_id').put(editProject);
router.route('/projects/:project_id').delete(deleteProject);

module.exports = router;

function createProject(req, res)
{
    var project = new Project();

    if (!("name" in req.body)){
        res.json({message : "Error : No name given !"});
        return ;
    } else
        project.name = req.body.name;

    if (!("type" in req.body)){
        res.json({message : "Error : No type given !"});
        return ;
    } else
        project.type = req.body.type;

    if (!("authorUsername" in req.body)){
        res.json({message : "Error : No authorUsername given !"});
        return ;
    }
    else {
        User.findOne({username : req.body.authorUsername.toLowerCase()}, function(err, user){
            if (err) {
                res.send(err);
            } else if (user === null){
                res.send({message : "Error : authorUsername not found !"});
            } else {
                project.author = user;
                project.save(function(err){
                    if (err) res.send(err);
                    else {
                        var projectUser = new ProjectUser();
                        projectUser.author = project.author;
                        projectUser.thread = project;
                        projectUser.value = 2;

                        projectUser.save(function(err){
                            if (err) res.send(err);
                            else res.json({ message: 'Project created !' });
                        });
                    }
                });
            }
        });
    }
}

function getProjects(req, res)
{
    Project.find(function(err, projects)
    {
        if (err) res.send(err);
        else res.json(projects);
    });
}

function getProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send(err);
        else res.json(project);
    });
}

function editProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        var usernameFound = true;

        if (err) res.send(err);
        if ("name" in req.body) project.name = req.body.name;
        if ("status" in req.body) project.status = req.body.status;
        if ("description" in req.body) project.description = req.body.description;
        if ("type" in req.body) project.type = req.body.type;
        if ("authorUsername" in req.body)
            calls.push(function(callback){
                User.findOne({username : req.body.authorUsername.toLowerCase()}, function(err, user){
                    if (err) usernameFound = false;
                    else project.author = user;
                    callback();
                });
            });

        async.parallel(calls, function(){
            project.save(function(err){
                if (err) res.send(err);
                else if (!usernameFound) res.send({message : 'Project updated but authorUsername not found!'});
                else res.json({ message: 'Project updated!' });
            });
        });

    });
}
function deleteProject(req, res)
{
    Project.remove({_id: req.params.project_id}, function(err, project)
    {
        if (err) res.send(err);
        else res.json({ message: 'Project deleted!' });
    });
}<commit_msg>Add more details in JSON return messages<commit_after>var Project = require('../models/project');
var User = require('../models/user');
var ProjectUser = require('../models/projectUser');
var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/projects').post(createProject);
router.route('/projects').get(getProjects);
router.route('/projects/:project_id').get(getProject);
router.route('/projects/:project_id').put(editProject);
router.route('/projects/:project_id').delete(deleteProject);

module.exports = router;

function createProject(req, res)
{
    var project = new Project();

    if (!("name" in req.body)){
        res.send({message : "Error : No name given!",
                 data : null,
                 success : 0});
        return ;
    } else
        project.name = req.body.name;

    if (!("type" in req.body)){
        res.send({message : "Error : No type given!",
                 data : null,
                 success : 0});
        return ;
    } else
        project.type = req.body.type;

    if (!("authorUsername" in req.body)){
        res.send({message : "Error : No authorUsername given!",
                 data : null,
                 success : 0});
        return ;
    }
    else {
        User.findOne({username : req.body.authorUsername.toLowerCase()}, function(err, user){
            if (err) {
                res.send({message:"Error!", data : err, success : 0});
            } else if (user === null){
                res.send({message : "Error : authorUsername not found!",
                          data : null,
                          success : 0});
            } else {
                project.author = user;
                project.save(function(err){
                    if (err) res.send({message:"Error!", data : err, success : 0});
                    else {
                        var projectUser = new ProjectUser();
                        projectUser.author = project.author;
                        projectUser.thread = project;
                        projectUser.value = 2;

                        projectUser.save(function(err){
                            if (err) res.send({message:"Error!", data : err, success : 0});
                            else res.send({ message: 'Project created!',
                                          data : project,
                                          success : 1});
                        });
                    }
                });
            }
        });
    }
}

function getProjects(req, res)
{
    Project.find(function(err, projects)
    {
        if (err) res.send({message:"Error!", data : err, success : 0});
        else res.send({message : "Projects found!",
                       data : projects,
                       success : 1});
    });
}

function getProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send({message:"Error!", data : err, success : 0});
        else res.send({message : "Project Found!",
                       data : project,
                       success : 1});
    });
}

function editProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        var usernameFound = true;

        if (err) res.send({message:"Error!", data : err, success : 0});
        if ("name" in req.body) project.name = req.body.name;
        if ("status" in req.body) project.status = req.body.status;
        if ("description" in req.body) project.description = req.body.description;
        if ("type" in req.body) project.type = req.body.type;
        if ("authorUsername" in req.body)
            calls.push(function(callback){
                User.findOne({username : req.body.authorUsername.toLowerCase()}, function(err, user){
                    if (err) usernameFound = false;
                    else project.author = user;
                    callback();
                });
            });

        async.parallel(calls, function(){
            project.save(function(err){
                if (err) res.send({message:"Error!", data : err, success : 0});
                else if (!usernameFound) res.send({message : 'Project updated but authorUsername not found!',
                                                  data : project,
                                                  success : 0});
                else res.send({ message: 'Project updated!',
                              data : project,
                              success : 1});
            });
        });

    });
}
function deleteProject(req, res)
{
    Project.remove({_id: req.params.project_id}, function(err, project)
    {
        if (err) res.send({message:"Error!", data : err, success : 0});
        else res.send({ message: 'Project deleted!',
                      data : null,
                      success : 1});
    });
}<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router();
var mongoose = require('mongoose')
var jwt = require('jsonwebtoken')
var moment = require('moment')
var timezone = require('moment-timezone')
var async = require('async');

var Models = require('../models/ScheduleModels.js')
var Account = require('../models/Account.js');

var Period = Models.Period
var Day = Models.Day
var DayType = Models.DayType

var config = require('../config.js');
var secret = config.secret;

var passport = require('passport')
var LocalStrategy = require('passport-local')

var authUtils = require('../utils/auth.js');

router.use(passport.initialize());

passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

/*******************************
 * Unauthenticated routes
 * ****************************/

/**
* @api {get} schedule/ API Status
* @apiName APIStatus
* @apiGroup Schedule
* @apiSuccess {String} message API OK
* @apiSuccessExample Success-Response:
*   API OK
*/

router.get('/', function(req, res) {
    res.json({"message": "API OK"});
});

/**
* @api {get} schedule/day_type Day Type (Letterday)
* @apiName "DayType"
* @apiDescription This endpoint returns the letter day of a given date, or now if none specified.
* @apiGroup Schedule
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {String} date Date in ISO8061 Format, UTC time
* @apiSuccess {String} type Letter Day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Response:
*   {
*       "date": "2016-02-26T13:00:00.000Z",
*       "type": "A"
*   }
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 Bad Request
*   {
*       "error": "Invalid date format"
*   }
*/
router.get('/day_type', function(req, res, next) {
    var date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment().hours(6).minutes(0).seconds(0).milliseconds(0).utc() :
        moment(req.query.date).hours(6).minutes(0).seconds(0).milliseconds(0).utc();

    DayType.findOne({date: date}, function(err, day) {
        if(err) {
            return res.status(500).send({
                success: false,
                error: "Internal server error"
            });
        }

        return res.send({
            date: day.date,
            type: date.type
        });
    });
});
/**
* @api {get} schedule/all_periods All Periods
* @apiName "All_Periods"
* @apiDescription This endpoint returns an array of all of the periods in a date, or today if none is specified.
* @apiGroup Schedule
* @apiHeader {String} [X-Access-Token] User's unique access token
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {Object[]} periods List of periods in a day.
* @apiSuccess {String} periods.title The period number or the user's name for the period provided X-Access-Token was set and the period has been named.
* @apiSuccess {String} periods.start_time Start time of period in UTC timezone
* @apiSuccess {String} periods.end_time End time of period in UTC timezone
* @apiSuccess {String} periods.day The period's associated day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Response:
*   [
*       {
*           "title": "English",
*           "start_time" : "",
*           "end_time": "",
*           "day": ""
*       },
*       {
*           "title": "Period 3",
*           "start_time" : "",
*           "end_time": "",
*           "day": ""
*       }
*       ...
*   ]
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 Bad Request
*   {
*       "error": "Invalid date format"
*   }
*/
router.get('/all_periods', authUtils.nonStrictAuthentication, function(req, res) {
    var date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment().hours(6).minutes(0).seconds(0).milliseconds(0).utc() :
        moment(req.query.date).hours(6).minutes(0).seconds(0).milliseconds(0).utc();

    if(!date.isValid()) {
        res.status(400).send({
            success: false,
            error: "Unable to parse date provided in request"
        });
    }

    Period.find({day: date.toISOString()},'-linked_day -_id -_v', function(error, periods) {
        if(error) res.status(500).send({
            success: false,
            error: "Internal server error"
        });

        result = [];
        async.each(periods, function(period, callback){
            if(req.decoded){
                Account.findOne({username: req.decoded.account.username}, function(err, account){
                    if(err) {
                        return res.status(500).send({
                            success: false,
                            message: "An internal server error has occured."
                        });
                    } else if(!account) {
                        return res.status(404).send({
                            success: false,
                            message: "A user with the given username was not found. Check your token."
                        });
                    } else {
                        period.title = account.classNames[period.title] ? account.classNames[period.title] : period.title;
                        result.push(period);
                        callback();
                    }
                });
            } else {
                result = periods;
                callback();
            }
        }, function(err){
            result.sort(function(a, b) {
                return (new Date(a.start_time)).getTime() - (new Date(b.start_time)).getTime();
            });

            res.json(result);
        });
    });
});
/**
* @api {get} schedule/period Period
* @apiName "Period"
* @apiDescription This endpoint returns the current period if no date is specified, or the current period in the specified day
* @apiGroup Schedule
* @apiHeader {String} [X-Access-Token] User's unique access token
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {String} title The period number or the user's name for the period provided X-Access-Token was set and the period has been named.
* @apiSuccess {String} start_time Start time of period in UTC timezone
* @apiSuccess {String} end_time End time of period in UTC timezone
* @apiSuccess {String} day The period's associated day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Example:
*   {
*       "title": "Period 1",
*       "start_time": "",
*       "end_time": "",
*       "day": ""
*   }
*/
router.get('/period', authUtils.nonStrictAuthentication, function(req, res) {
    let date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment() :
        moment(req.query.date); //moment date parsing tends to be more flexible, specifically with timezones

    if(!date.isValid()) {
        res.status(400).send({
            success: false,
            error: "Unable to parse date provided in request"
        });
    }

    Period.findOne(
        {
            $and: [
                {start_time: {$lte: date.toISOString()}}, //Now "is a period" if the time is in between the start/end time of a period
                {end_time: {$gte: date.toISOString()}}
            ]
        },
        '-linked_day -_id -_v',
        function(error, period) {
            if(error) {
                res.status(500).send({
                    success: false
                });
            } else if(period) {
                //If the user supplied a token that was able to decoded, check for the classNames that might be defined
                if(req.decoded) {
                    Account.findOne({username: req.decoded.account.username}, function(err, account){
                        if(err) res.json(500, {"message": "An internal server error has occured."});
                        else if(!account) res.json(401, {"message": "A user with the given username was not found. Check your token."});
                        else {
                            //If the account has a named period, rename it in the response accordingly
                            period.title = account.classNames[period.title] ? account.classNames[period.title] : period.title;
                            res.send(period);
                        }
                    });
                } else {
                    res.send(period);
                }
            } else {
                res.send({});
            }
    });

});
/**
* @api {post} schedule/register Register Account
* @apiName "Register Account"
* @apiDescription This endpoint creates a user account in the database and returns a token.
* @apiGroup Schedule
* @apiParam {String} username Account Username
* @apiParam {String} password Account Password
* @apiSuccess {String} message Creation status
* @apiSuccess {String} token User token
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "Account created",
*       "token": "<USER_TOKEN>"
*   }
*/
router.post('/register', function(req, res) {
    Account.register(new Account({username: req.body.username, userType: "User"}), req.body.password, function(err, account) {
        if(err) {
            return res.json({message:'Error creating account', account: account});
        }

        var token = jwt.sign({account: account}, secret, {
            expiresIn: "365 days"
        });

        res.json({message:'Account created', token:token});
    });
});
/**
* @api {post} schedule/get-token GetToken
* @apiName "Get Token"
* @apiDescription This endpoint returns a user's token after authentication.
* @apiGroup Schedule
* @apiParam {String} username Account Username
* @apiParam {String} password Account Password
* @apiSuccess {String} message Token retrieval status
* @apiSuccess {String} token User token
* @apiError 400 The user with the given username/password does not exist.
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "Here is your token",
*       "token": "<USER_TOKEN>"
*   }
*/
router.post('/get-token', function(req, res) {
        Account.findOne({username:req.body.username}, function(err, account) {
                if(err) {
                        res.json(400, {error: 'User not found'});
                }

                var token = jwt.sign({account: account}, secret, {
                        expiresIn: "365 days"
                });

                passport.authenticate('local')(req, res, function() {
                        res.json({
                                message: 'Here is your token',
                                token: token
                        });
                });

        });
});

//Auth

router.use(authUtils.strictAuthentication);

/********************************
 * Authenticated Routes
 * ******************************/

router.post('/period', function(req,res){
        var userType = req.decoded.account.userType;
        if (userType == "Admin") {
                DayType.findOne({ date: req.body.day }, function(error, result) {
                        if (error) {
                            return res.status(500).send({
                                success: false
                            });
                        } else if (result) {
                                var newPeriod = new Period({
                                        day: new Date(req.body.day),
                                        start_time: new Date(req.body.start_time),
                                        end_time: new Date(req.body.end_time),
                                        title: req.body.title,
                                        linked_day: result._id
                                });
                                newPeriod.save((err, result) => {
                                    if (err) {
                                        return res.status(500).send({
                                            success: false
                                        });
                                    }

                                    return res.send({
                                        period: newPeriod
                                    });
                                });
                        }
                });
        } else {
                res.json(401, {"message": "You do not have permission to perform that action"});
        }
});

router.post('/day_type', function(req,res){
    var userType = req.decoded.account.userType;
    if(userType == "Admin") {
        var date = moment(req.body.date).tz('America/Denver').hours(6).minutes(0).seconds(0).milliseconds(0).utc();
        DayType.create({
            'date': date,
            'type': req.body.type
        },
        function(err,post){
            if(err) res.json("error");
                res.json(post);
            });
    } else {
        res.json(401, {"message": "You do not have permission to perform that action"});
    }
});
/**
* @api {get} schedule/name_period Name Period
* @apiName "Name Period"
* @apiDescription This endpoint associates a period number with a user-specifice dname.
* @apiGroup Schedule
* @apiParam {String} period Period number to replace (ex. "Period 1")
* @apiParam {String} periodName Name for the period.
* @apiSuccess {String} message Success message
* @apiError 400 The user with the given username does not exist.
* @apiError 500 An internal server error has occured
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "success"
*   }
*/
router.get('/name_period', function(req,res){
    Account.findOne({"username": req.decoded.account.username}, function(err, account){
        if(err) res.json(500, {"message": "An internal server error has occured"});
        else if(!account) res.json(401, {"message": "No user with the given username could be found."});
        else {
            if(account.classNames === undefined) {
                account.classNames = {};
            }
            account.classNames[req.query.period] = req.query.periodName;
            account.markModified('classNames');
            account.save();

            res.send({"message": "success"});
        }
    });
});

router.get('/auth-test', function(req, res) {
        res.json('Authentication successful!');
});

module.exports = router;
<commit_msg>Fix schedule endpoint<commit_after>var express = require('express')
var router = express.Router();
var mongoose = require('mongoose')
var jwt = require('jsonwebtoken')
var moment = require('moment')
var timezone = require('moment-timezone')
var async = require('async');

var Models = require('../models/ScheduleModels.js')
var Account = require('../models/Account.js');

var Period = Models.Period
var Day = Models.Day
var DayType = Models.DayType

var config = require('../config.js');
var secret = config.secret;

var passport = require('passport')
var LocalStrategy = require('passport-local')

var authUtils = require('../utils/auth.js');

router.use(passport.initialize());

passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

/*******************************
 * Unauthenticated routes
 * ****************************/

/**
* @api {get} schedule/ API Status
* @apiName APIStatus
* @apiGroup Schedule
* @apiSuccess {String} message API OK
* @apiSuccessExample Success-Response:
*   API OK
*/

router.get('/', function(req, res) {
    res.json({"message": "API OK"});
});

/**
* @api {get} schedule/day_type Day Type (Letterday)
* @apiName "DayType"
* @apiDescription This endpoint returns the letter day of a given date, or now if none specified.
* @apiGroup Schedule
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {String} date Date in ISO8061 Format, UTC time
* @apiSuccess {String} type Letter Day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Response:
*   {
*       "date": "2016-02-26T13:00:00.000Z",
*       "type": "A"
*   }
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 Bad Request
*   {
*       "error": "Invalid date format"
*   }
*/
router.get('/day_type', function(req, res, next) {
    var date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment().hours(6).minutes(0).seconds(0).milliseconds(0).utc() :
        moment(req.query.date).hours(6).minutes(0).seconds(0).milliseconds(0).utc();

    DayType.findOne({date: date.toISOString()}, function(err, day) {
        if(err) {
            return res.status(500).send({
                success: false,
                error: "Internal server error"
            });
        }

        if (day) {
            return res.send({
                date: day.date,
                type: date.type
            });
        }

        return res.send({
            date: "No school",
            type: "No"
        });
    });
});
/**
* @api {get} schedule/all_periods All Periods
* @apiName "All_Periods"
* @apiDescription This endpoint returns an array of all of the periods in a date, or today if none is specified.
* @apiGroup Schedule
* @apiHeader {String} [X-Access-Token] User's unique access token
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {Object[]} periods List of periods in a day.
* @apiSuccess {String} periods.title The period number or the user's name for the period provided X-Access-Token was set and the period has been named.
* @apiSuccess {String} periods.start_time Start time of period in UTC timezone
* @apiSuccess {String} periods.end_time End time of period in UTC timezone
* @apiSuccess {String} periods.day The period's associated day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Response:
*   [
*       {
*           "title": "English",
*           "start_time" : "",
*           "end_time": "",
*           "day": ""
*       },
*       {
*           "title": "Period 3",
*           "start_time" : "",
*           "end_time": "",
*           "day": ""
*       }
*       ...
*   ]
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 Bad Request
*   {
*       "error": "Invalid date format"
*   }
*/
router.get('/all_periods', authUtils.nonStrictAuthentication, function(req, res) {
    var date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment().hours(6).minutes(0).seconds(0).milliseconds(0).utc() :
        moment(req.query.date).hours(6).minutes(0).seconds(0).milliseconds(0).utc();

    if(!date.isValid()) {
        res.status(400).send({
            success: false,
            error: "Unable to parse date provided in request"
        });
    }

    Period.find({day: date.toISOString()},'-linked_day -_id -_v', function(error, periods) {
        if(error) res.status(500).send({
            success: false,
            error: "Internal server error"
        });

        result = [];
        async.each(periods, function(period, callback){
            if(req.decoded){
                Account.findOne({username: req.decoded.account.username}, function(err, account){
                    if(err) {
                        return res.status(500).send({
                            success: false,
                            message: "An internal server error has occured."
                        });
                    } else if(!account) {
                        return res.status(404).send({
                            success: false,
                            message: "A user with the given username was not found. Check your token."
                        });
                    } else {
                        period.title = account.classNames[period.title] ? account.classNames[period.title] : period.title;
                        result.push(period);
                        callback();
                    }
                });
            } else {
                result = periods;
                callback();
            }
        }, function(err){
            result.sort(function(a, b) {
                return (new Date(a.start_time)).getTime() - (new Date(b.start_time)).getTime();
            });

            res.json(result);
        });
    });
});
/**
* @api {get} schedule/period Period
* @apiName "Period"
* @apiDescription This endpoint returns the current period if no date is specified, or the current period in the specified day
* @apiGroup Schedule
* @apiHeader {String} [X-Access-Token] User's unique access token
* @apiParam {String} date=now an ISO 8061 date string
* @apiSuccess {String} title The period number or the user's name for the period provided X-Access-Token was set and the period has been named.
* @apiSuccess {String} start_time Start time of period in UTC timezone
* @apiSuccess {String} end_time End time of period in UTC timezone
* @apiSuccess {String} day The period's associated day
* @apiError 400 The date query was formatted incorrectly or is an invalid range.
* @apiSuccessExample {json} Success-Example:
*   {
*       "title": "Period 1",
*       "start_time": "",
*       "end_time": "",
*       "day": ""
*   }
*/
router.get('/period', authUtils.nonStrictAuthentication, function(req, res) {
    let date = (req.query.date === 'now' || typeof req.query.date === 'undefined') ?
        moment() :
        moment(req.query.date); //moment date parsing tends to be more flexible, specifically with timezones

    if(!date.isValid()) {
        res.status(400).send({
            success: false,
            error: "Unable to parse date provided in request"
        });
    }

    Period.findOne(
        {
            $and: [
                {start_time: {$lte: date.toISOString()}}, //Now "is a period" if the time is in between the start/end time of a period
                {end_time: {$gte: date.toISOString()}}
            ]
        },
        '-linked_day -_id -_v',
        function(error, period) {
            if(error) {
                res.status(500).send({
                    success: false
                });
            } else if(period) {
                //If the user supplied a token that was able to decoded, check for the classNames that might be defined
                if(req.decoded) {
                    Account.findOne({username: req.decoded.account.username}, function(err, account){
                        if(err) res.json(500, {"message": "An internal server error has occured."});
                        else if(!account) res.json(401, {"message": "A user with the given username was not found. Check your token."});
                        else {
                            //If the account has a named period, rename it in the response accordingly
                            period.title = account.classNames[period.title] ? account.classNames[period.title] : period.title;
                            res.send(period);
                        }
                    });
                } else {
                    res.send(period);
                }
            } else {
                res.send({});
            }
    });

});
/**
* @api {post} schedule/register Register Account
* @apiName "Register Account"
* @apiDescription This endpoint creates a user account in the database and returns a token.
* @apiGroup Schedule
* @apiParam {String} username Account Username
* @apiParam {String} password Account Password
* @apiSuccess {String} message Creation status
* @apiSuccess {String} token User token
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "Account created",
*       "token": "<USER_TOKEN>"
*   }
*/
router.post('/register', function(req, res) {
    Account.register(new Account({username: req.body.username, userType: "User"}), req.body.password, function(err, account) {
        if(err) {
            return res.json({message:'Error creating account', account: account});
        }

        var token = jwt.sign({account: account}, secret, {
            expiresIn: "365 days"
        });

        res.json({message:'Account created', token:token});
    });
});
/**
* @api {post} schedule/get-token GetToken
* @apiName "Get Token"
* @apiDescription This endpoint returns a user's token after authentication.
* @apiGroup Schedule
* @apiParam {String} username Account Username
* @apiParam {String} password Account Password
* @apiSuccess {String} message Token retrieval status
* @apiSuccess {String} token User token
* @apiError 400 The user with the given username/password does not exist.
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "Here is your token",
*       "token": "<USER_TOKEN>"
*   }
*/
router.post('/get-token', function(req, res) {
        Account.findOne({username:req.body.username}, function(err, account) {
                if(err) {
                        res.json(400, {error: 'User not found'});
                }

                var token = jwt.sign({account: account}, secret, {
                        expiresIn: "365 days"
                });

                passport.authenticate('local')(req, res, function() {
                        res.json({
                                message: 'Here is your token',
                                token: token
                        });
                });

        });
});

//Auth

router.use(authUtils.strictAuthentication);

/********************************
 * Authenticated Routes
 * ******************************/

router.post('/period', function(req,res){
        var userType = req.decoded.account.userType;
        if (userType == "Admin") {
                DayType.findOne({ date: req.body.day }, function(error, result) {
                        if (error) {
                            return res.status(500).send({
                                success: false
                            });
                        } else if (result) {
                                var newPeriod = new Period({
                                        day: new Date(req.body.day),
                                        start_time: new Date(req.body.start_time),
                                        end_time: new Date(req.body.end_time),
                                        title: req.body.title,
                                        linked_day: result._id
                                });
                                newPeriod.save((err, result) => {
                                    if (err) {
                                        return res.status(500).send({
                                            success: false
                                        });
                                    }

                                    return res.send({
                                        period: newPeriod
                                    });
                                });
                        }
                });
        } else {
                res.json(401, {"message": "You do not have permission to perform that action"});
        }
});

router.post('/day_type', function(req,res){
    var userType = req.decoded.account.userType;
    if(userType == "Admin") {
        var date = moment(req.body.date).tz('America/Denver').hours(6).minutes(0).seconds(0).milliseconds(0).utc();
        DayType.create({
            'date': date,
            'type': req.body.type
        },
        function(err,post){
            if(err) res.json("error");
                res.json(post);
            });
    } else {
        res.json(401, {"message": "You do not have permission to perform that action"});
    }
});
/**
* @api {get} schedule/name_period Name Period
* @apiName "Name Period"
* @apiDescription This endpoint associates a period number with a user-specifice dname.
* @apiGroup Schedule
* @apiParam {String} period Period number to replace (ex. "Period 1")
* @apiParam {String} periodName Name for the period.
* @apiSuccess {String} message Success message
* @apiError 400 The user with the given username does not exist.
* @apiError 500 An internal server error has occured
* @apiSuccessExample {json} Success-Response:
*   {
*       "message": "success"
*   }
*/
router.get('/name_period', function(req,res){
    Account.findOne({"username": req.decoded.account.username}, function(err, account){
        if(err) res.json(500, {"message": "An internal server error has occured"});
        else if(!account) res.json(401, {"message": "No user with the given username could be found."});
        else {
            if(account.classNames === undefined) {
                account.classNames = {};
            }
            account.classNames[req.query.period] = req.query.periodName;
            account.markModified('classNames');
            account.save();

            res.send({"message": "success"});
        }
    });
});

router.get('/auth-test', function(req, res) {
        res.json('Authentication successful!');
});

module.exports = router;
<|endoftext|>