diff --git a/app/realtime.php b/app/realtime.php index aae66036d7..9c8ad2d0ab 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -30,6 +30,7 @@ use Utopia\Database\Adapter\Pool as DatabasePool; use Utopia\Database\Database; use Utopia\Database\DateTime; use Utopia\Database\Document; +use Utopia\Database\Exception\Duplicate; use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -1224,8 +1225,19 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re if ($presenceId !== 'unique()') { $presenceDocument->setAttribute('$id', $presenceId); } - - $presence = $database->upsertDocument('presenceLogs', $presenceDocument); + /** @var Document|null $presence */ + $presence = null; + try { + $presence = $database->upsertDocument('presenceLogs', $presenceDocument); + } catch (Duplicate $th) { + // will be triggerd in case of mongodb adapter everytime as $id needs to be same as well here + // in mongodb , upsert works on basis of set and unset by comparing the document with the existing one + // if presenceId differs then it will create a new document and not update the existing one + // TODO: send better error message telling about the presenceId mismatch + $existingPresence = $database->findOne('presenceLogs', [Query::equal('userId', [$userId])]); + $presenceDocument->setAttribute('$id', $existingPresence->getId()); + $presence = $database->upsertDocument('presenceLogs', $presenceDocument); + } $presence->removeAttribute('hostname');