Repositories | Polyback | Log in to see private repositories


polyback-website / 0279ba1c25ece783ab4d4a7055b0fa01bd501cde / js/polygon/games.js

16,836 bytes | parent directory

polygon.games = 
{
	Joining: false,
	protocols: { 2009: "polygon-nine", 2010: "polygon-ten", 2011: "polygon-eleven", 2012: "polygon-twelve" },

	install: function(client)
	{
		$(".placelauncher .modal-dialog").css("max-width", "500px");
		$(".placelauncher .modal-content").empty().html($(".placelauncher .template.install").clone().html());
		$(".placelauncher .modal-content .year").text(client);
		$(".placelauncher .modal-content .install").attr("href", "https://setup" + client + ".pizzaboxer.xyz/Polygon" + client + ".exe");
		$(".placelauncher").modal();
	},

	error: function(text)
	{
		$(".placelauncher .modal-dialog span").hide();
		$(".placelauncher .modal-dialog h5").html(text);
		$(".placelauncher .modal-dialog a.btn").text("Close");
	},

	GetModalText: function(Text)
	{
		return $(".placelauncher .modal-content h5").text();
	},

	SetModalText: function(Text)
	{
		if (!$(".placelauncher").is(":visible"))
		{
			$(".placelauncher .modal-dialog").css("max-width", "300px");
			$(".placelauncher .modal-content").empty().html($(".placelauncher .template.launch").clone().html());
			$(".placelauncher").modal({"backdrop":"static"});
			$(".placelauncher .modal-content h5").fadeIn("slow");
		}

		if (polygon.games.GetModalText() == Text) return;

		$(".placelauncher .modal-content h5").hide();
		$(".placelauncher .modal-content h5").text(Text);
		$(".placelauncher .modal-content h5").fadeIn("slow");
	},

	Shutdown: function(jobId)
	{
		$.get('/api/games/shutdown', {jobId: jobId}, function(data)
		{
			if (data.success)
				toastr["success"](data.message);
			else
				toastr["error"](data.message);
		});
	},

	startGame: function(launchMode, version, visitUrl)
	{
		if (!polygon.games.Joining) return;

		polygon.games.SetModalText("Starting Polyback...");

		$.post("/Game/GetAuthTicket", function(ticket) 
		{
			// visitUrl += "&suggest=" + encodeURIComponent(ticket);

			// if we're in ide mode then we can try opening it in the same studio window
			if (launchMode == "ide" && typeof window.external !== 'undefined' && window.external.IsRobloxAppIDE)
			{
				try
				{
					var app = window.external.GetApp();
					var workspace = app.CreateGame("44340105256");
					workspace.ExecUrlScript(visitUrl, null, null, null, null);

					setTimeout(function(){ $(".placelauncher").modal("hide") }, 5000);
					return;
				}
				catch (e)
				{
					// fallback to uri launch
				}
			}

			var protocol = polygon.games.protocols[version] + ":1";
			protocol += "+launchmode:" + launchMode;

			if (launchMode == "ide")
			{
				protocol += "+script:";
			}
			else
			{
				protocol += "+joinscripturl:";
			}

			protocol += encodeURIComponent(visitUrl);

			protocol += "+ticket:" + encodeURIComponent(ticket);

			if (!polygon.games.Joining) return;

			window.protocolCheck(
				protocol,
				function(){ polygon.games.install(version); },
				function(){ setTimeout(function(){ $(".placelauncher").modal("hide") }, 5000); }, 
				2500
			);
		});
	}
};

