<commit_before>/**
 * Ejemplo de servicio basado en Node.js para crear contenido dinámico para un bot.
 *
 */

// Puerto en el que escucha el servidor Node.js (lo obtiene de una variable de entorno y si no existe, el 3000)
const PORT = process.env.PORT || 3000;

// Importamos el framework Express y lo inicializamos
var express = require("express");
var app = express();

// El contenido de la carpeta public se muestra en la raíz del servidor
app.use(express.static(__dirname + "/public"));

/*
 GET /plazo/:fecha

 Ruta que calcula el número de días que faltan para una fecha

 Si el servidor se está ejecutando localmente:

 http://localhost:3000/plazo/2017-01-31T23:59:59.000Z

 Devuelve un objeto JSON con el formato:

 [{"text":"Faltan 59 días..."}]
 */
 /*
app.get("/plazo/:fecha", function (req, res) {

    // Obtener la fecha que llega en la URL
    var fecha_entrega = new Date(req.params.fecha);
    var ahora = new Date();

    // Algo no ha ido bien
    if (!fecha_entrega) {
        return res.status(400).send();
    }

    // http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
    var oneDay = 24 * 60 * 60 * 1000;
    var dias = Math.round(Math.abs((ahora.getTime() - fecha_entrega.getTime()) / (oneDay)));

    // Crear el objeto con la respuesta
    var respuesta = [
        {
            text: "Faltan " + dias + " días...",
        }
    ];

    // Devolver el objeto en formato JSON
    res.json(respuesta);
});
*/

app.get("/castellano", function (req, res){

	var d = new Date();
	var n = d.getHours();

	if (n >= 0 && n < 6 || n >= 21) {
		var respuesta = [
			{
				text: "¡¡Buenas noches!!",
			}
		];
	} else if (n >= 6 && n < 12) {
		var respuesta = [
			{
				text: "¡¡Buenos días!!",
			}
		];
	} else if (n >= 12 && n < 21) {
		var respuesta = [
			{
				text: "¡¡Buenas tardes!!",
			}
		];
	}

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});
app.get("/euskara", function (req, res){

	var d = new Date();
	var n = d.getHours();

	if (n >= 0 && n < 6 || n >= 21) {
		var respuesta = [
			{
				text: "Gabon!!",
			}
		];
	} else if (n >= 6 && n < 12) {
		var respuesta = [
			{
				text: "Egun on!!",
			}
		];
	} else if (n >= 12 && n < 21) {
		var respuesta = [
			{
				text: "Arratsalde on!!",
			}
		];
	}

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

// Arrancar el servidor y dejarlo a la espera
app.listen(PORT, function () {
    console.log("Servidor Express escuchando en el puerto " + PORT + "...");
});
<commit_msg>server secretarias<commit_after>/**
 * Ejemplo de servicio basado en Node.js para crear contenido dinámico para un bot.
 *
 */

// Puerto en el que escucha el servidor Node.js (lo obtiene de una variable de entorno y si no existe, el 3000)
const PORT = process.env.PORT || 3000;

// Importamos el framework Express y lo inicializamos
var express = require("express");
var app = express();

// El contenido de la carpeta public se muestra en la raíz del servidor
app.use(express.static(__dirname + "/public"));

/*
 GET /plazo/:fecha

 Ruta que calcula el número de días que faltan para una fecha

 Si el servidor se está ejecutando localmente:

 http://localhost:3000/plazo/2017-01-31T23:59:59.000Z

 Devuelve un objeto JSON con el formato:

 [{"text":"Faltan 59 días..."}]
 */
 /*
app.get("/plazo/:fecha", function (req, res) {

    // Obtener la fecha que llega en la URL
    var fecha_entrega = new Date(req.params.fecha);
    var ahora = new Date();

    // Algo no ha ido bien
    if (!fecha_entrega) {
        return res.status(400).send();
    }

    // http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
    var oneDay = 24 * 60 * 60 * 1000;
    var dias = Math.round(Math.abs((ahora.getTime() - fecha_entrega.getTime()) / (oneDay)));

    // Crear el objeto con la respuesta
    var respuesta = [
        {
            text: "Faltan " + dias + " días...",
        }
    ];

    // Devolver el objeto en formato JSON
    res.json(respuesta);
});
*/

app.get("/castellano", function (req, res){

	var d = new Date();
	var n = d.getHours();

	if (n >= 0 && n < 6 || n >= 21) {
		var respuesta = [
			{
				text: "¡¡Buenas noches!!",
			}
		];
	} else if (n >= 6 && n < 12) {
		var respuesta = [
			{
				text: "¡¡Buenos días!!",
			}
		];
	} else if (n >= 12 && n < 21) {
		var respuesta = [
			{
				text: "¡¡Buenas tardes!!",
			}
		];
	}

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});
app.get("/euskara", function (req, res){

	var d = new Date();
	var n = d.getHours();

	if (n >= 0 && n < 6 || n >= 21) {
		var respuesta = [
			{
				text: "Gabon!!",
			}
		];
	} else if (n >= 6 && n < 12) {
		var respuesta = [
			{
				text: "Egun on!!",
			}
		];
	} else if (n >= 12 && n < 21) {
		var respuesta = [
			{
				text: "Arratsalde on!!",
			}
		];
	}

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/castArriaga", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 18){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/euskArriaga", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 18){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/castJO", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 19){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/euskJO", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 19){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/castMendi", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4 || day == 5){

    if(hour >= 8 && hour < 12 || hour == 12 && minutes < 45){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }

  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/eusMendi", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4 || day == 5){

    if(hour >= 8 && hour < 12 || hour == 12 && minutes < 45){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }

  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/castMoliNC", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30){
		var respuesta = [
			{
				text: "¡Ahora está abierta!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Está cerrada ahora mismo...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

app.get("/eusMoliNC", function (req, res){

  var now = new Date();
  var hour = now.getHours();
  var day = now.getDay();
  var minutes = now.getMinutes();

  if(day == 1 || day == 2 ||day == 3 ||day == 4){

    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30 || hour >= 16 && hour < 20){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }

  } else if (day == 5) {
    if(hour >= 8 && hour <= 13 || hour == 13 && minutes < 30){
		var respuesta = [
			{
				text: "Irekita dago oraintxe bertan!",
			}
		];
    } else {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
    }
  } else if (day == 6 || day == 7) {
		var respuesta = [
			{
				text: "Oraintxe bertan itxita dago...",
			}
		];
  }

	// Devolver el objeto en formato JSON
            res.json(respuesta);

});

// Arrancar el servidor y dejarlo a la espera
app.listen(PORT, function () {
    console.log("Servidor Express escuchando en el puerto " + PORT + "...");
});
<|endoftext|>


<commit_before>var to_preflop = 0;
var push = false;

function socket_listens_players(socket, table) {
    var player; // Current player.
    var curseat; // Current seat.
    var channel; // Channel involved.
    //table = get_table(table.id, tables);

    /*socket.on("nb player", function(nb) {
    	nb_player = nb;
    	console.log('first '+ nb_player);
    })*/
    socket.on("is valid nickname", function(nickname, seat_idx) {
        curseat = get_seat(table.seats, seat_idx);
        channel = get_private_id(table.private_ids, seat_idx);
        if (!nickname || check_blanks(nickname) || nickname.length < 2 || nickname.length > 8) {
            console.log("Invalid nickname!");
            socket.emit("is valid nickname info", "invalid");
        } else if (table.nicknames.indexOf(nickname) != -1) {
            console.log("Nickname already taken!");
            socket.emit("is valid nickname info", "already taken");
        } else if (curseat.state != "available")
            socket.emit("is valid nickname info", "seat busy");
        else {
            console.log(nickname + " is valid!");
            socket.emit("is valid nickname info", "valid", nickname);
            table.nicknames.push(nickname); // Add the user nickname to the table nicknames array.
            if (table.players_nb < 6)
                ++table.players_nb;
            console.log("There are now " + table.players_nb + " seated at the table (imo of course)!");
            player = new Player(seat_idx, nickname, +table.start_bankroll, -1, -1, -1, -1);
            curseat.state = "busy";
            curseat.player = player;
            console.log("Seat" + seat_idx + " is now " + curseat.state);
            io.to(table.id).emit("new player", player);
            if (table.playing_seats.indexOf(seat_idx) != -1)
                return;
				console.log('first '+table.playing_seats.length);
			if (table.playing_seats.length == 1)
                tryChrono(socket, table);
            if (table.game.moment == "waiting")
                table.playing_seats.push(seat_idx);
            for (var i = 0; i < table.playing_seats.length; i++)
                get_seat(table.seats, table.playing_seats[i]).state = "playing";
			console.log('second '+table.playing_seats.length);
            if (table.playing_seats.length >= 1 && table.game.moment == "waiting") {
                if (table.playing_seats.length > 1)
                    return;
				console.log('third '+table.playing_seats.length);
                tryChrono(socket, table);
            }
            return;
        }
    });
    socket.on("get seated players", function() {
        send_seats_infos(table);
    });
    socket.on("get board", function() {
        if (table.game.board.length >= 3)
            io.to(table.id).emit("send flop", table.game.board[0], table.game.board[1], table.game.board[2]);
        if (table.game.board.length >= 4)
            io.to(table.id).emit("send turn", table.game.board[3]);
        if (table.game.board.length === 5)
            io.to(table.id).emit("send river", table.game.board[4]);
    });
    socket.on("to preflop", function(init) {
        to_preflop = init;
    });
    socket.on("player decision", function(decision, channel_id, bet_amount, rc) {
        if (!decision || !channel_id)
            return;
        var seat_nb = +channel_id[channel_id.length - 1];

        if (table.playing_seats.length == 2)
            table.game.highlights_pos = seat_nb;
        if (seat_nb != table.game.highlights_pos)
            return;
        if (bet_amount && bet_amount[bet_amount.length - 1] == "$") {
            bet_amount = bet_amount.slice(0, bet_amount.length - 1);
            bet_amount = (Math.round(+bet_amount * 100)) / 100;
        }
        console.log(decision + " " + bet_amount + " has been chosen by seat n°" + seat_nb);
        treat_decision(table, get_seat(table.seats, seat_nb), decision, bet_amount, get_seat(table.seats, seat_nb).player, seat_nb, rc);
        io.to(table.id).emit("last action", decision, seat_nb, bet_amount);
        console.log(table.game.round_nb + "/" + table.playing_seats.length);
        if (table.game.round_nb >= table.playing_seats.length && check_bets(table, table.seats)) {
            if (table.playing_seats.length < 2) {
                return one_playing_player_left(table);
            }
            console.log('next_moment');
            next_moment(table, table.game);
        } else {
            if (table.playing_seats.length < 2) {
                return one_playing_player_left(table);
            }
            console.log('switch next player');
            switch_next_player(table);
        }
        ++table.game.round_nb;
    });
}

function tryChrono(socket, table) {
    var chrono = setInterval(function() {
        push = false;
        clearInterval(chrono);
    }, 45000);
    if (push == false) {
        io.to(table.id).emit("chrono", 45, "The game will begin ...");
        push = true;
    }
    var timer = setInterval(function() {
        clearInterval(timer);
        io.to(table.id).emit("chrono off");
        if (table.playing_seats.length > 1) {
            console.log("Starting a new game...");
            new_cashgame(socket, table);
        } else
            tryChrono(socket, table);
    }, 45000);
}

function treat_decision(table, seat, decision, bet_amount, player, seat_nb, rc) {
    if (decision == "FOLD")
        decision = "FOLD";
    else if (rc == "undefined")
        decision = "CALL";
    else if (rc == 1)
        decision = "RAISE";
    if (decision == "CHECK" && +seat.bet === +table.game.curbet)
        return (1);
    else if (decision == "CALL") {
        player.bankroll -= (+table.game.curbet - +seat.bet) > 0 ? (+table.game.curbet - +seat.bet) : +table.game.curbet;
        if (player.bankroll < 0)
            player.bankroll = 0;
        seat.bet = +seat.bet + +bet_amount;
        seat.bet = Math.round(seat.bet * 100) / 100;
        seat.bet = +seat.bet + (+table.game.curbet - +seat.bet);
        table.game.pot_amount = +table.game.pot_amount + +bet_amount;
        io.to(table.id).emit("bet", seat_nb, +seat.bet);
        io.to(table.id).emit("bankroll modification", seat_nb, player);
        io.to(table.id).emit("pot modification", +table.game.pot_amount);
        return (1);
    } else if (decision == "RAISE" || decision == "BET") {
        if (bet_amount > player.bankroll || bet_amount <= 0)
            return (0);
        player.bankroll -= +bet_amount;
        if (player.bankroll < 0)
            player.bankroll = 0;
        table.game.curbet = +bet_amount /*+ +seat.bet*/ ;
        seat.bet = /*+seat.bet +*/ +bet_amount;
        seat.bet = Math.round(seat.bet * 100) / 100;
        table.game.pot_amount = +table.game.pot_amount + +bet_amount;
        io.to(table.id).emit("bet", seat_nb, +seat.bet);
        io.to(table.id).emit("bankroll modification", seat_nb, player);
        io.to(table.id).emit("pot modification", +table.game.pot_amount);
        return (1);
    } else if (decision == "FOLD") {
        remove_from_playing_seats(table.playing_seats, seat_nb);
        seat.state = "busy";
        io.to(table.id).emit("fold", seat_nb);
        return (1);
    }
    return (1);
}

function adjust_bets_values(table) {
    var curseat;

    for (var idx = 1; idx <= 6; ++idx) {
        if (table.playing_seats.indexOf(idx) != -1) {
            curseat = get_seat(table.seats, idx);
            curseat.bet = (Math.round(curseat.bet * 100)) / 100;
            console.log("Seat bet n°" + idx + ": " + curseat.bet);
        }
    }
}

function switch_next_player(table) {
    var player;

    if (table.game.highlights_pos == "none")
        return;
    io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait");
    io.to(table.id).emit("highlights", table.game.highlights_pos, "off");
    table.game.highlights_pos = get_next_player(table, table.game);
    io.to(table.id).emit("highlights", table.game.highlights_pos, "on");
    send_raise_limits(table, table.game, table.game.highlights_pos, 0);
    adjust_bets_values(table);
    if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
        if (table.game.curbet == "0") {
            send_option(table, table.game.highlights_pos, "first choice", "check", 0);
            send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind);
            send_raise_limits(table, table.game, table.game.highlights_pos, 1);
        } else {
            if (table.game.curbet > get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
                send_option(table, table.game.highlights_pos, "first choice", "call", get_seat(table.seats, table.game.highlights_pos).player.bankroll);
                send_option(table, table.game.highlights_pos, "second choice", "null", -1);
            } else {
                send_option(table, table.game.highlights_pos, "first choice", "call", table.game.curbet);
                if (table.game.curbet * 2 > get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
                    send_option(table, table.game.highlights_pos, "second choice", "null", -1);
                } else {
                    /*table.game.curbet == 20 ? */
                    send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet * 2)
                        /*:
					send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet = table.game.curbet + (table.game.curbet - ));*/
                }
            }
        }
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    } else {
        if (table.game.curbet == "0") {
            send_option(table, table.game.highlights_pos, "first choice", "check", 0);
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
            send_raise_limits(table, table.game, table.game.highlights_pos, 1);
        } else {
            send_option(table, table.game.highlights_pos, "first choice", "call", 0);
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        }
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    }
}

function next_moment(table, game) {
    var player;

    if (to_preflop) {
        table.game.moment = "preflop";
        to_preflop = 0;
    }
    if (table.game.moment == "preflop") {
        table.game.curbet = "0";
        table.game.moment = "flop";
        deal_flop(table, game);
        if (evalhand(table, game)) {
            console.log("PreFlop eval hand");
        } // Evaluate the current hand of all the players playing.
    } else if (table.game.moment == "flop") {
        table.game.curbet = "0";
        table.game.moment = "turn";
        deal_turn(table, game);
        if (evalhand(table, game)) {
            console.log("Flop eval hand");
        }
    } else if (table.game.moment == "turn") {
        table.game.curbet = "0";
        table.game.moment = "river";
        deal_river(table, game);
        evalhand(table, game);
    } else if (table.game.moment == "river")
        return show_down(table, game);
    table.game.round_nb = 0;
    table.game.curbet = "0";
    for (var idx = 1; idx <= 6; ++idx) {
        get_seat(table.seats, idx).bet = 0;
        io.to(table.id).emit("bet", idx, "");
    }
    io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait");
    io.to(table.id).emit("highlights", table.game.highlights_pos, "off");
    table.game.highlights_pos = get_first_to_talk(table, game);
    io.to(table.id).emit("highlights", table.game.highlights_pos, "on");
    send_raise_limits(table, table.game, table.game.highlights_pos, 1);
    if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
        send_option(table, table.game.highlights_pos, "first choice", "check", 0);
        if (get_seat(table.seats, table.game.highlights_pos).player.bankroll < cfg.conf.big_blind)
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        else
            send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind);
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    } else {
        send_option(table, table.game.highlights_pos, "first choice", "check", 0);
        send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    }
}

