57 lines
2.0 KiB
C#
57 lines
2.0 KiB
C#
using System.Text;
|
|
|
|
namespace Messenger.Api.Services;
|
|
|
|
// Непрозрачный для клиента cursor keyset-пагинации: (created_at, id) последнего элемента страницы.
|
|
// Привязан к ресурсу (scope): cursor от другого списка или чата отклоняется как 400.
|
|
public static class Cursors
|
|
{
|
|
public const string Chats = "chats";
|
|
|
|
public static string Messages(Guid chatId) => $"messages/{chatId:D}";
|
|
|
|
public static string Encode(string scope, DateTimeOffset createdAt, Guid id) =>
|
|
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{scope}|{createdAt.UtcTicks}:{id:D}"));
|
|
|
|
// cursor == null — первая страница (успех, value == null). Любая ошибка формата или чужой scope — false.
|
|
public static bool TryDecode(string? cursor, string scope, out (DateTimeOffset CreatedAt, Guid Id)? value)
|
|
{
|
|
value = null;
|
|
if (cursor is null)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (cursor.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var decoded = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(Convert.FromBase64String(cursor));
|
|
var scoped = decoded.Split('|', 2);
|
|
if (scoped.Length != 2 || scoped[0] != scope)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var parts = scoped[1].Split(':', 2);
|
|
if (parts.Length != 2 ||
|
|
!long.TryParse(parts[0], out var ticks) ||
|
|
ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks ||
|
|
!Guid.TryParse(parts[1], out var id))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
value = (new DateTimeOffset(ticks, TimeSpan.Zero), id);
|
|
return true;
|
|
}
|
|
catch (Exception ex) when (ex is FormatException or ArgumentException or DecoderFallbackException)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|