// Polygon Player: the bootstrapper the site launches through polyback-player:// links.
polygon.games.Player =
{
	install: function()
	{
		$(".placelauncher .modal-dialog").css("max-width", "500px");
		$(".placelauncher .modal-content").empty().html($(".placelauncher .template.install").clone().html());
		$(".placelauncher .modal-content h5").text("You need the Polyback Player to play. Install it once, then click Play again.");
		$(".placelauncher .modal-content .install").attr("href", "/download");
		$(".placelauncher").modal();
	},

	// open the place in Polyback Studio (through the Polyback Player, signed in as us)
	edit: function(placeId)
	{
		polygon.games.Joining = true;
		polygon.games.SetModalText("Opening Polyback Studio...");
		$.post("/api/studio/launch", { placeId: placeId }, function(data)
		{
			if (!polygon.games.Joining) return;
			window.protocolCheck(
				data.url,
				function() { polygon.games.Player.install(); },
				function() { setTimeout(function() { $(".placelauncher").modal("hide"); }, 5000); },
				2500
			);
		}).fail(function(xhr)
		{
			var message = (xhr.responseJSON && xhr.responseJSON.message) || "Studio couldn't be opened. Please try again later.";
			polygon.games.error(message);
		});
	},

	// join a place (any server, started if needed), a particular running server by jobId,
	// (solo) a one-player server of our own, or (privateMode "solo" / "friends") a new
	// private server of our own. When the game servers have no free slot for a new server
	// we wait in their queue (the site answers "queued" with our position, and we poll it)
	// until ours is up; closing the dialog or leaving the page leaves the queue.
	queuedJob: null,
	pollTimer: null,

	// For a game that supports several client versions the site answers with the choice
	// first; we ask, and join again with the chosen version.
	join: function(placeId, jobId, solo, privateMode, version)
	{
		var player = polygon.games.Player;
		player.leaveQueue();
		polygon.games.Joining = true;
		polygon.games.SetModalText(solo || privateMode ? "Starting your server..." : "Finding a server...");
		var params = jobId ? { jobId: jobId } : { placeId: placeId };
		if (solo) params.solo = "1";
		if (privateMode) params.private = privateMode;
		if (version) params.version = version;
		$.post("/api/games/join", params, function(data)
		{
			if (!data.chooseVersion) return player.joinResponse(data);
			if (!polygon.games.Joining) return;
			player.chooseVersion(data.chooseVersion, function(chosen) { player.join(placeId, jobId, solo, privateMode, chosen); });
		}).fail(player.joinFailed);
	},

	chooseVersion: function(versions, callback)
	{
		var content = $(".placelauncher .modal-content");
		var body = $('<div class="modal-body text-center"><h5 class="font-weight-normal mb-3">Which version do you want to play?</h5></div>');
		$.each(versions, function(_, item)
		{
			$('<button type="button" class="btn btn-success btn-block choose-version"></button>')
				.text(item.version + (item.players ? " (" + item.players + " playing)" : ""))
				.click(function()
				{
					// back to the launcher's usual look, then carry on
					content.html($(".placelauncher .template.launch").html());
					callback(item.version);
				})
				.appendTo(body);
		});
		body.append('<a class="btn btn-sm btn-outline-danger btn-block px-4 mt-3 cancel-join" data-dismiss="modal">Cancel</a>');
		content.empty().append(body);
	},

	joinResponse: function(data)
	{
		var player = polygon.games.Player;
		if (data.queued)
		{
			// gave up meanwhile (Cancel): don't keep the place
			if (!polygon.games.Joining || (player.queuedJob !== null && player.queuedJob !== data.jobId))
			{
				if (player.queuedJob !== data.jobId) player.cancelRequest(data.jobId);
				return;
			}
			player.queuedJob = data.jobId;
			polygon.games.SetModalText(data.starting
				? "A server is free! Starting it..."
				: "You're in the queue: position " + data.position + " of " + data.queueLength);
			clearTimeout(player.pollTimer);
			player.pollTimer = setTimeout(function() { player.poll(data.jobId); }, 2000);
			return;
		}

		player.queuedJob = null;
		if (!polygon.games.Joining) return;
		polygon.games.SetModalText("Starting the Polyback Player...");
		window.protocolCheck(
			data.joinUrl,
			function() { polygon.games.Player.install(); },
			function() { setTimeout(function() { $(".placelauncher").modal("hide"); }, 5000); },
			2500
		);
	},

	joinFailed: function(xhr)
	{
		polygon.games.Player.queuedJob = null;
		if (!polygon.games.Joining) return;
		var message = (xhr.responseJSON && xhr.responseJSON.message) || "The game couldn't be started. Please try again later.";
		polygon.games.error(message);
	},

	// ask where we are in the queue (this also keeps our place: one not asked about for
	// ~30 seconds is dropped)
	poll: function(jobId)
	{
		var player = polygon.games.Player;
		if (!polygon.games.Joining || player.queuedJob !== jobId) return;
		$.post("/api/games/join", { queueJobId: jobId }, player.joinResponse).fail(player.joinFailed);
	},

	// leave the queue, if we're in it
	leaveQueue: function()
	{
		var player = polygon.games.Player;
		clearTimeout(player.pollTimer);
		var jobId = player.queuedJob;
		player.queuedJob = null;
		if (jobId) player.cancelRequest(jobId);
	},

	cancelRequest: function(jobId)
	{
		var csrf = $('meta[name="polygon-csrf"]').attr("content");
		// keepalive: still sent when we're leaving the page
		if (window.fetch)
		{
			var body = new FormData();
			body.append("queueJobId", jobId);
			body.append("cancel", "1");
			fetch("/api/games/join", { method: "POST", body: body, keepalive: true, credentials: "same-origin", headers: { "x-polygon-csrf": csrf } }).catch(function() {});
		}
		else
		{
			$.post("/api/games/join", { queueJobId: jobId, cancel: "1" });
		}
	}
};