function one_playing_player_left(table) {
    var player = get_seat(table.seats, table.playing_seats[0]).player;

    player.bankroll += +table.game.pot_amount;
    io.to(table.id).emit("bankroll modification", table.playing_seats[0], player);
    return end_game(table, table.game, 42, player);
}
<commit_msg>test co<commit_after>var to_preflop = 0;
var push = false;
var lock = false;

function socket_listens_players(socket, table) {
    var player; // Current player.
    var curseat; // Current seat.
    var channel; // Channel involved.
    //table = get_table(table.id, tables);

    /*socket.on("nb player", function(nb) {
    	nb_player = nb;
    	console.log('first '+ nb_player);
    })*/
    socket.on("is valid nickname", function(nickname, seat_idx) {
        curseat = get_seat(table.seats, seat_idx);
        channel = get_private_id(table.private_ids, seat_idx);
        if (!nickname || check_blanks(nickname) || nickname.length < 2 || nickname.length > 8) {
            console.log("Invalid nickname!");
            socket.emit("is valid nickname info", "invalid");
        } else if (table.nicknames.indexOf(nickname) != -1) {
            console.log("Nickname already taken!");
            socket.emit("is valid nickname info", "already taken");
        } else if (curseat.state != "available")
            socket.emit("is valid nickname info", "seat busy");
        else {
            console.log(nickname + " is valid!");
            socket.emit("is valid nickname info", "valid", nickname);
            table.nicknames.push(nickname); // Add the user nickname to the table nicknames array.
            if (table.players_nb < 6)
                ++table.players_nb;
            console.log("There are now " + table.players_nb + " seated at the table (imo of course)!");
            player = new Player(seat_idx, nickname, +table.start_bankroll, -1, -1, -1, -1);
            curseat.state = "busy";
            curseat.player = player;
            console.log("Seat" + seat_idx + " is now " + curseat.state);
            io.to(table.id).emit("new player", player);
            if (table.playing_seats.indexOf(seat_idx) != -1)
                return;
				console.log('first '+table.playing_seats.length);
			if (table.playing_seats.length == 1 && lock)
                tryChrono(socket, table);
            if (table.game.moment == "waiting")
                table.playing_seats.push(seat_idx);
            for (var i = 0; i < table.playing_seats.length; i++)
                get_seat(table.seats, table.playing_seats[i]).state = "playing";
			console.log('second '+table.playing_seats.length);
            if (table.playing_seats.length >= 1 && table.game.moment == "waiting") {
                if (table.playing_seats.length > 1)
                    return;
				console.log('third '+table.playing_seats.length);
				if (!lock)
                	tryChrono(socket, table);
            }
            return;
        }
    });
    socket.on("get seated players", function() {
        send_seats_infos(table);
    });
    socket.on("get board", function() {
        if (table.game.board.length >= 3)
            io.to(table.id).emit("send flop", table.game.board[0], table.game.board[1], table.game.board[2]);
        if (table.game.board.length >= 4)
            io.to(table.id).emit("send turn", table.game.board[3]);
        if (table.game.board.length === 5)
            io.to(table.id).emit("send river", table.game.board[4]);
    });
    socket.on("to preflop", function(init) {
        to_preflop = init;
    });
    socket.on("player decision", function(decision, channel_id, bet_amount, rc) {
        if (!decision || !channel_id)
            return;
        var seat_nb = +channel_id[channel_id.length - 1];

        if (table.playing_seats.length == 2)
            table.game.highlights_pos = seat_nb;
        if (seat_nb != table.game.highlights_pos)
            return;
        if (bet_amount && bet_amount[bet_amount.length - 1] == "$") {
            bet_amount = bet_amount.slice(0, bet_amount.length - 1);
            bet_amount = (Math.round(+bet_amount * 100)) / 100;
        }
        console.log(decision + " " + bet_amount + " has been chosen by seat n°" + seat_nb);
        treat_decision(table, get_seat(table.seats, seat_nb), decision, bet_amount, get_seat(table.seats, seat_nb).player, seat_nb, rc);
        io.to(table.id).emit("last action", decision, seat_nb, bet_amount);
        console.log(table.game.round_nb + "/" + table.playing_seats.length);
        if (table.game.round_nb >= table.playing_seats.length && check_bets(table, table.seats)) {
            if (table.playing_seats.length < 2) {
                return one_playing_player_left(table);
            }
            console.log('next_moment');
            next_moment(table, table.game);
        } else {
            if (table.playing_seats.length < 2) {
                return one_playing_player_left(table);
            }
            console.log('switch next player');
            switch_next_player(table);
        }
        ++table.game.round_nb;
    });
}

