Repositories | Polyback | Log in to see private repositories


polyback-website / b0d92d543d33db09acbae728aa0eb9b4a0a682ce / api/games/join.php

14,875 bytes | parent directory

<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';

// Join a game with the Polygon Player: find (or start) a server for the place and return a
// polyback-player:// link with the server address and a one-time join ticket.
//   POST placeId, or jobId (a particular running server, from the place's server list);
//   solo=1 (the Visit button), or private=solo|friends (Private Servers): a new server of
//   the user's own. "solo" ("Just me") is a one-player server only they can join;
//   "friends" is listed for, and joinable by, only them and their friends. Neither is ever
//   matched into by Play.
//   version=2016M: the client version to play on. Servers of different versions are never
//   mixed. Not needed for a place with one version, or with jobId (the server's own is used);
//   otherwise, without it, the answer is the choice to offer (no server is found or started):
//   {"success":true,"chooseVersion":[{"version":"2014M","players":3},...]}
// Response: {"success":true,"joinUrl":"polyback-player://join?...","host":...,"port":...}
//
// Queue: when the game server has no free slot for a new server, the request waits in its
// queue (first come, first served) instead of failing. The response is then
//   {"success":true,"queued":true,"jobId":"...","position":3,"queueLength":5,"starting":false}
// and the page polls with POST queueJobId=<jobId> (every couple of seconds; a request nobody
// polls for ~30 s is dropped) until it gets the normal join response above - the join link is
// only issued once the server is really up. POST queueJobId=<jobId>&cancel=1 leaves the queue.
// Joining a running server with room (jobId, or Play finding one) is never queued.

use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\ClientVersions;
use pizzaboxer\ProjectPolygon\ClientContent;
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Gameservers;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\Polygon;

API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);

$userId = (int) SESSION["user"]["id"];

// the join link for a running server
function respondJoin($job, $place, $era)
{
	$ticket = Gameservers::CreateTicket(SESSION["user"]["id"], $job->JobID);
	$joinUrl = "polyback-player://join?" . http_build_query([
		"host" => $job->MachineAddress,
		"port" => (int) $job->ServerPort,
		"ticket" => $ticket,
		"era" => $era,
		"place" => (int) $place->id,
		// lets the Polyback Player fetch this era's client content pack (short-lived)
		"auth" => ClientContent::CreateToken(SESSION["user"]["id"]),
		// the site the player should talk to (assets, updates), as they reached it
		"site" => Polygon::SiteURL(),
	]);

	API::respondCustom([
		"status" => 200,
		"success" => true,
		"joinUrl" => $joinUrl,
		"host" => $job->MachineAddress,
		"port" => (int) $job->ServerPort,
		"era" => $era,
	]);
}

// still waiting for a server: where we are in the queue
function respondQueued($jobId, $answer)
{
	$starting = $answer["state"] === "starting";
	API::respondCustom([
		"status" => 200,
		"success" => true,
		"queued" => true,
		"jobId" => $jobId,
		"starting" => $starting,
		"position" => $starting ? 0 : (int) $answer["position"],
		"queueLength" => $starting ? 0 : (int) $answer["queueLength"],
		"message" => $starting ? "A server is free! Starting it..." : "You're in the queue: position {$answer["position"]} of {$answer["queueLength"]}",
	]);
}

function closeJob($jobId)
{
	Database::singleton()->run(
		"UPDATE GameJobs SET Status = 'Closed', LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j AND Status IN ('Queued', 'Loading')",
		[":j" => $jobId]
	);
}

// leave the queue (the machine drops the request, or stops the game if it's just starting)
function cancelQueued($job)
{
	$server = Database::singleton()->run("SELECT * FROM GameServers WHERE ServerID = :s", [":s" => $job->ServerID])->fetch(PDO::FETCH_OBJ);
	if ($server) Gameservers::StopJob($server, $job->JobID);
	closeJob($job->JobID);
}