polygon.games.PlaceLauncher = 
{
	PlaySolo: function(placeId, version)
	{
		polygon.games.Joining = true;
		polygon.games.startGame("play", version, "http://" + window.location.hostname + "/Game/Visit.ashx?PlaceID=" + placeId);
	},

	Edit: function(placeId, version)
	{
		polygon.games.Joining = true;
		polygon.games.startGame("ide", version, "http://" + window.location.hostname + "/Game/Edit.ashx?PlaceID=" + placeId);
	},

	Request: function(Parameters)
	{
		if (Parameters.request != "CheckGameJobStatus")
		{
			polygon.games.Joining = true;
			polygon.games.SetModalText("Requesting a server");
		}
		else
		{
			if (!polygon.games.Joining) return;
		}

		$.get("/api/games/placelauncher", Parameters, function(data)
		{
			if (!polygon.games.Joining) return;

			if (data.joinScriptUrl)
			{
				polygon.games.SetModalText(data.message);
				polygon.games.startGame("play", data.version, data.joinScriptUrl);
			}
			else if (data.jobId) 
			{
				polygon.games.SetModalText(data.message);
				setTimeout(function(){ polygon.games.PlaceLauncher.Request({request: "CheckGameJobStatus", jobId: data.jobId}); }, 3000);
			}
			else
			{ 
				polygon.games.error(data.message);
			}
		});
	}
}

polygon.games.Places = polygon.CreateControl(
{
	Container: "places",

	Properties: 
	{
		FilterBy: "Default",
		FilterVersion: "All",
		Query: "",

		SetFilter: function(Filter)
		{
			if (Filter.FilterBy != undefined) this.FilterBy = Filter.FilterBy;
			if (Filter.FilterVersion != undefined) this.FilterVersion = Filter.FilterVersion;
			if (Filter.Query != undefined) this.Query = Filter.Query;
			
			this.Display(1);
		}
	},

	AjaxConfig: function(Control)
	{
		return {
			type: "POST",
			url: "/api/games/fetch",
			data: 
			{ 
				FilterBy: Control.FilterBy, 
				FilterVersion: Control.FilterVersion, 
				Query: Control.Query 
			}
		}
	},

	PopulateCallback: function(Item, Template)
	{
		if (Item.OnlinePlayers === false)
		{
			// Template.find(".online-players").remove();
			Template.find(".online-players small").text("0 players online");
			Template.find(".online-players small").addClass("text-secondary");
		}

		return {Item: Item, Template: Template};
	},

	Initializers: function(Control)
	{
		$("." + Control.Container + "-container select.SortFilter").change(function()
		{ 
			Control.SetFilter({FilterBy: $(this).val()}); 
		});

		$("." + Control.Container + "-container select.VersionFilter").change(function() {
			wrapper = $("." + Control.Container + "-container div.version-filter-wrapper");
			version = $(this).val();
			
			if (version == "All") {
				wrapper.removeClass("input-group");
				wrapper.find("div.input-group-append").addClass("d-none");
			} else {
				wrapper.addClass("input-group");
				wrapper.find("div.input-group-append").removeClass("d-none");
				wrapper.find("a.version-filter-download").attr("href", "/download");
			}
			
			Control.SetFilter({ FilterVersion: version }); 
		});

		$("." + Control.Container + "-container button.SearchButton").click(function()
		{ 
			Control.SetFilter({Query: $("." + Control.Container + "-container input.SearchBox").val()}); 
		});

		$("." + Control.Container + "-container input.SearchBox").on("keypress", this, function(event)
		{
			if (event.which != 13) return;
			Control.SetFilter({Query: $("." + Control.Container + "-container input.SearchBox").val()}); 
		});

		if ($("." + Control.Container + "-container input.SearchBox").val() != "")
		{
			Control.SetFilter({Query: $("." + Control.Container + "-container input.SearchBox").val()}); 
		}
	}
});

