Repositories | Polyback | Log in to see private repositories


polyback-website / db9a7ac7345e94204336a2a121c1338c5462f5f6 / js/polygon/chat.js

13,381 bytes | parent directory

// Friends chat (/chat): friends list with presence, 1:1 conversations, typing status.
// Real time by short polling /api/chat/poll (every few seconds while the tab is visible,
// slower while hidden); it returns only messages newer than the newest one shown, unread
// counts and who is typing, plus friends' statuses every few polls.
// Text from the server (names, messages, game names) is already HTML-escaped.

polygon.chat =
{
	PollVisible: 3000,
	PollHidden: 10000,
	PresenceEvery: 5, // polls
	TypingThrottle: 2500,

	Friends: {},
	FriendID: 0,
	LastID: 0,
	FirstID: 0,
	Loaded: false, // the open conversation's history has arrived
	Unread: {},
	Typing: [],
	PollCount: 0,
	PollTimer: null,
	Polling: false,
	TypingSentAt: 0,
	Generation: 0, // bumped when the open conversation changes, so stale responses are dropped

	statusText: function(friend)
	{
		if (friend.status == "ingame") return "In game: " + friend.game.name;
		if (friend.status == "online") return "Online";
		return "Offline";
	},

	setUnreadBadge: function(total)
	{
		if (total > 0) $(".unread-messages-indicator").text(total).removeClass("d-none");
		else $(".unread-messages-indicator").addClass("d-none");

		document.title = document.title.replace(/^\(\d+\) /, "");
		if (total > 0) document.title = "(" + total + ") " + document.title;
	},

	renderFriends: function()
	{
		var list = $(".chat-friends");
		var order = { ingame: 0, online: 1, offline: 2 };
		var friends = $.map(polygon.chat.Friends, function(friend) { return friend; });

		friends.sort(function(a, b)
		{
			if (order[a.status] != order[b.status]) return order[a.status] - order[b.status];
			return a.username.toLowerCase() < b.username.toLowerCase() ? -1 : 1;
		});

		list.find(".loading").remove();
		list.find(".chat-friend").remove();
		$(".chat-no-friends").toggleClass("d-none", friends.length > 0);

		$.each(friends, function(_, friend)
		{
			var unread = polygon.chat.Unread[friend.userId] || 0;
			var typing = polygon.chat.Typing.indexOf(friend.userId) != -1;
			var title = friend.status == "offline" ? ' title="Last seen ' + friend.lastOnlineText + '"' : '';

			var html = '<a class="list-group-item list-group-item-action chat-friend d-flex align-items-center px-2 py-2' + (friend.userId == polygon.chat.FriendID ? ' active' : '') + '" data-friend-id="' + friend.userId + '">';
			html += '<img class="chat-avatar rounded mr-2" src="' + (friend.avatar || "") + '" alt="">';
			html += '<div class="flex-grow-1 text-truncate">';
			html += '<div>' + friend.username + (typing ? ' <small class="font-italic chat-friend-typing">typing&hellip;</small>' : '') + '</div>';
			html += '<div class="chat-friend-status text-truncate chat-status-' + friend.status + '"' + title + '><span class="chat-status-dot"></span>' + polygon.chat.statusText(friend) + '</div>';
			html += '</div>';
			if (unread > 0) html += '<span class="badge badge-danger badge-pill ml-1">' + unread + '</span>';
			html += '</a>';

			list.append(html);
		});
	},

	renderHeader: function()
	{
		var friend = polygon.chat.Friends[polygon.chat.FriendID];
		if (!friend) return;

		var title = '<a href="/user?ID=' + friend.userId + '">' + friend.username + '</a> ';
		title += '<small class="chat-status-' + friend.status + '"><span class="chat-status-dot"></span>';
		if (friend.status == "ingame") title += 'In game: <a href="' + friend.game.url + '">' + friend.game.name + '</a>';
		else title += polygon.chat.statusText(friend);
		title += '</small>';
		$(".chat-conversation-title").html(title);

		var actions = "";
		if (friend.status == "ingame")
		{
			// the game page's Join: /api/games/join with that particular server
			if (friend.game.jobId && /^[0-9a-f-]{36}$/.test(friend.game.jobId))
				actions = '<button class="btn btn-sm btn-success VisitButton VisitButtonPlay" jobid="' + friend.game.jobId + '"><i class="fas fa-play"></i> Join</button>';
			else
				actions = '<a class="btn btn-sm btn-light" href="' + friend.game.url + '">View game</a>';
		}
		$(".chat-conversation-actions").html(actions);
	},

	renderTyping: function()
	{
		var friend = polygon.chat.Friends[polygon.chat.FriendID];
		if (friend && polygon.chat.Typing.indexOf(friend.userId) != -1) $(".chat-typing").html(friend.username + " is typing&hellip;");
		else $(".chat-typing").empty();
	},

	messageHtml: function(message)
	{
		var mine = message.sender == polygon.user.id;
		var html = '<div class="d-flex mb-2" data-message-id="' + message.id + '">';
		html += '<div class="chat-message rounded px-2 py-1 ' + (mine ? 'chat-message-mine bg-primary text-white' : 'chat-message-theirs') + '" title="' + message.timeText + '">';
		html += message.message;
		html += '</div></div>';
		return html;
	},

	appendMessages: function(messages)
	{
		var box = $(".chat-messages");
		var atBottom = box[0].scrollHeight - box.scrollTop() - box.outerHeight() < 60;
		var added = false;

		$.each(messages, function(_, message)
		{
			if (message.id <= polygon.chat.LastID) return;
			box.append(polygon.chat.messageHtml(message));
			polygon.chat.LastID = message.id;
			if (!polygon.chat.FirstID) polygon.chat.FirstID = message.id;
			added = true;
		});

		box.find(".chat-placeholder").remove();
		if (added && (atBottom || messages[messages.length - 1].sender == polygon.user.id)) box.scrollTop(box[0].scrollHeight);
	},

	prependMessages: function(messages, more)
	{
		var box = $(".chat-messages");
		var oldHeight = box[0].scrollHeight;
		var html = "";

		$.each(messages, function(_, message) { html += polygon.chat.messageHtml(message); });

		box.find(".chat-load-older").remove();
		box.prepend(html);
		if (messages.length) polygon.chat.FirstID = messages[0].id;
		if (more) box.prepend('<div class="text-center mb-2 chat-load-older"><button class="btn btn-sm btn-light">Load older messages</button></div>');

		box.scrollTop(box[0].scrollHeight - oldHeight);
	},

	open: function(friendId)
	{
		friendId = parseInt(friendId);
		if (!polygon.chat.Friends[friendId]) return;

		polygon.chat.stopTyping();
		polygon.chat.Generation++;
		polygon.chat.FriendID = friendId;
		polygon.chat.LastID = 0;
		polygon.chat.FirstID = 0;
		polygon.chat.Loaded = false;
		delete polygon.chat.Unread[friendId];

		$(".chat-messages").html('<div class="text-center py-5"><span class="spinner-border" role="status"></span></div>');
		$(".chat-compose").removeClass("d-none");
		$(".chat-input").val("").trigger("input");
		polygon.chat.renderHeader();
		polygon.chat.renderTyping();
		polygon.chat.renderFriends();

		if (window.history.replaceState) window.history.replaceState(null, "", "/chat?with=" + friendId);

		var generation = polygon.chat.Generation;
		$.post("/api/chat/history", { friendId: friendId }, function(data)
		{
			if (generation != polygon.chat.Generation) return;
			if (!data.success) return toastr["error"](data.message);

			polygon.chat.Loaded = true;
			$(".chat-messages").empty();
			if (!data.messages.length) $(".chat-messages").html('<p class="chat-placeholder text-muted text-center mt-5">No messages yet. Say hi!</p>');
			polygon.chat.appendMessages(data.messages);
			if (data.more) polygon.chat.prependMessages([], true);
			$(".chat-messages").scrollTop($(".chat-messages")[0].scrollHeight);
			$(".chat-input").focus();
		});
	},

	loadOlder: function()
	{
		var generation = polygon.chat.Generation;
		$(".chat-load-older button").attr("disabled", "disabled");

		$.post("/api/chat/history", { friendId: polygon.chat.FriendID, before: polygon.chat.FirstID }, function(data)
		{
			if (generation != polygon.chat.Generation) return;
			if (!data.success) return toastr["error"](data.message);
			polygon.chat.prependMessages(data.messages, data.more);
		});
	},

	send: function()
	{
		var input = $(".chat-input");
		var text = $.trim(input.val());
		var maxLength = parseInt($(".app").attr("data-chat-max-length"));
		var button = $(".chat-send");

		if (!text.length || !polygon.chat.FriendID) return;
		if (text.length > maxLength) return toastr["error"]("Your message can't be longer than " + maxLength + " characters");

		var generation = polygon.chat.Generation;
		polygon.button.busy(button);

		$.post("/api/chat/send", { friendId: polygon.chat.FriendID, message: text }, function(data)
		{
			polygon.button.active(button);
			if (!data.success) return toastr["error"](data.message);

			polygon.chat.TypingSentAt = 0; // sending ends "typing" on the server too
			if (generation != polygon.chat.Generation) return;
			input.val("").trigger("input").focus();
			polygon.chat.appendMessages([data.chatMessage]);
		}).fail(function()
		{
			polygon.button.active(button);
			toastr["error"]("Your message couldn't be sent. Please try again.");
		});
	},

	// tell the friend we're typing (at most every TypingThrottle ms; it expires by itself)
	typing: function()
	{
		if (!polygon.chat.FriendID) return;

		if (!$.trim($(".chat-input").val()).length) return polygon.chat.stopTyping();
		if (Date.now() - polygon.chat.TypingSentAt < polygon.chat.TypingThrottle) return;

		polygon.chat.TypingSentAt = Date.now();
		$.post("/api/chat/typing", { friendId: polygon.chat.FriendID, typing: "true" });
	},

	stopTyping: function()
	{
		if (!polygon.chat.TypingSentAt || !polygon.chat.FriendID) return;
		polygon.chat.TypingSentAt = 0;
		$.post("/api/chat/typing", { friendId: polygon.chat.FriendID, typing: "false" });
	},

	loadFriends: function(callback)
	{
		$.post("/api/chat/friends", function(data)
		{
			if (!data.success) return;

			polygon.chat.Friends = {};
			$.each(data.friends, function(_, friend) { polygon.chat.Friends[friend.userId] = friend; });
			polygon.chat.Unread = data.unread;
			polygon.chat.setUnreadBadge(data.unreadTotal);

			if (polygon.chat.FriendID && !polygon.chat.Friends[polygon.chat.FriendID]) polygon.chat.close();

			polygon.chat.renderFriends();
			polygon.chat.renderHeader();
			if (callback) callback();
		});
	},

	close: function()
	{
		polygon.chat.Generation++;
		polygon.chat.FriendID = 0;
		$(".chat-compose").addClass("d-none");
		$(".chat-conversation-title").text("Select a friend to chat with");
		$(".chat-conversation-actions").empty();
		$(".chat-messages").html('<p class="chat-placeholder text-muted text-center mt-5">Click one of your friends to start chatting.</p>');
	},

	schedulePoll: function()
	{
		clearTimeout(polygon.chat.PollTimer);
		polygon.chat.PollTimer = setTimeout(polygon.chat.poll, document.hidden ? polygon.chat.PollHidden : polygon.chat.PollVisible);
	},

	poll: function()
	{
		if (polygon.chat.Polling) return;

		var presence = ++polygon.chat.PollCount % polygon.chat.PresenceEvery == 0;
		var generation = polygon.chat.Generation;
		var params = {};
		if (polygon.chat.FriendID) params.friendId = polygon.chat.FriendID;
		if (polygon.chat.FriendID && polygon.chat.Loaded) params.since = polygon.chat.LastID;
		if (presence) params.presence = "1";

		polygon.chat.Polling = true;

		$.post("/api/chat/poll", params, function(data)
		{
			if (!data.success)
			{
				// no longer friends with the open conversation's friend
				polygon.chat.close();
				polygon.chat.loadFriends();
				return;
			}

			polygon.chat.Unread = data.unread;
			polygon.chat.Typing = data.typing || [];
			polygon.chat.setUnreadBadge(data.unreadTotal);

			if (generation == polygon.chat.Generation && polygon.chat.Loaded && data.messages.length)
				polygon.chat.appendMessages(data.messages);

			if (data.friends)
			{
				var changed = data.friends.length != Object.keys(polygon.chat.Friends).length;

				$.each(data.friends, function(_, friend)
				{
					var known = polygon.chat.Friends[friend.userId];
					if (!known) { changed = true; return; }
					friend.avatar = known.avatar;
					polygon.chat.Friends[friend.userId] = friend;
				});

				// someone was friended or unfriended: reload the whole list (with avatars)
				if (changed) return polygon.chat.loadFriends();
				polygon.chat.renderHeader();
			}

			polygon.chat.renderFriends();
			polygon.chat.renderTyping();
		}).fail(function(xhr)
		{
			if (xhr.status == 401) window.location.reload();
		}).always(function()
		{
			polygon.chat.Polling = false;
			polygon.chat.schedulePoll();
		});
	}
};

