Repositories | Polyback | Log in to see private repositories


polyback-website / e42532356725a8793cd69d6a3842fafc119421ea / api/chat/poll.php

1,818 bytes | parent directory

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

// The chat page's short poll (every few seconds; this request also keeps you "online" through
// core.php's Users::UpdatePing).
//   POST friendId (optional: the open conversation), since (newest message id the page has, once loaded),
//        presence=1 (optional: include friends' statuses, without avatars)
// Response: {"success":true,"messages":[...new in the open conversation],"unread":{...},
//            "unreadTotal":n, "typing":[friend ids typing to you], "friends":[...] (with presence=1)}

use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Chat;

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

$userId = SESSION["user"]["id"];
$friendId = API::GetParameter("POST", "friendId", "int", 0);
$since = isset($_POST["since"]) ? API::GetParameter("POST", "since", "int") : null;
$presence = ($_POST["presence"] ?? "") === "1";

$unread = Chat::GetUnreadCounts($userId);
$response = ["status" => 200, "success" => true, "message" => "OK", "messages" => []];

if ($friendId)
{
	if (!Chat::AreFriends($userId, $friendId)) API::respond(200, false, "You can only chat with your friends");

	// (the page loads a conversation through history first and only then polls with since)
	if ($since !== null) $response["messages"] = Chat::GetMessages($userId, $friendId, max(0, $since));

	// the conversation is open, so whatever the friend sent is read now
	if (isset($unread[$friendId]))
	{
		Chat::MarkRead($userId, $friendId);
		unset($unread[$friendId]);
	}
}

$response["unread"] = (object) $unread;
$response["unreadTotal"] = array_sum($unread);
$response["typing"] = Chat::GetTypingTo($userId);
if ($presence) $response["friends"] = Chat::GetFriendsPresence($userId);

API::respondCustom($response);