// the client version a server runs (not the place's: that can change, or be several)
function jobEra($job, $place)
{
	return ClientVersions::Normalize($job->Version) ?? ClientVersions::Normalize($place->Version) ?? ClientVersions::DEFAULT;
}

// a running public server for this place and client version, on the latest engine, with room left
function findRunningServer($place, $era, $latest)
{
	return Database::singleton()->run(
		"SELECT j.* FROM GameJobs j
		 JOIN GameServers s ON s.ServerID = j.ServerID AND s.Online = 1 AND s.LastUpdated + 90 > UNIX_TIMESTAMP()
		 WHERE j.PlaceID = :p AND j.Status = 'Ready' AND j.Private = 0 AND j.PlayerCount < :max AND j.EngineVersion = :v AND j.Version = :era
		 ORDER BY j.PlayerCount DESC LIMIT 1",
		[":p" => $place->id, ":max" => (int) ($place->MaxPlayers ?: 12), ":v" => $latest, ":era" => $era]
	)->fetch(PDO::FETCH_OBJ);
}

// a new server is up: check it runs the latest version and mark it Ready (or respond with
// the error). Returns its GameJobs row.
function finishStart($server, $jobId, $started, $latest)
{
	if ($started["version"] !== $latest)
	{
		// the machine hasn't got the new release yet: a client couldn't join this game
		Gameservers::StopJob($server, $jobId);
		Database::singleton()->run("UPDATE GameJobs SET Status = 'Closed', EngineVersion = :v, LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j", [":v" => $started["version"], ":j" => $jobId]);
		API::respond(503, false, "The game servers are updating to the latest version. Please try again in a minute.");
	}
	Database::singleton()->run(
		"UPDATE GameJobs SET Status = 'Ready', MachineAddress = :h, ServerPort = :port, EngineVersion = :v, LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j",
		[":h" => $started["host"], ":port" => $started["port"], ":v" => $started["version"], ":j" => $jobId]
	);
	return Database::singleton()->run("SELECT * FROM GameJobs WHERE JobID = :j", [":j" => $jobId])->fetch(PDO::FETCH_OBJ);
}

// waiting in the queue: poll for our place (or cancel)
if (isset($_POST["queueJobId"]))
{
	$expired = "Your place in the queue has expired. Please try again.";
	$job = Database::singleton()->run(
		"SELECT * FROM GameJobs WHERE JobID = :j", [":j" => substr((string) $_POST["queueJobId"], 0, 36)]
	)->fetch(PDO::FETCH_OBJ);
	if (!$job || (int) $job->RequestedBy !== $userId) API::respond(404, false, $expired);

	if (($_POST["cancel"] ?? "") === "1")
	{
		if ($job->Status === "Queued") cancelQueued($job);
		API::respond(200, true, "You've left the queue");
	}

	$place = Database::singleton()->run("SELECT * FROM assets WHERE id = :id AND type = 9", [":id" => $job->PlaceID])->fetch(PDO::FETCH_OBJ);
	if (!$place) API::respond(404, false, "That game doesn't exist");
	$era = jobEra($job, $place);

	// a repeated poll after the server came up
	if ($job->Status === "Ready") respondJoin($job, $place, $era);
	if ($job->Status !== "Queued") API::respond(404, false, $expired);

	$latest = Gameservers::LatestClientVersion();
	if ($latest === null) API::respond(503, false, "The game client hasn't been published yet");

	// Play: a public server with room may have turned up meanwhile; take it instead
	if (!$job->Private)
	{
		$running = findRunningServer($place, $era, $latest);
		if ($running)
		{
			cancelQueued($job);
			respondJoin($running, $place, $era);
		}
	}

	$server = Database::singleton()->run("SELECT * FROM GameServers WHERE ServerID = :s", [":s" => $job->ServerID])->fetch(PDO::FETCH_OBJ);
	if (!$server)
	{
		closeJob($job->JobID);
		API::respond(404, false, $expired);
	}
	$answer = Gameservers::JobStatus($server, $job->JobID);
	if (!is_array($answer) || $answer["state"] === "full")
	{
		closeJob($job->JobID);
		API::respond(503, false, "The game couldn't be started: " . (is_array($answer) ? $answer["message"] : $answer));
	}
	if ($answer["state"] === "gone")
	{
		closeJob($job->JobID);
		API::respond(404, false, $expired);
	}
	if ($answer["state"] !== "running")
	{
		Database::singleton()->run("UPDATE GameJobs SET LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j", [":j" => $job->JobID]);
		respondQueued($job->JobID, $answer);
	}
	respondJoin(finishStart($server, $job->JobID, $answer, $latest), $place, $era);
}