function tryChrono(socket, table) {
    var chrono = setInterval(function() {
        push = false;
        clearInterval(chrono);
    }, 45000);
    if (push == false) {
        io.to(table.id).emit("chrono", 45, "The game will begin ...");
        push = true;
    }
    var timer = setInterval(function() {
        clearInterval(timer);
        io.to(table.id).emit("chrono off");
        if (table.playing_seats.length > 1) {
            console.log("Starting a new game...");
            new_cashgame(socket, table);
			lock = true;
        } else
            tryChrono(socket, table);
    }, 45000);
}

function treat_decision(table, seat, decision, bet_amount, player, seat_nb, rc) {
    if (decision == "FOLD")
        decision = "FOLD";
    else if (rc == "undefined")
        decision = "CALL";
    else if (rc == 1)
        decision = "RAISE";
    if (decision == "CHECK" && +seat.bet === +table.game.curbet)
        return (1);
    else if (decision == "CALL") {
        player.bankroll -= (+table.game.curbet - +seat.bet) > 0 ? (+table.game.curbet - +seat.bet) : +table.game.curbet;
        if (player.bankroll < 0)
            player.bankroll = 0;
        seat.bet = +seat.bet + +bet_amount;
        seat.bet = Math.round(seat.bet * 100) / 100;
        seat.bet = +seat.bet + (+table.game.curbet - +seat.bet);
        table.game.pot_amount = +table.game.pot_amount + +bet_amount;
        io.to(table.id).emit("bet", seat_nb, +seat.bet);
        io.to(table.id).emit("bankroll modification", seat_nb, player);
        io.to(table.id).emit("pot modification", +table.game.pot_amount);
        return (1);
    } else if (decision == "RAISE" || decision == "BET") {
        if (bet_amount > player.bankroll || bet_amount <= 0)
            return (0);
        player.bankroll -= +bet_amount;
        if (player.bankroll < 0)
            player.bankroll = 0;
        table.game.curbet = +bet_amount /*+ +seat.bet*/ ;
        seat.bet = /*+seat.bet +*/ +bet_amount;
        seat.bet = Math.round(seat.bet * 100) / 100;
        table.game.pot_amount = +table.game.pot_amount + +bet_amount;
        io.to(table.id).emit("bet", seat_nb, +seat.bet);
        io.to(table.id).emit("bankroll modification", seat_nb, player);
        io.to(table.id).emit("pot modification", +table.game.pot_amount);
        return (1);
    } else if (decision == "FOLD") {
        remove_from_playing_seats(table.playing_seats, seat_nb);
        seat.state = "busy";
        io.to(table.id).emit("fold", seat_nb);
        return (1);
    }
    return (1);
}

function adjust_bets_values(table) {
    var curseat;

    for (var idx = 1; idx <= 6; ++idx) {
        if (table.playing_seats.indexOf(idx) != -1) {
            curseat = get_seat(table.seats, idx);
            curseat.bet = (Math.round(curseat.bet * 100)) / 100;
            console.log("Seat bet n°" + idx + ": " + curseat.bet);
        }
    }
}

function switch_next_player(table) {
    var player;

    if (table.game.highlights_pos == "none")
        return;
    io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait");
    io.to(table.id).emit("highlights", table.game.highlights_pos, "off");
    table.game.highlights_pos = get_next_player(table, table.game);
    io.to(table.id).emit("highlights", table.game.highlights_pos, "on");
    send_raise_limits(table, table.game, table.game.highlights_pos, 0);
    adjust_bets_values(table);
    if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
        if (table.game.curbet == "0") {
            send_option(table, table.game.highlights_pos, "first choice", "check", 0);
            send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind);
            send_raise_limits(table, table.game, table.game.highlights_pos, 1);
        } else {
            if (table.game.curbet > get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
                send_option(table, table.game.highlights_pos, "first choice", "call", get_seat(table.seats, table.game.highlights_pos).player.bankroll);
                send_option(table, table.game.highlights_pos, "second choice", "null", -1);
            } else {
                send_option(table, table.game.highlights_pos, "first choice", "call", table.game.curbet);
                if (table.game.curbet * 2 > get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
                    send_option(table, table.game.highlights_pos, "second choice", "null", -1);
                } else {
                    /*table.game.curbet == 20 ? */
                    send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet * 2)
                        /*:
					send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet = table.game.curbet + (table.game.curbet - ));*/
                }
            }
        }
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    } else {
        if (table.game.curbet == "0") {
            send_option(table, table.game.highlights_pos, "first choice", "check", 0);
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
            send_raise_limits(table, table.game, table.game.highlights_pos, 1);
        } else {
            send_option(table, table.game.highlights_pos, "first choice", "call", 0);
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        }
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    }
}

function next_moment(table, game) {
    var player;

    if (to_preflop) {
        table.game.moment = "preflop";
        to_preflop = 0;
    }
    if (table.game.moment == "preflop") {
        table.game.curbet = "0";
        table.game.moment = "flop";
        deal_flop(table, game);
        if (evalhand(table, game)) {
            console.log("PreFlop eval hand");
        } // Evaluate the current hand of all the players playing.
    } else if (table.game.moment == "flop") {
        table.game.curbet = "0";
        table.game.moment = "turn";
        deal_turn(table, game);
        if (evalhand(table, game)) {
            console.log("Flop eval hand");
        }
    } else if (table.game.moment == "turn") {
        table.game.curbet = "0";
        table.game.moment = "river";
        deal_river(table, game);
        evalhand(table, game);
    } else if (table.game.moment == "river")
        return show_down(table, game);
    table.game.round_nb = 0;
    table.game.curbet = "0";
    for (var idx = 1; idx <= 6; ++idx) {
        get_seat(table.seats, idx).bet = 0;
        io.to(table.id).emit("bet", idx, "");
    }
    io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait");
    io.to(table.id).emit("highlights", table.game.highlights_pos, "off");
    table.game.highlights_pos = get_first_to_talk(table, game);
    io.to(table.id).emit("highlights", table.game.highlights_pos, "on");
    send_raise_limits(table, table.game, table.game.highlights_pos, 1);
    if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) {
        send_option(table, table.game.highlights_pos, "first choice", "check", 0);
        if (get_seat(table.seats, table.game.highlights_pos).player.bankroll < cfg.conf.big_blind)
            send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        else
            send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind);
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    } else {
        send_option(table, table.game.highlights_pos, "first choice", "check", 0);
        send_option(table, table.game.highlights_pos, "second choice", "null", -1);
        send_option(table, table.game.highlights_pos, "third choice", "fold");
    }
}

function one_playing_player_left(table) {
    var player = get_seat(table.seats, table.playing_seats[0]).player;

    player.bankroll += +table.game.pot_amount;
    io.to(table.id).emit("bankroll modification", table.playing_seats[0], player);
    return end_game(table, table.game, 42, player);
}
<|endoftext|>


<commit_before>'use strict';

var util = require("util");
var mongoose = require('mongoose');
var path = process.cwd();
require('dotenv').load();
var app = require('express')();

if (process.env.MONGOLAB_URI) {
    mongoose.connect(process.env.MONGOLAB_URI);
} else {
    mongoose.connect(process.env.MONGO_URI);
}

var BanyaUsers = require('./app/models/banyaUsers.js');
var checkUser = require("./app/models/checkUser.js");

var start = require("./app/controllers/commands/start.js");
var help = require("./app/controllers/commands/help.js");
var motivateme = require("./app/controllers/commands/motivateme.js");
var trollme = require("./app/controllers/commands/trollme.js");
var trolluser = require("./app/controllers/commands/trolluser.js");
var requestfeature = require("./app/controllers/commands/requestfeature.js");
var reportbug = require("./app/controllers/commands/reportbug.js");

var TeaBot = require("teabot")(process.env.BOT_TOKEN, process.env.BOT_NAME);
TeaBot.use('analytics', require('teabot-botan')(process.env.BOTAN_TOKEN));

function printFrom(dialog) {
    var from = {
        id: dialog.message.from.id,
        username: dialog.message.from.username,
        first_name: dialog.message.from.first_name,
        last_name: dialog.message.from.last_name
    };
    var command = dialog.message.command;
    console.log(new Date().toISOString(), "command " + command + " request from: ", from.id, from.username, from.first_name, from.last_name);
}

function getName(dialog) {
    return dialog.message.from.first_name || dialog.message.from.username;
}

function getCurrentUsers(next) {
    BanyaUsers.find({}, function(err, users) {
        if (err) console.error(err);
        next(users);
    });
}

function userExists(name, next) {
    BanyaUsers.findOne({ $or: [ { 'user.secondName': name }, { 'user.firstName': name } ]}, function(err, user) {
        if (err) console.error(err);
        console.log("--- found this user: ", user.userid, user.user.username, user.user.firstName, user.user.secondName);
        if (next) { next(user); } else return user;
    });
}

function prepareTempData(data, user) {
    data.userid = user.userid;
    data.user = {
        firstName: user.user.firstName,
        secondName: user.user.secondName
    };
    return data;
}

TeaBot.onError(function (e) {
    console.error('TeaBot error:', e.stack);
});

// COMMANDS //