polygon.games.RunningGames = polygon.CreateControl(
{
	Container: "running-games",

	ExtraComponents: [".refresh"],

	AjaxConfig: function(Control)
	{
		return {
			type: "POST",
			url: "/api/games/fetch-running",
			data: { PlaceID: $(".app").attr("data-asset-id") }
		}
	},

	PopulateCallback: function(Item, Template)
	{
		// usernames come HTML-escaped from the server
		$.each(Item.IngamePlayers, function(_, Player)
		{
			Template.find(".IngamePlayers").append(
				"<div class=\"col-2 px-1 mb-1 text-center\" style=\"line-height: normal\">\
					<a href=\"/user?ID=" + parseInt(Player.UserID) + "\">\
						<img src=\"" + Player.Thumbnail + "\" class=\"img-fluid\" title=\"" + Player.Username + (Player.IsFriend ? " (your friend)" : "") + "\" data-toggle=\"tooltip\" data-placement=\"bottom\">\
						<small class=\"d-block text-truncate" + (Player.IsFriend ? " font-weight-bold" : "") + "\">" + (Player.IsFriend ? "<i class=\"fas fa-user-friends\"></i> " : "") + Player.Username + "</small>\
					</a>\
				</div>"
			);
		});

		if (!Item.IngamePlayers.length) Template.find(".NoIngamePlayers").removeClass("d-none");
		if (Item.PlayersUncertain) Template.find(".PlayersUncertain").removeClass("d-none");

		if (Item.IsPrivateServer)
		{
			Template.find(".PrivateServerInfo").removeClass("d-none");
			if (Item.IsPrivateServerOwner)
				Template.find(".PrivateServerOwnerLabel").text("Your private server");
			else
				Template.find(".PrivateServerOwner").attr("href", "/user?ID=" + parseInt(Item.PrivateServerOwnerID)).html(Item.PrivateServerOwnerName);
		}

		if (!Item.CanShutdown)
		{
			Template.find(".ShutdownGame").remove();
		}

		return {Item: Item, Template: Template};
	},

	Initializers: function(Control)
	{
		$("body").on("click", ".ShutdownGame", function()
		{ 
			setTimeout(function(){ Control.Display(); }, 3000);
		});

		$("." + Control.Container + "-container .refresh").click(function()
		{ 
			Control.Display(); 
		});
	}
});

$("body").on("click", ".VisitButton.VisitButtonEdit", function()
{ 
	polygon.games.Player.edit($(this).attr("placeid")); 
});

$("body").on("click", ".VisitButton.VisitButtonSolo", function()
{ 
	polygon.games.Player.join($(this).attr("placeid"), null, true); 
});


$("body").on("click", ".VisitButton.VisitButtonPlay", function()
{ 
	if ($(this).attr("placeid") != undefined)
	{
		polygon.games.Player.join($(this).attr("placeid"));
	}
	else if ($(this).attr("jobid") != undefined)
	{
		polygon.games.Player.join(null, $(this).attr("jobid"));
	}
	else if ($(this).attr("userid") != undefined)
	{
		polygon.games.PlaceLauncher.Request({request: "RequestFollowUser", userId: $(this).attr("userId")}); 
	}
});

// Private Servers: choose who may join, then start it like a Visit
$("body").on("click", ".PrivateServersButton", function()
{
	var placeId = $(this).attr("placeid");
	polygon.buildModal({
		header: "Private Servers",
		body: "<p>Start a server of your own for this game:</p>\
			<p class=\"mb-1\"><b>Just me</b> &ndash; only you can join it, and it isn't listed anywhere.</p>\
			<p class=\"mb-0\"><b>Friends</b> &ndash; listed in this game's Games tab only for you and your friends, and only you and your friends can join it.</p>",
		buttons: [
			{class: "btn btn-success px-3 PrivateServerStart", attributes: {"data-mode": "solo", "placeid": parseInt(placeId)}, dismiss: true, text: "Just me"},
			{class: "btn btn-primary px-3 PrivateServerStart", attributes: {"data-mode": "friends", "placeid": parseInt(placeId)}, dismiss: true, text: "Friends"},
			{class: "btn btn-secondary px-3", dismiss: true, text: "Cancel"}
		]
	});
});

$("body").on("click", ".PrivateServerStart", function()
{
	var placeId = $(this).attr("placeid");
	var mode = $(this).attr("data-mode") == "friends" ? "friends" : "solo";
	// wait for the chooser to close before the launch dialog opens
	$(".global.modal").one("hidden.bs.modal", function()
	{
		polygon.games.Player.join(placeId, null, false, mode);
	});
});

$("body").on("click", ".ShutdownGame", function()
{ 
	polygon.games.Shutdown($(this).attr("jobid")); 
});

$("body").on("click", ".cancel-join", function()
{
	polygon.games.Joining = false;
	polygon.games.Player.leaveQueue();
});

// closing the launcher, or leaving the page, gives up our place in the queue
$("body").on("hidden.bs.modal", ".placelauncher", function()
{
	polygon.games.Player.leaveQueue();
});

$(window).on("pagehide", function()
{
	polygon.games.Player.leaveQueue();
});