$placeId = (int) ($_POST["placeId"] ?? 0);
$private = $_POST["private"] ?? (($_POST["solo"] ?? "") === "1" ? "solo" : "");
if (!in_array($private, ["", "solo", "friends"], true)) API::respond(400, false, "Unknown kind of private server");
$solo = $private === "solo";
$privateMode = ["" => null, "solo" => "Solo", "friends" => "Friends"][$private];
$wantJob = null;
if (isset($_POST["jobId"]))
{
	$wantJob = Database::singleton()->run(
		"SELECT * FROM GameJobs WHERE JobID = :j", [":j" => (string) $_POST["jobId"]]
	)->fetch(PDO::FETCH_OBJ);
	if (!$wantJob || $wantJob->Status != "Ready") API::respond(404, false, "That server isn't running any more");
	// private servers: only the owner (and, for friends-only ones, the owner's friends). The
	// same answer as a closed server, so others can't probe for them.
	if (!Games::CanJoinJob($wantJob, SESSION["user"]["id"])) API::respond(404, false, "That server isn't running any more");
	if ($privateMode !== null) API::respond(400, false, "A private server can't be started on a running server");
	$placeId = (int) $wantJob->PlaceID;
}
$place = Database::singleton()->run("SELECT * FROM assets WHERE id = :id AND type = 9", [":id" => $placeId])->fetch(PDO::FETCH_OBJ);
if (!$place) API::respond(404, false, "That game doesn't exist");
if ($place->approved != 1 && $place->creator != SESSION["user"]["id"]) API::respond(403, false, "That game isn't available");
if ($place->Access == "Friends" && !Games::CanPlayGame($place)) API::respond(403, false, "Only the creator's friends can play this game");

// which client version: the server's, the only one, or the player's choice
$supported = ClientVersions::Supported($place);
if ($wantJob) $era = jobEra($wantJob, $place);
else if (count($supported) === 1) $era = $supported[0];
else if (($_POST["version"] ?? "") === "")
{
	$players = Database::singleton()->run(
		"SELECT j.Version, SUM(j.PlayerCount) FROM GameJobs j
		 JOIN GameServers s ON s.ServerID = j.ServerID AND s.Online = 1 AND s.LastUpdated + 90 > UNIX_TIMESTAMP()
		 WHERE j.PlaceID = :p AND j.Status = 'Ready' AND j.Private = 0 GROUP BY j.Version",
		[":p" => $place->id]
	)->fetchAll(PDO::FETCH_KEY_PAIR);
	API::respondCustom(["status" => 200, "success" => true, "chooseVersion" => array_map(
		fn($v) => ["version" => $v, "players" => (int) ($players[$v] ?? 0)], $supported
	)]);
}
else
{
	$era = $_POST["version"];
	if (!in_array($era, $supported, true)) API::respond(400, false, "This game doesn't support that version");
}
$place->Version = $era; // what the game server is told to run

// rate limit: a few join requests per minute per user
$recent = Database::singleton()->run(
	"SELECT COUNT(*) FROM JoinTickets WHERE UserID = :u AND Created + 60 > UNIX_TIMESTAMP()",
	[":u" => SESSION["user"]["id"]]
)->fetchColumn();
if ($recent >= 5) API::respond(429, false, "You're joining games too quickly. Please wait a moment.");