TeaBot
    .defineCommand('/start', function (dialog) {
        // console.log(util.inspect(dialog.message.from));
        printFrom(dialog);
        checkUser(dialog.message, function(user) {
            dialog
                .setKeyboard()
                .sendMessage(start(getName(dialog)));
        });

    })

    .defineCommand('/help', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(help(getName(dialog)));
    })

    .defineCommand('/motivateme', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(motivateme());
    })

    .defineCommand('/trollme', function (dialog) {
        printFrom(dialog);
        dialog.setKeyboard();
        trollme(dialog.message, function(response) {
            dialog.sendMessage(response);
        });
    })

    .defineCommand('/trolluser', function(dialog) {
        printFrom(dialog);
        dialog.startAction('/trolluser');
        getCurrentUsers(function(users) {
            var keyboard = [];
            users.forEach((el) => {
                keyboard.push(new Array((el.user.secondName) ? el.user.firstName + " " + el.user.secondName : el.user.firstName));
            });
            keyboard.push(['другого']);
            keyboard.push(['/cancel']);

            dialog.setKeyboard(keyboard, true, true);
            dialog.sendMessage("Кого ты хочешь потроллить (скролл работает, если что)?");
        });

    })

    .defineCommand('/requestfeature', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/requestfeature').sendMessage("Опиши предлагаемую фичу. Только коротко.");
    })

    .defineCommand('/reportbug', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/reportbug').sendMessage("Опиши найденную ошибку. Только коротко.");
    })

    .defineCommand('/cancel', function (dialog) {
        printFrom(dialog);
        if (dialog.inAction()) {
            dialog
                .setKeyboard()
                .endAction()
                .sendMessage('Как скажешь. Если что, поддать парка можно с помощью /help.');
        }
    })

    .defineCommand(function (dialog) {
        printFrom(dialog);
        dialog.sendMessage('Это я не понял. Отправь мне /help, что ли.');
    });

// ACTIONS //

TeaBot
    .defineAction('/requestfeature', function(dialog, message) {
        var description = message.getArgument();
        requestfeature(message, description, function(features) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое предложение. Парься дальше.");
        });
    })

    .defineAction('/reportbug', function(dialog, message) {
        var description = message.getArgument();
        reportbug(message, description, function(bug) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое сообщение. Легкого пара.");
        });
    })

    .defineAction('/trolluser', function(dialog, message) {

        var data = {};
        var keyboardPress = message.getArgument().split(" ")[1] || message.getArgument().split(" ")[0];

        console.log("--- got this when reacted to keyboard press: ", keyboardPress);

        if (keyboardPress === 'другого') {
            dialog
                .endAction(true)
                .setKeyboard()
                .startAction('/trolluser:manual')
                .sendMessage('OK, пиши сам руками тогда.');
        } else {
            userExists(keyboardPress, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");

                } else {
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:contact')
                        .sendMessage("Запутался в своих записях. Пришли его телеграмовские контакты. Так надежнее.");
                }
            });
        }
    })

    .defineAction('/trolluser:manual', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        var userLastName = message.getArgument();
        userExists(userLastName, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:contact')
                    .sendMessage("Не нашел такого в своих записях. Или просмотрел. Шли его телеграмовские контакты. Так надежнее.");
            }
        });
    })

    .defineAction('/trolluser:phrase', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        data.phrase = message.getArgument();
        trolluser.addTrollPhrase(data, function(user) {
            dialog
                .endAction()
                .setKeyboard();
            if (user) {
                dialog.sendMessage("Добавил, короче, ему в список.");
            } else {
                dialog.sendMessage("Что-то не получилось у меня. Попробуй еще раз как-нибудь.");
            }
        });
    })

    .defineAction('/trolluser:contact', function(dialog, message) {
        // console.log("--- contact received: ", message);

        var data = dialog.getTempData('data') || {};

        trolluser.addUserFromContact(message.contact, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Контакт запомнил. Пиши теперь фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction()
                    .setKeyboard()
                    .sendMessage("Что-то пошло не так. Сложный юзер. Не смог запомнить.");
            }

        });

    });

console.log(new Date().toISOString(), "BANYA BOT PROUDLY STARTED...");
TeaBot.startPolling();

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

var util = require("util");
var mongoose = require('mongoose');
var path = process.cwd();
require('dotenv').load();
var app = require('express')();

if (process.env.MONGOLAB_URI) {
    mongoose.connect(process.env.MONGOLAB_URI);
} else {
    mongoose.connect(process.env.MONGO_URI);
}

var BanyaUsers = require('./app/models/banyaUsers.js');
var checkUser = require("./app/models/checkUser.js");

var start = require("./app/controllers/commands/start.js");
var help = require("./app/controllers/commands/help.js");
var motivateme = require("./app/controllers/commands/motivateme.js");
var trollme = require("./app/controllers/commands/trollme.js");
var trolluser = require("./app/controllers/commands/trolluser.js");
var requestfeature = require("./app/controllers/commands/requestfeature.js");
var reportbug = require("./app/controllers/commands/reportbug.js");

var TeaBot = require("teabot")(process.env.BOT_TOKEN, process.env.BOT_NAME);
TeaBot.use('analytics', require('teabot-botan')(process.env.BOTAN_TOKEN));

function printFrom(dialog) {
    var from = {
        id: dialog.message.from.id,
        username: dialog.message.from.username,
        first_name: dialog.message.from.first_name,
        last_name: dialog.message.from.last_name
    };
    var command = dialog.message.command;
    console.log(new Date().toISOString(), "command " + command + " request from: ", from.id, from.username, from.first_name, from.last_name);
}

function getName(dialog) {
    return dialog.message.from.first_name || dialog.message.from.username;
}

function getCurrentUsers(next) {
    BanyaUsers.find({}, function(err, users) {
        if (err) console.error(err);
        next(users);
    });
}

function userExists(name, next) {
    BanyaUsers.findOne({ $or: [ { 'user.secondName': name }, { 'user.firstName': name } ]}, function(err, user) {
        if (err) console.error(err);
        console.log("--- found this user: ", user.userid, user.user.username, user.user.firstName, user.user.secondName);
        if (next) { next(user); } else return user;
    });
}

function prepareTempData(data, user) {
    data.userid = user.userid;
    data.user = {
        firstName: user.user.firstName,
        secondName: user.user.secondName
    };
    return data;
}

TeaBot.onError(function (e) {
    console.error('TeaBot error:', e.stack);
});

// COMMANDS //

TeaBot
    .defineCommand('/start', function (dialog) {
        // console.log(util.inspect(dialog.message.from));
        printFrom(dialog);
        checkUser(dialog.message, function(user) {
            dialog
                .setKeyboard()
                .sendMessage(start(getName(dialog)));
        });

    })

    .defineCommand('/help', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(help(getName(dialog)));
    })

    .defineCommand('/motivateme', function (dialog) {
        printFrom(dialog);
        dialog
          .setKeyboard()
          .sendMessage(motivateme());
    })

    .defineCommand('/trollme', function (dialog) {
        printFrom(dialog);
        dialog.setKeyboard();
        trollme(dialog.message, function(response) {
            dialog.sendMessage(response);
        });
    })

    .defineCommand('/trolluser', function(dialog) {
        printFrom(dialog);
        dialog.startAction('/trolluser');
        getCurrentUsers(function(users) {
            var keyboard = [];
            users.forEach((el) => {
                keyboard.push(new Array((el.user.secondName) ? el.user.firstName + " " + el.user.secondName : el.user.firstName));
            });
            keyboard.push(['другого']);
            keyboard.push(['/cancel']);

            dialog.setKeyboard(keyboard, true, true);
            dialog.sendMessage("Кого ты хочешь потроллить (скролл работает, если что)?");
        });

    })

    .defineCommand('/requestfeature', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/requestfeature').sendMessage("Опиши предлагаемую фичу. Только коротко.");
    })

    .defineCommand('/reportbug', function (dialog) {
        printFrom(dialog);
        dialog.startAction('/reportbug').sendMessage("Опиши найденную ошибку. Только коротко.");
    })

    .defineCommand('/cancel', function (dialog) {
        printFrom(dialog);
        if (dialog.inAction()) {
            dialog
                .setKeyboard()
                .endAction()
                .sendMessage('Как скажешь. Если что, поддать парка можно с помощью /help.');
        }
    })

    .defineCommand(function (dialog) {
        printFrom(dialog);
        dialog.sendMessage('Это я не понял. Отправь мне /help, что ли.');
    });

// ACTIONS //

TeaBot
    .defineAction('/requestfeature', function(dialog, message) {
        var description = message.getArgument();
        requestfeature(message, description, function(features) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое предложение. Парься дальше.");
        });
    })

    .defineAction('/reportbug', function(dialog, message) {
        var description = message.getArgument();
        reportbug(message, description, function(bug) {
            dialog.endAction();
            dialog.sendMessage("Сохранил твое сообщение. Легкого пара.");
        });
    })

    .defineAction('/trolluser', function(dialog, message) {

        var data = {};
        var keyboardPress = message.getArgument().split(" ")[1] || message.getArgument().split(" ")[0];

        console.log("--- got this when reacted to keyboard press: ", keyboardPress);

        if (keyboardPress === 'другого') {
            dialog
                .endAction(true)
                .setKeyboard()
                .startAction('/trolluser:manual')
                .sendMessage('OK, пиши сам руками тогда.');
        } else {
            userExists(keyboardPress, function(user) {
                if (user) {
                    data = prepareTempData(data, user);
                    dialog.setTempData('data', data);
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:phrase')
                        .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");

                } else {
                    dialog
                        .endAction(true)
                        .setKeyboard()
                        .startAction('/trolluser:contact')
                        .sendMessage("Запутался в своих записях. Пришли его телеграмовские контакты. Так надежнее.");
                }
            });
        }
    })

    .defineAction('/trolluser:manual', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        var userLastName = message.getArgument();
        userExists(userLastName, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Пиши фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:contact')
                    .sendMessage("Не нашел такого в своих записях. Или просмотрел. Шли его телеграмовские контакты. Так надежнее.");
            }
        });
    })

    .defineAction('/trolluser:phrase', function(dialog, message) {
        var data = dialog.getTempData('data') || {};
        data.phrase = message.getArgument();
        trolluser.addTrollPhrase(data, function(user) {
            dialog
                .endAction()
                .setKeyboard();
            if (user) {
                dialog.sendMessage("Добавил, короче, ему в список.");
            } else {
                dialog.sendMessage("Что-то не получилось у меня. Попробуй еще раз как-нибудь.");
            }
        });
    })

    .defineAction('/trolluser:contact', function(dialog, message) {
        // console.log("--- contact received: ", message);

        var data = dialog.getTempData('data') || {};

        trolluser.addUserFromContact(message.contact, function(user) {
            if (user) {
                data = prepareTempData(data, user);
                dialog.setTempData('data', data);
                dialog
                    .endAction(true)
                    .setKeyboard()
                    .startAction('/trolluser:phrase')
                    .sendMessage("Контакт запомнил. Пиши теперь фразу, чтобы добавить в его копилку. Когда он будет себя троллить, она будет выбираться случайным образом среди других.");
            } else {
                dialog
                    .endAction()
                    .setKeyboard()
                    .sendMessage("Что-то пошло не так. Сложный юзер. Не смог запомнить.");
            }

        });

    });