$(function()
{
	if (!$(".chat-friends").length) return;

	polygon.chat.loadFriends(function()
	{
		var withId = parseInt($(".app").attr("data-chat-with"));
		if (withId && polygon.chat.Friends[withId]) polygon.chat.open(withId);
		polygon.chat.schedulePoll();
	});

	$(".chat-friends").on("click", ".chat-friend", function()
	{
		var friendId = parseInt($(this).attr("data-friend-id"));
		if (friendId != polygon.chat.FriendID) polygon.chat.open(friendId);
	});

	$(".chat-messages").on("click", ".chat-load-older button", polygon.chat.loadOlder);

	$(".chat-form").on("submit", function(event)
	{
		event.preventDefault();
		polygon.chat.send();
	});

	$(".chat-input").on("input", function()
	{
		var maxLength = $(".app").attr("data-chat-max-length");
		$(".chat-counter").text($(this).val().length + "/" + maxLength);
	});

	$(".chat-input").on("keyup", function(event)
	{
		if (event.which == 13) return;
		polygon.chat.typing();
	});

	$(".chat-input").on("blur", polygon.chat.stopTyping);

	// coming back to the tab: catch up straight away
	$(document).on("visibilitychange", function()
	{
		if (!document.hidden) { clearTimeout(polygon.chat.PollTimer); polygon.chat.poll(); }
	});
});