// a few private servers per user at a time (each one is a whole game server)
if ($privateMode !== null)
{
	$open = Database::singleton()->run(
		"SELECT COUNT(*) FROM GameJobs j
		 JOIN GameServers s ON s.ServerID = j.ServerID AND s.Online = 1 AND s.LastUpdated + 90 > UNIX_TIMESTAMP()
		 WHERE j.OwnerID = :u AND j.Private = 1 AND j.Status IN ('Loading', 'Ready')",
		[":u" => SESSION["user"]["id"]]
	)->fetchColumn();
	if ($open >= 3) API::respond(429, false, "You already have 3 private servers running. Close one (leave it, or shut it down from the Games tab) before starting another.");
}

// Players always get the latest client (the Polygon Player updates before launching), and
// a client can only join a server running the very same version. So only games on the
// latest version are joined; older ones get no new players and close once empty.
$latest = Gameservers::LatestClientVersion();
if ($latest === null) API::respond(503, false, "The game client hasn't been published yet");

if ($wantJob)
{
	// a particular server: it must be on the latest version and have room
	if ($wantJob->EngineVersion !== $latest)
		API::respond(409, false, "That server is running an older version of the game and will close once its players leave. Click Play to join a server on the latest version.");
	if ((int) $wantJob->PlayerCount >= (int) ($place->MaxPlayers ?: 12)) API::respond(409, false, "That server is full");
	$online = Database::singleton()->run(
		"SELECT COUNT(*) FROM GameServers WHERE ServerID = :s AND Online = 1 AND LastUpdated + 90 > UNIX_TIMESTAMP()",
		[":s" => $wantJob->ServerID]
	)->fetchColumn();
	if (!$online) API::respond(404, false, "That server isn't running any more");
}

// a running server for this place, on the latest version, with room left (never a private
// one; a Visit or private server always gets a fresh server)
$job = $wantJob ?: ($privateMode !== null ? null : findRunningServer($place, $era, $latest));

if (!$job)
{
	$server = Gameservers::PickServer();
	if (!$server) API::respond(503, false, "There are no game servers available right now. Please try again later.");
	// one place in the queue per player: a new request replaces any older one still waiting
	$waiting = Database::singleton()->run(
		"SELECT * FROM GameJobs WHERE RequestedBy = :u AND Status = 'Queued'", [":u" => $userId]
	)->fetchAll(PDO::FETCH_OBJ);
	foreach ($waiting as $old) cancelQueued($old);

	$jobId = generateUUID();
	Database::singleton()->run(
		"INSERT INTO GameJobs (JobID, RequestedBy, ServerID, Version, PlaceID, TimeCreated, LastUpdated, Status, Private, OwnerID, PrivateMode)
		 VALUES (:j, :u, :s, :v, :p, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 'Loading', :priv, :owner, :mode)",
		[":j" => $jobId, ":u" => SESSION["user"]["id"], ":s" => $server->ServerID, ":v" => $era, ":p" => $place->id,
		 ":priv" => $privateMode !== null ? 1 : 0, ":owner" => $privateMode !== null ? SESSION["user"]["id"] : null, ":mode" => $privateMode]
	);
	$started = Gameservers::StartJob($server, $jobId, $place, $solo ? 1 : null);
	if (!is_array($started) || $started["state"] === "full")
	{
		Database::singleton()->run("UPDATE GameJobs SET Status = 'Closed', LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j", [":j" => $jobId]);
		if (is_array($started)) API::respond(503, false, $started["message"]);
		API::respond(503, false, "The game couldn't be started: $started");
	}
	if ($started["state"] !== "running")
	{
		// no free slot: wait in the machine's queue (the page polls with queueJobId)
		Database::singleton()->run("UPDATE GameJobs SET Status = 'Queued', LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j", [":j" => $jobId]);
		respondQueued($jobId, $started);
	}
	$job = finishStart($server, $jobId, $started, $latest);
}

respondJoin($job, $place, $era);