console.log(new Date().toISOString(), "BANYA BOT PROUDLY STARTED...");
TeaBot.startPolling();

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


<commit_before>'use strict';

const request = require('sync-request');
const parseXml = require('xml2js').parseString;

Sitemapper = (url, opts) => {

	var _self = {};

	_self.reqOptions = {
		'headers' : {
			'user-agent' : 'github.com/bcmh/sitemapper'
		}
	};

	if (typeof url !== 'string') {
		throw new TypeError('url is required.');
	}

	_self.url = url;

	opts = opts || {};

	_self.getUrlsFromUrlset = (urlset) => {
		var arr = [];

		urlset.url.forEach(function (item) {
			arr.push(item.loc.pop());
		});

		return arr;
	};

	return {
		fetchUrlsFromUrlset : _self.getUrlsFromUrlset,
		fetch: (cb) => {
			var res = request('GET', _self.url, _self.reqOptions );

			parseXml(res.getBody(), (err,res) => {
				var urls = [];

				if ( res.urlset ) {
					urls = _self.getUrlsFromUrlset(res.urlset);
				} else if (res.sitemapindex) {

					var sitemaps = [];
					res.sitemapindex.sitemap.forEach(function(item) {
						sitemaps.push(item.loc.pop());
					});

					sitemaps.forEach(url => {
						var r = request('GET', url, _self.reqOptions );

						parseXml(r.getBody(), (err, res) => {
							urls = urls.concat(_self.getUrlsFromUrlset(res.urlset));
						});
					});
				}

				_self.urls = urls;

				if (cb) {
					cb();
				}
			});
		},
		fetchUrls : () => {
			return _self.urls;
		}
	};
}

module.exports = Sitemapper;<commit_msg>Removes ol function styling<commit_after>'use strict';

const request = require('sync-request');
const parseXml = require('xml2js').parseString;

const Sitemapper = (url, opts) => {

	var _self = {};

	_self.reqOptions = {
		'headers' : {
			'user-agent' : 'github.com/bcmh/sitemapper'
		}
	};

	if (typeof url !== 'string') {
		throw new TypeError('url is required.');
	}

	_self.url = url;

	opts = opts || {};

	_self.getUrlsFromUrlset = (urlset) => {
		var arr = [];

		urlset.url.forEach((item) => {
			arr.push(item.loc.pop());
		});

		return arr;
	};

	return {
		fetchUrlsFromUrlset : _self.getUrlsFromUrlset,
		fetch: (cb) => {

			var res = request('GET', _self.url, _self.reqOptions );

			parseXml(res.getBody(), (err,res) => {
				var urls = [];

				if (err) {
					throw err;
				}

				if ( res.urlset ) {
					urls = _self.getUrlsFromUrlset(res.urlset);
				} else if (res.sitemapindex) {

					var sitemaps = [];
					res.sitemapindex.sitemap.forEach((item) => {
						sitemaps.push(item.loc.pop());
					});

					sitemaps.forEach(url => {
						var r = request('GET', url, _self.reqOptions );

						parseXml(r.getBody(), (err, res) => {
							if (!err) {
								throw err;
							}

							urls = urls.concat(_self.getUrlsFromUrlset(res.urlset));
						});
					});
				}

				_self.urls = urls;

				if (cb) {
					return cb();
				}
			});
		},
		fetchUrls : () => {
			return _self.urls;
		}
	};
}

module.exports = Sitemapper;<|endoftext|>


<commit_before>var Hapi = require('hapi');
var routes = require('./routes');
var Db = require('./db');
var User = require('./model').User;
var boom = require('boom');
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: process.env.PORT
});

server.register(require('hapi-auth-bearer-token'), function (err) {

    server.auth.strategy('tokenBased', 'bearer-access-token', {
        allowQueryToken: true,              // optional, true by default
        allowMultipleHeaders: false,        // optional, false by default
        accessTokenName: 'access_token',    // optional, 'access_token' by default
        validateFunc: function( token, callback ) {

			User.findOne({token : token},function(err,doc){
				if(err){
					return reply(boom.forbidden(err));
			}
			if(doc){
				console.log("!!!!" + (parseFloat(doc.time) + 28800 < Date.now()))
				if(parseFloat(doc.time) + 28800 < Date.now())
					callback(null, true, { token: token });
				else
					callback(null,false,{token : token});
			}
			else{
				callback(null,false,{token : token});
			}
			});
        }
    });
});

server.route(routes);
// Start the server
server.start(function(){
	console.log('Server started at: ' + server.info.uri);
});<commit_msg>uri change<commit_after>var Hapi = require('hapi');
var routes = require('./routes');
var Db = require('./db');
var User = require('./model').User;
var boom = require('boom');
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: parseInt(process.env.PORT, 10) || 3000
});

server.register(require('hapi-auth-bearer-token'), function (err) {

    server.auth.strategy('tokenBased', 'bearer-access-token', {
        allowQueryToken: true,              // optional, true by default
        allowMultipleHeaders: false,        // optional, false by default
        accessTokenName: 'access_token',    // optional, 'access_token' by default
        validateFunc: function( token, callback ) {

			User.findOne({token : token},function(err,doc){
				if(err){
					return reply(boom.forbidden(err));
			}
			if(doc){
				console.log("!!!!" + (parseFloat(doc.time) + 28800 < Date.now()))
				if(parseFloat(doc.time) + 28800 < Date.now())
					callback(null, true, { token: token });
				else
					callback(null,false,{token : token});
			}
			else{
				callback(null,false,{token : token});
			}
			});
        }
    });
});

server.route(routes);
// Start the server
server.start(function(){
	console.log('Server started at: ' + server.info.uri);
});<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Dumb from '../components/dumb';
import Radium from 'radium';
import Feed from './feed';
import Login from './login';
import Longform from './longform';
import GraphicNovel from './graphicNovel';
import MenuAndSettings from './menuAndSettings';
import { Link } from 'react-router';

const contentData = [{
  localPicWord: 'behavior',
  foreignPicWord: 'behavior',
  localContent: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  localHeader: 'Hugging',
  foreignContent: 'قد بلا دخول كانت كنقطة. ثم قادة ساعة للحكومة يبق. من سبتمبر وحرمان ذلك, يبق الضروري الثالث٬ الواقعة عل, هذه أي الأوروبيّون.',
  foreignHeader: 'عناق',

}],
styles = {
  mainContainer: {
    width: '100vw',
    height: '95vh',
    fontFamily: 'Roboto',
  },
  row: {
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'space-between',
  },
  col: {
    display: 'flex',
    flexFlow: 'col-nowrap',
    justifyContent: 'space-between',
  },
  topRow: {
    disply: 'flex',
    alignItems: 'center',
    backgroundColor: '#4A90E2',
    padding: '10px',
    height: '9.5vh',
  },
  icons: {
    color: 'white',
  },
  menuLogo: {
    padding: '2px',
    width: '30vmin',
    height: '10vmin',
  },
  culturalnorm: {
    backgroundColor: '#4A90E2',
    color: 'white',
    textTransform: 'uppercase',
    fontWeight: 'bold',
    border: '1px solid grey',
    alignItems: 'center',
    alignContent: 'center',
  },
  feedImage: {
    height: '55vh',
    backgroundImage: `url('assets/images/photo_HUGGING.png')`,
    backgroundSize: '100%',
    width: '100vw',
    justifyContent: 'space-between',
    display: 'flex',
    flexFlow: 'column nowrap',
    padding: '10px',
  },
  descriptions: {
    width: '50vw',
    padding: '5px',
  },
  languageLocal: {
    display: 'flex',
    flexFlow: 'column nowrap',
  },
  languageForeign: {
    display: 'flex',
    flexFlow: 'column nowrap',
  },
  header: {
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  content: {
    color: 'grey',
  },
  behaviorRow: {
    display: 'flex',
    flexFlow: 'row nowrap',
    height: '5vh',
    display: 'flex',
    alignItems: 'center',
  },
  volume: {
    color: '#4A90E2',
    height: '4vh',
    width: '4vh',
    marginLeft: '5px',
  },
  learningWord: {
    fontWeight: 500,
    fontSize: '20px',
    display: 'flex',
    alignContent: 'center',
  },
  bottomRow: {
    display: 'flex',
    padding: '0px 20px',
    height: '5vh',
    justifyContent: 'center',
    alignContent: 'center',
  },
  bottomDiv: {
    marginTop: '10px',
    padding: '5px',
    borderTop: '1px solid #d3d3d3',
    display: 'flex',
    height: '5vh',
    width:  '90vw',
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'flex-end',
  },
  socialIcons: {
     color: '#4A90E2',
     padding: '5px',
  }
};

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {
          enabled: true,
        };
    }

    toggleEnabled() {
        this.setState({ enabled: !this.state.enabled });
    }

    componentDidMount() {
      console.log('hola')
    }

    render() {
      let content = null;

      content = contentData.map((c) => {
        return (

                    menu

                    book

                            {c.localPicWord} | {c.foreignPicWord}

favorite

{c.localHeader}volume_up

                              {c.localContent}

                              {c.foreignHeader}

                              {c.foreignContent}

                    share
                    chat
                    favorite

        );
      });

      const
        toggleEnabled = this.toggleEnabled;
        return (

                {content}

        );
    }
}
Main = Radium(Main);

Main.propTypes = {
}

export default Main;
<commit_msg>prefetch<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Dumb from '../components/dumb';
import Radium from 'radium';
import Feed from './feed';
import Login from './login';
import Longform from './longform';
import GraphicNovel from './graphicNovel';
import MenuAndSettings from './menuAndSettings';
import { Link } from 'react-router';

const contentData = [{
  localPicWord: 'behavior',
  foreignPicWord: 'behavior',
  localContent: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  localHeader: 'Hugging',
  foreignContent: 'قد بلا دخول كانت كنقطة. ثم قادة ساعة للحكومة يبق. من سبتمبر وحرمان ذلك, يبق الضروري الثالث٬ الواقعة عل, هذه أي الأوروبيّون.',
  foreignHeader: 'عناق',
},
{
  localPicWord: 'behavior',
  foreignPicWord: 'behavior',
  localContent: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  localHeader: 'Hugging',
  foreignContent: 'قد بلا دخول كانت كنقطة. ثم قادة ساعة للحكومة يبق. من سبتمبر وحرمان ذلك, يبق الضروري الثالث٬ الواقعة عل, هذه أي الأوروبيّون.',
  foreignHeader: 'عناق',
},
{
  localPicWord: 'behavior',
  foreignPicWord: 'behavior',
  localContent: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  localHeader: 'Hugging',
  foreignContent: 'قد بلا دخول كانت كنقطة. ثم قادة ساعة للحكومة يبق. من سبتمبر وحرمان ذلك, يبق الضروري الثالث٬ الواقعة عل, هذه أي الأوروبيّون.',
  foreignHeader: 'عناق',
}],
styles = {
  mainContainer: {
    width: '100vw',
    fontFamily: 'Roboto',
  },
  scrollingContainer: {
    height: '90vh',
  },
  row: {
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'space-between',
  },
  col: {
    display: 'flex',
    flexFlow: 'col-nowrap',
    justifyContent: 'space-between',
  },
  topRow: {
    disply: 'flex',
    alignItems: 'center',
    backgroundColor: '#4A90E2',
    padding: '10px',
    height: '9.5vh',
  },
  icons: {
    color: 'white',
  },
  menuLogo: {
    padding: '2px',
    width: '30vmin',
    height: '10vmin',
  },
  culturalnorm: {
    backgroundColor: '#4A90E2',
    color: 'white',
    textTransform: 'uppercase',
    fontWeight: 'bold',
    border: '1px solid grey',
    alignItems: 'center',
    alignContent: 'center',
  },
  feedImage: {
    height: '55vh',
    backgroundImage: `url('assets/images/photo_HUGGING.png')`,
    backgroundSize: '100%',
    width: '100vw',
    justifyContent: 'space-between',
    display: 'flex',
    flexFlow: 'column nowrap',
    padding: '10px',
  },
  descriptions: {
    width: '50vw',
    padding: '5px',
  },
  languageLocal: {
    display: 'flex',
    flexFlow: 'column nowrap',
  },
  languageForeign: {
    display: 'flex',
    flexFlow: 'column nowrap',
  },
  header: {
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  content: {
    color: 'grey',
  },
  behaviorRow: {
    display: 'flex',
    flexFlow: 'row nowrap',
    height: '5vh',
    display: 'flex',
    alignItems: 'center',
  },
  volume: {
    color: '#4A90E2',
    height: '4vh',
    width: '4vh',
    marginLeft: '5px',
  },
  learningWord: {
    fontWeight: 500,
    fontSize: '20px',
    display: 'flex',
    alignContent: 'center',
  },
  bottomRow: {
    display: 'flex',
    padding: '0px 20px',
    height: '5vh',
    justifyContent: 'center',
    alignContent: 'center',
  },
  bottomDiv: {
    marginTop: '10px',
    padding: '5px',
    borderTop: '1px solid #d3d3d3',
    display: 'flex',
    height: '5vh',
    width:  '90vw',
    display: 'flex',
    flexFlow: 'row nowrap',
    justifyContent: 'flex-end',
  },
  socialIcons: {
     color: '#4A90E2',
     padding: '5px',
  }
};

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {
          enabled: true,
        };
    }

    toggleEnabled() {
        this.setState({ enabled: !this.state.enabled });
    }

    componentDidMount() {
      console.log('hola')
    }

    render() {
      let content = null;

      content = contentData.map((c) => {
        return (

                              {c.localPicWord} | {c.foreignPicWord}

favorite

{c.localHeader}volume_up

                                {c.localContent}

                                {c.foreignHeader}

                                {c.foreignContent}

                      share
                      chat
                      favorite

        );
      });

      const
        toggleEnabled = this.toggleEnabled;
        return (

                    menu

                    book

                {content}

        );
    }
}
Main = Radium(Main);

Main.propTypes = {
}

export default Main;
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port', port);
});

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

let players = [];
let score = [0,0]

io.on('connection', socket => {
  //socket.on('mouse move', (data) => {
  //  console.log(data);
  //});
  socket.on('addPlayer', function(data) {
	if(players.length == 0)
	{
    socket.emit('isHost', true);
    console.log("isHost = true");
  }
  else
  {
    console.log("isHost = false");
    socket.emit('isHost', false);
  }

  players.push(
  {
    name: data,
    socket: socket
  });
  console.log("addPlayer " + data);
  socket.emit('score', score);
  });

  socket.on('connected', () => {
    console.log('connected');
  });

  socket.on('disconnect', () => {
    console.log('disconnected');
    if(players.length > 0)
    {
      if(players[0].socket === socket)
      {
        console.log("Host " + players[0].name + " is leaving");
        players.shift();
        if(players.length > 0)
        {
          players[0].socket.emit('isHost', true);
          console.log("New host is " + players[0].name)
        }
      }
      else
      {
        console.log("Player " + players[0].name + " is leaving");
        for(var i = 0; i < players.length; i++)
        if(players[i].socket === socket)
            players.splice(i,1);
        }
    }
  });

  socket.on('ballSet', function(data) {
	socket.broadcast.emit('ballSet', data);
  });

  socket.on('score', function(data) {
    if(data == 1)
      score[0] += 7;
    else
      score[1] +=7;

    socket.emit('score', score);
	  socket.broadcast.emit('score', score);
    console.log("score " + data);
  });
  socket.on('click', function(data){
    players[0].socket.emit(data);
    players[0].socket.emit('click', data);
    console.log("Click X: " + data[0] + " Y: " + data[1]);
  });
});
<commit_msg>Working multiplayer<commit_after>const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port', port);
});

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

let players = [];
let score = [0,0]

io.on('connection', socket => {
  //socket.on('mouse move', (data) => {
  //  console.log(data);
  //});
  socket.on('addPlayer', function(data) {
	if(players.length == 0)
	{
    socket.emit('isHost', true);
    console.log("isHost = true");
  }
  else
  {
    console.log("isHost = false");
    socket.emit('isHost', false);
  }

  players.push(
  {
    name: data,
    socket: socket
  });
  console.log("addPlayer " + data);
  socket.emit('score', score);
  });

  socket.on('connected', () => {
    console.log('connected');
  });

  socket.on('disconnect', () => {
    console.log('disconnected');
    if(players.length > 0)
    {
      if(players[0].socket === socket)
      {
        console.log("Host " + players[0].name + " is leaving");
        players.shift();
        if(players.length > 0)
        {
          players[0].socket.emit('isHost', true);
          console.log("New host is " + players[0].name)
        }
      }
      else
      {
        console.log("Player " + players[0].name + " is leaving");
        for(var i = 0; i < players.length; i++)
        if(players[i].socket === socket)
            players.splice(i,1);
        }
    }
  });

  socket.on('ballSet', function(data) {
	socket.broadcast.emit('ballSet', data);
  });

  socket.on('score', function(data) {
    if(data == 1)
      score[0] += 7;
    else
      score[1] +=7;

    socket.emit('score', score);
	  socket.broadcast.emit('score', score);
    console.log("score " + data);
  });
  socket.on('click', function(data){
    players[0].socket.emit('click', data);
    console.log("Click X: " + data[0] + " Y: " + data[1]);
  });
});
<|endoftext|>


<commit_before>'use strict'

const Joi = require('joi')
const {
  isVPlusDottedVersionNClausesWithOptionalSuffix,
} = require('../test-validators')
const { ServiceTester } = require('../tester')
const t = (module.exports = new ServiceTester({
  id: 'packagist',
  title: 'Packagist Version',
  pathPrefix: '/packagist',
}))

/*
  validator for a packagist version number

  From https://packagist.org/about :
  "version names should match 'X.Y.Z', or 'vX.Y.Z',
  with an optional suffix for RC, beta, alpha or patch versions"
*/
const isPackagistVersion = Joi.string().regex(/^v?[0-9]+.[0-9]+.[0-9]+[\S]*$/)

t.create('version (valid)').get('/v/symfony/symfony.json').expectBadge({
  label: 'packagist',
  message: isPackagistVersion,
})

t.create('version (no releases)').get('/v/wsg/hello.json').expectBadge({
  label: 'packagist',
  message: 'no released version found',
  color: 'red',
})

t.create('version (invalid package name)')
  .get('/v/frodo/is-not-a-package.json')
  .expectBadge({ label: 'packagist', message: 'not found' })

t.create('pre-release version (valid)')
  .get('/v/symfony/symfony.json?include_prereleases')
  .expectBadge({
    label: 'packagist',
    message: isVPlusDottedVersionNClausesWithOptionalSuffix,
  })

t.create('version (valid custom server)')
  .get('/v/symfony/symfony.json?server=https%3A%2F%2Fpackagist.org')
  .expectBadge({
    label: 'packagist',
    message: isPackagistVersion,
  })

t.create('version (invalid custom server)')
  .get('/v/symfony/symfony.json?server=https%3A%2F%2Fpackagist.com')
  .expectBadge({ label: 'packagist', message: 'not found' })

t.create('version (legacy redirect: vpre)')
  .get('/vpre/symfony/symfony.svg')
  .expectRedirect('/packagist/v/symfony/symfony.svg?include_prereleases')

t.create('version (legacy redirect: vpre) (custom server)')
  .get('/vpre/symfony/symfony.svg?server=https%3A%2F%2Fpackagist.org')
  .expectRedirect(
    '/packagist/v/symfony/symfony.svg?include_prereleases&server=https%3A%2F%2Fpackagist.org'
  )
<commit_msg>tests: fix PackagistVersion service test (#5703)<commit_after>'use strict'

const Joi = require('joi')
const {
  isVPlusDottedVersionNClausesWithOptionalSuffix,
} = require('../test-validators')
const { ServiceTester } = require('../tester')
const t = (module.exports = new ServiceTester({
  id: 'packagist',
  title: 'Packagist Version',
  pathPrefix: '/packagist',
}))

/*
  validator for a packagist version number

  From https://packagist.org/about :
  "version names should match 'X.Y.Z', or 'vX.Y.Z',
  with an optional suffix for RC, beta, alpha or patch versions"
*/
const isPackagistVersion = Joi.string().regex(/^v?[0-9]+.[0-9]+.[0-9]+[\S]*$/)

t.create('version (valid)').get('/v/symfony/symfony.json').expectBadge({
  label: 'packagist',
  message: isPackagistVersion,
})

t.create('version (no releases)').get('/v/wsg/hello.json').expectBadge({
  label: 'packagist',
  message: 'no released version found',
  color: 'red',
})

t.create('version (invalid package name)')
  .get('/v/frodo/is-not-a-package.json')
  .expectBadge({ label: 'packagist', message: 'not found' })

t.create('pre-release version (valid)')
  .get('/v/guzzlehttp/guzzle.json?include_prereleases')
  .expectBadge({
    label: 'packagist',
    message: isVPlusDottedVersionNClausesWithOptionalSuffix,
  })

t.create('version (valid custom server)')
  .get('/v/symfony/symfony.json?server=https%3A%2F%2Fpackagist.org')
  .expectBadge({
    label: 'packagist',
    message: isPackagistVersion,
  })

t.create('version (invalid custom server)')
  .get('/v/symfony/symfony.json?server=https%3A%2F%2Fpackagist.com')
  .expectBadge({ label: 'packagist', message: 'not found' })

t.create('version (legacy redirect: vpre)')
  .get('/vpre/symfony/symfony.svg')
  .expectRedirect('/packagist/v/symfony/symfony.svg?include_prereleases')

t.create('version (legacy redirect: vpre) (custom server)')
  .get('/vpre/symfony/symfony.svg?server=https%3A%2F%2Fpackagist.org')
  .expectRedirect(
    '/packagist/v/symfony/symfony.svg?include_prereleases&server=https%3A%2F%2Fpackagist.org'
  )
<|endoftext|>


<commit_before>/**
 * @author Jan Kaufmann <jan@moldjs.de>
 * @description build a vdom from a content-template string
 * @example Mold/Test/Lib/VDom/Builder#build
 */

"user strict";
Seed({
		name : "Mold.Lib.VDom.Builder",
		dna : "class",
		test : "Mold.Test.Lib.VDom.Builder",
		include : [
			"Mold.Lib.Dom",
			"Mold.Tools.Dev.CodeInclude",
			".ProtoNode",
			[
				{ DomNode : ".DomNode" },
				{ BlockNode : ".BlockNode" },
				{ ValueNode : ".ValueNode" },
				{ TextNode : ".TextNode" },
				{ AttributeNode : ".AttributeNode" },
				{ RootNode : ".RootNode" },
				{ Doc : ".VDoc"}
			]
		]
	},
	function(content, config){

		var config = config || {};

		var _dom = new Mold.Lib.Dom(content);
		var _newDoc = Doc;
		var _doc = _dom.get();
		var _template = [];
		var undefined;

		var BLOCK_START = "{{#";
		var BLOCK_NEGATIV = "{{^";
		var BLOCK_END = "{{/";
		var VALUE = "{{";
		var BINDED_VALUE = "{{*";
		var END = "}}";

		var _parseAttributes = function(attributes, domNode){

			var output = {};
			var i = 0, len = attributes.length;

			for(; i < len; i++){

				var selected = attributes[i];
				var newAttribute = new AttributeNode({
					name : selected.nodeName
				})

				domNode.addAttribute(newAttribute);
				newAttribute.addData(selected.nodeValue)

			}

		}

		var _parseAsText = function(content){

		}

		var _getFilter = function(name){
			var filter = {};
			if(~name.indexOf("|")){
				var nameParts = name.split("|");
				name = nameParts.shift();
				var i = 0, len = nameParts.length;

				for(; i < len; i++){
					if(~nameParts[i].indexOf("(")){
						var filterName = nameParts[i].substring(0, nameParts[i].indexOf("("))
						var expression = nameParts[i].substring(nameParts[i].indexOf("(") + 1, nameParts[i].lastIndexOf(")"));
						filter[filterName] = {
							expression : expression
						};
					}else{
						var filterParts = nameParts[i].split(':');
						var y = 1, paramLength = filterParts.length;
						var filterName = filterParts[0];

						filter[filterName] = {};

						for(; y < paramLength; y++){
							var paramParts = filterParts[y].split("=");
							filter[filterName][paramParts[0]] = (paramParts[1]) ? paramParts[1] : true;
						}
					}
				}
			}
			return { name : name, filter : filter}
		}

		var _parseNode = function(node, vDom, level){

			var level = level || 0;
			var parentNode = false;
			var collectedProtoDom = {};
			var i = 0, len = node.childNodes.length;

			for(; i < len; i++){
				var selected = node.childNodes[i];
				switch(selected.nodeType){

					//handel Elementnode
					case 1:

						var domNode = new DomNode({
							name : selected.nodeName
						});

						vDom.addNode(domNode);
						_parseAttributes(selected.attributes, domNode);
						_parseNode(selected, domNode)

						break;

					//handel Textnode
					case 3:
						//Block Node
						if(Mold.startsWith(selected.nodeValue, BLOCK_START)){

							var name = selected.nodeValue.replace(BLOCK_START, "").replace(END, "");

							var parts = _getFilter(name);
							var blockNode = new BlockNode({
								name : parts.name,
								filter : parts.filter
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;

							break;
						}

						//Block Negativ
						if(Mold.startsWith(selected.nodeValue, BLOCK_NEGATIV)){
							var name = selected.nodeValue.replace(BLOCK_NEGATIV, "").replace(END, "");
							var blockNode = new BlockNode({
								name : name,
								isNegative : true
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;
							break;
						}

						//Block End
						if(Mold.startsWith(selected.nodeValue, BLOCK_END)){
							vDom = vDom.parent;
							break;
						}

						//Value
						if(Mold.startsWith(selected.nodeValue, VALUE) || Mold.startsWith(selected.nodeValue, BINDED_VALUE)){

							var binding = (Mold.startsWith(selected.nodeValue, BINDED_VALUE)) ? true : false;
							var name = selected.nodeValue.replace(BINDED_VALUE, "").replace(VALUE, "").replace(END, "");

							var parts = _getFilter(name);
							console.log("name", name, parts)
							var valueNode = new ValueNode({
								name : parts.name,
								filter : parts.filter,
								binding : binding,
								isPointer : (parts.name === ".") ? true : false
							});

							vDom.addNode(valueNode);
							break;
						}

						//Standard text
						if(selected.nodeValue !== undefined && selected.nodeValue !== null && selected.nodeValue !== false){
							var textNode = new TextNode({
								name : "Text" + Mold.getId(),
								data : selected.nodeValue
							});
							vDom.addNode(textNode);
						}

						break;
				}
			}
			return vDom;
		}

		var rootNode = new RootNode({
			name : "root",
			protoDom : _doc,
			services : {
				template : config.template
			},
		});

		this.dom = _parseNode(_doc, rootNode);

		this.publics = {
		/**
		 * @method render
		 * @description trigger the renderservice
		 * @return {object} returns the renderd vdom
		 * @example Mold/Test/Lib/VDom/Builder.js#render
		 */
			render : function(){
				return rootNode.render();
			},
		/**
		 * @method reRender
		 * @description reRenders the vdom, recreat dom elements only if needed
		 */
			reRender : function(){
				rootNode.reRender();
			},

		/**
		 * @method renderString
		 * @description renders the vdom as a string
		 * @return {string} returns a string from the renderd vdom
		 */
			renderString : function(){
				return rootNode.renderString();
			}
		}
	}
)<commit_msg>console log removed<commit_after>/**
 * @author Jan Kaufmann <jan@moldjs.de>
 * @description build a vdom from a content-template string
 * @example Mold/Test/Lib/VDom/Builder#build
 */

"user strict";
Seed({
		name : "Mold.Lib.VDom.Builder",
		dna : "class",
		test : "Mold.Test.Lib.VDom.Builder",
		include : [
			"Mold.Lib.Dom",
			"Mold.Tools.Dev.CodeInclude",
			".ProtoNode",
			[
				{ DomNode : ".DomNode" },
				{ BlockNode : ".BlockNode" },
				{ ValueNode : ".ValueNode" },
				{ TextNode : ".TextNode" },
				{ AttributeNode : ".AttributeNode" },
				{ RootNode : ".RootNode" },
				{ Doc : ".VDoc"}
			]
		]
	},
	function(content, config){

		var config = config || {};

		var _dom = new Mold.Lib.Dom(content);
		var _newDoc = Doc;
		var _doc = _dom.get();
		var _template = [];
		var undefined;

		var BLOCK_START = "{{#";
		var BLOCK_NEGATIV = "{{^";
		var BLOCK_END = "{{/";
		var VALUE = "{{";
		var BINDED_VALUE = "{{*";
		var END = "}}";

		var _parseAttributes = function(attributes, domNode){

			var output = {};
			var i = 0, len = attributes.length;

			for(; i < len; i++){

				var selected = attributes[i];
				var newAttribute = new AttributeNode({
					name : selected.nodeName
				})

				domNode.addAttribute(newAttribute);
				newAttribute.addData(selected.nodeValue)

			}

		}

		var _parseAsText = function(content){

		}

		var _getFilter = function(name){
			var filter = {};
			if(~name.indexOf("|")){
				var nameParts = name.split("|");
				name = nameParts.shift();
				var i = 0, len = nameParts.length;

				for(; i < len; i++){
					if(~nameParts[i].indexOf("(")){
						var filterName = nameParts[i].substring(0, nameParts[i].indexOf("("))
						var expression = nameParts[i].substring(nameParts[i].indexOf("(") + 1, nameParts[i].lastIndexOf(")"));
						filter[filterName] = {
							expression : expression
						};
					}else{
						var filterParts = nameParts[i].split(':');
						var y = 1, paramLength = filterParts.length;
						var filterName = filterParts[0];

						filter[filterName] = {};

						for(; y < paramLength; y++){
							var paramParts = filterParts[y].split("=");
							filter[filterName][paramParts[0]] = (paramParts[1]) ? paramParts[1] : true;
						}
					}
				}
			}
			return { name : name, filter : filter}
		}

		var _parseNode = function(node, vDom, level){

			var level = level || 0;
			var parentNode = false;
			var collectedProtoDom = {};
			var i = 0, len = node.childNodes.length;

			for(; i < len; i++){
				var selected = node.childNodes[i];
				switch(selected.nodeType){

					//handel Elementnode
					case 1:

						var domNode = new DomNode({
							name : selected.nodeName
						});

						vDom.addNode(domNode);
						_parseAttributes(selected.attributes, domNode);
						_parseNode(selected, domNode)

						break;

					//handel Textnode
					case 3:
						//Block Node
						if(Mold.startsWith(selected.nodeValue, BLOCK_START)){

							var name = selected.nodeValue.replace(BLOCK_START, "").replace(END, "");

							var parts = _getFilter(name);
							var blockNode = new BlockNode({
								name : parts.name,
								filter : parts.filter
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;

							break;
						}

						//Block Negativ
						if(Mold.startsWith(selected.nodeValue, BLOCK_NEGATIV)){
							var name = selected.nodeValue.replace(BLOCK_NEGATIV, "").replace(END, "");
							var blockNode = new BlockNode({
								name : name,
								isNegative : true
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;
							break;
						}

						//Block End
						if(Mold.startsWith(selected.nodeValue, BLOCK_END)){
							vDom = vDom.parent;
							break;
						}

						//Value
						if(Mold.startsWith(selected.nodeValue, VALUE) || Mold.startsWith(selected.nodeValue, BINDED_VALUE)){

							var binding = (Mold.startsWith(selected.nodeValue, BINDED_VALUE)) ? true : false;
							var name = selected.nodeValue.replace(BINDED_VALUE, "").replace(VALUE, "").replace(END, "");
							var parts = _getFilter(name);
							var valueNode = new ValueNode({
								name : parts.name,
								filter : parts.filter,
								binding : binding,
								isPointer : (parts.name === ".") ? true : false
							});

							vDom.addNode(valueNode);
							break;
						}

						//Standard text
						if(selected.nodeValue !== undefined && selected.nodeValue !== null && selected.nodeValue !== false){
							var textNode = new TextNode({
								name : "Text" + Mold.getId(),
								data : selected.nodeValue
							});
							vDom.addNode(textNode);
						}

						break;
				}
			}
			return vDom;
		}

		var rootNode = new RootNode({
			name : "root",
			protoDom : _doc,
			services : {
				template : config.template
			},
		});

		this.dom = _parseNode(_doc, rootNode);

		this.publics = {
		/**
		 * @method render
		 * @description trigger the renderservice
		 * @return {object} returns the renderd vdom
		 * @example Mold/Test/Lib/VDom/Builder.js#render
		 */
			render : function(){
				return rootNode.render();
			},
		/**
		 * @method reRender
		 * @description reRenders the vdom, recreat dom elements only if needed
		 */
			reRender : function(){
				rootNode.reRender();
			},

		/**
		 * @method renderString
		 * @description renders the vdom as a string
		 * @return {string} returns a string from the renderd vdom
		 */
			renderString : function(){
				return rootNode.renderString();
			}
		}
	}
)<|endoftext|>


<commit_before>#!/usr/bin/env node

// todo: SAFETY CHECK!
// todo: this is a very bad implementation, i want a streams-based solution

const CONF = {
  storage_root: `${__dirname}/STORAGE`,
  port: 9988,
  containers: {
    vek: {
      root: 'http://www.vek-dverey.ru/media',
      transforms: {
        square_200x200: 'convert {source} -resize 200x200 -background white -gravity center -extent 200x200 {destination}',
        rectangle_80x200: 'convert {source} -resize 80x200 -background white -gravity center -extent 80x200 {destination}'
      }
    }
  }
};

const mkdirp = require('mkdirp');
const http = require('http');
const request = require('request');
const fs = require('fs');
const path = require('path');
const nodeStatic = require('node-static');
const shell = require('shelljs');

// request: {service_url}/vek/square_200x200/klin/impex1.png

var staticServer = new nodeStatic.Server(CONF.storage_root);

http.createServer(function(request, response) {
  request.addListener('end', function () {
    staticServer.serve(request, response, function (e, res) {
      if (e && e.status == 404) {
        try {
          var r = requestParser(request);
        } catch (err) {
          response.writeHead(404, {"Content-Type": "text/plain"});
          response.end('HTTP 404 - Not Found');
          return;
        }
        action(r, function(err) {
          if (err) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.end(`HTTP 404 - Not Found. (Request to origin error: ${err.message})`);
          } else {
            var relative = r.locals[r.transName].replace(CONF.storage_root, '');
            staticServer.serveFile(relative, 200, {}, request, response);
          }
        });
      }
    });
  }).resume();
}).listen(CONF.port);

function requestParser(request) {
  // requestInfo
  var r = {};

  var parts = request.url.split('/');
  r.container = parts[1];
  r.transName = parts[2];
  r.relativePath = '/' + parts.slice(3, parts.lenght).join('/');
  r.origin = CONF.containers[r.container].root + r.relativePath;

  if (r.transName == 'origin') {
    r.transform = 'origin';
  } else {
    r.transform = CONF.containers[r.container].transforms[r.transName];
  }

  if (!(r.container && r.transName && r.relativePath && r.transform)) {
    throw new Error();
  }

  r.locals = {};
  r.locals.origin = `${CONF.storage_root}/${r.container}/origin${r.relativePath}`;
  r.locals[r.transName] = `${CONF.storage_root}/${r.container}/${r.transName}${r.relativePath}`;

  return r;
}

function action(r, callback) {
  if (r.transName === 'origin') {
    getOrigin(r, callback);
  } else {
    getOrigin(r, function(err) {
      if (err) {
        callback(err);
        return;
      }
      var source = r.locals.origin;
      var dest = r.locals[r.transName];
      var destDirname = path.dirname(dest);
      mkdirp(destDirname, function(err) {
        if (err) {
          callback(err);
        }
        var transform = r.transform.replace('{source}', source).replace('{destination}', dest);
        // *******************************
        // * 99.9% of perfomance is here *
        // *******************************
        shell.exec(transform, {async: true, silent: true}, function(code, stdout, stderr) {
          if (code) {
            console.error('Exit code:', code);
            console.error('Program output:', stdout);
            console.error('Program stderr:', stderr);
            callback(new Error(`${code}: ${stderr}`));
          }
          callback();
        });
      });
    });
  }
}

function getOrigin(r, callback) {
  fs.stat(r.locals.origin, function(err, stats) {
    if (!err && stats.isFile()) {
      callback();
    } else {
      request.get(r.origin, {encoding: 'binary'}, function(err, response, body) {
        if (err) {
          console.error(err);
          return callback(err);
        }
        if (response.statusCode != 200) {
          callback(new Error(`Response status code is ${response.statusCode}`));
        } else {
          mkdirp(path.dirname(r.locals.origin), function(err) {
            if (err) {
              callback(err);
            } else {
              fs.writeFile(r.locals.origin, body, 'binary', function (err) {
                callback(err);
              });
            }
          });
        }
      });
    }
  });
}
<commit_msg>transforms change<commit_after>#!/usr/bin/env node

// todo: SAFETY CHECK!
// todo: this is a very bad implementation, i want a streams-based solution

const CONF = {
  storage_root: `${__dirname}/STORAGE`,
  port: 9988,
  containers: {
    vek: {
      root: 'http://www.vek-dverey.ru/media',
      transforms: {
        square_400x400: 'convert {source} -resize 400x400 -background white -gravity center -extent 400x400 {destination}',
        rectangle_160x400: 'convert {source} -resize 160x400 -background white -gravity center -extent 160x400 {destination}'
      }
    }
  }
};

const mkdirp = require('mkdirp');
const http = require('http');
const request = require('request');
const fs = require('fs');
const path = require('path');
const nodeStatic = require('node-static');
const shell = require('shelljs');

// request: {service_url}/vek/square_200x200/klin/impex1.png

var staticServer = new nodeStatic.Server(CONF.storage_root);

http.createServer(function(request, response) {
  request.addListener('end', function () {
    staticServer.serve(request, response, function (e, res) {
      if (e && e.status == 404) {
        try {
          var r = requestParser(request);
        } catch (err) {
          response.writeHead(404, {"Content-Type": "text/plain"});
          response.end('HTTP 404 - Not Found');
          return;
        }
        action(r, function(err) {
          if (err) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.end(`HTTP 404 - Not Found. (Request to origin error: ${err.message})`);
          } else {
            var relative = r.locals[r.transName].replace(CONF.storage_root, '');
            staticServer.serveFile(relative, 200, {}, request, response);
          }
        });
      }
    });
  }).resume();
}).listen(CONF.port);

function requestParser(request) {
  // requestInfo
  var r = {};

  var parts = request.url.split('/');
  r.container = parts[1];
  r.transName = parts[2];
  r.relativePath = '/' + parts.slice(3, parts.lenght).join('/');
  r.origin = CONF.containers[r.container].root + r.relativePath;

  if (r.transName == 'origin') {
    r.transform = 'origin';
  } else {
    r.transform = CONF.containers[r.container].transforms[r.transName];
  }

  if (!(r.container && r.transName && r.relativePath && r.transform)) {
    throw new Error();
  }

  r.locals = {};
  r.locals.origin = `${CONF.storage_root}/${r.container}/origin${r.relativePath}`;
  r.locals[r.transName] = `${CONF.storage_root}/${r.container}/${r.transName}${r.relativePath}`;

  return r;
}

function action(r, callback) {
  if (r.transName === 'origin') {
    getOrigin(r, callback);
  } else {
    getOrigin(r, function(err) {
      if (err) {
        callback(err);
        return;
      }
      var source = r.locals.origin;
      var dest = r.locals[r.transName];
      var destDirname = path.dirname(dest);
      mkdirp(destDirname, function(err) {
        if (err) {
          callback(err);
        }
        var transform = r.transform.replace('{source}', source).replace('{destination}', dest);
        // *******************************
        // * 99.9% of perfomance is here *
        // *******************************
        shell.exec(transform, {async: true, silent: true}, function(code, stdout, stderr) {
          if (code) {
            console.error('Exit code:', code);
            console.error('Program output:', stdout);
            console.error('Program stderr:', stderr);
            callback(new Error(`${code}: ${stderr}`));
          }
          callback();
        });
      });
    });
  }
}

function getOrigin(r, callback) {
  fs.stat(r.locals.origin, function(err, stats) {
    if (!err && stats.isFile()) {
      callback();
    } else {
      request.get(r.origin, {encoding: 'binary'}, function(err, response, body) {
        if (err) {
          console.error(err);
          return callback(err);
        }
        if (response.statusCode != 200) {
          callback(new Error(`Response status code is ${response.statusCode}`));
        } else {
          mkdirp(path.dirname(r.locals.origin), function(err) {
            if (err) {
              callback(err);
            } else {
              fs.writeFile(r.locals.origin, body, 'binary', function (err) {
                callback(err);
              });
            }
          });
        }
      });
    }
  });
}
<|endoftext|>