Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UsersLongPoolUpdatesHandler #1587

Merged
merged 2 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions VkNet/Model/LongPollHistoryResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace VkNet.Model;
/// Обновления в личных сообщениях пользователя.
/// </summary>
[Serializable]
public class LongPollHistoryResponse
public class LongPollHistoryResponse<TMessage>
{
/// <summary>
/// Обновления в личных сообщениях пользователя.
Expand All @@ -25,6 +25,7 @@ public class LongPollHistoryResponse
/// История.
/// </summary>
[JsonProperty("history")]

// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public List<ReadOnlyCollection<long>> History { get; set; }

Expand All @@ -37,7 +38,7 @@ public class LongPollHistoryResponse
/// Колекция сообщений.
/// </summary>
[JsonProperty("messages")]
public VkCollection<Message> Messages { get; set; }
public VkCollection<TMessage> Messages { get; set; }

/// <summary>
/// Колекция профилей.
Expand Down Expand Up @@ -65,4 +66,10 @@ public class LongPollHistoryResponse
/// </summary>
[JsonProperty("more")]
public bool More { get; set; }
}

/// <inheritdoc />
[Serializable]
public class LongPollHistoryResponse : LongPollHistoryResponse<Message>
{
}
2 changes: 1 addition & 1 deletion VkNet/Utils/BotsLongPool/BotsLongPoolHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static class BotsLongPoolHelpers
/// <returns>
/// Возвращает список обновлений группы
/// </returns>
public static List<GroupUpdateEvent> GetGroupUpdateEvents(List<JObject> jObjectUpdates)
public static List<GroupUpdateEvent> GetGroupUpdateEvents(IEnumerable<JObject> jObjectUpdates)
{
var updates = new List<GroupUpdateEvent>();

Expand Down
4 changes: 2 additions & 2 deletions VkNet/Utils/BotsLongPool/BotsLongPoolUpdatesHandlerParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
namespace VkNet.Utils.BotsLongPool;

/// <summary>
/// Параметры для конструктора BotsLongPoolUpdatesProvider
/// Параметры для конструктора BotsLongPoolUpdatesHandler
/// </summary>
[UsedImplicitly]
public class BotsLongPoolUpdatesHandlerParams
Expand Down Expand Up @@ -58,7 +58,7 @@ public BotsLongPoolUpdatesHandlerParams(IVkApi api, ulong groupId)
public Action<BotsLongPoolOnUpdatesEvent>? OnUpdates { get; set; } = null;

/// <summary>
/// Функция, в которую будет отправляться ts при каждом его обновлении.
/// Функция, в которую будет отправляться TS при каждом его обновлении.
/// </summary>
public Action<ulong>? OnTsChange { get; set; } = null;

Expand Down
17 changes: 17 additions & 0 deletions VkNet/Utils/UsersLongPool/IUsersLongPoolUpdatesHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#nullable enable
using System.Threading;
using System.Threading.Tasks;

namespace VkNet.Utils.UsersLongPool;

/// <summary>
/// Обработчик лонгпула пользовательских сообщений
/// </summary>
public interface IUsersLongPoolUpdatesHandler
{
/// <summary>
/// Запуск отслеживания событий
/// </summary>
/// <param name="token">Токен отмены операции</param>
Task RunAsync(CancellationToken token = default);
}
26 changes: 26 additions & 0 deletions VkNet/Utils/UsersLongPool/UserMessageEvent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#nullable enable
using Newtonsoft.Json.Linq;
using VkNet.Model;

namespace VkNet.Utils.UsersLongPool;

/// <summary>
/// Обёртка для Message, в которой кроме самого сообщения есть и ошибки при парсинге.
/// </summary>
public class UserMessageEvent
{
/// <summary>
/// Сообщение
/// </summary>
public Message? Message = null;

/// <summary>
/// Ошибка парсинга сообщения
/// </summary>
public System.Exception? Exception = null;

/// <summary>
/// Сообщение в JObject
/// </summary>
public JObject RawMessage;
}
48 changes: 48 additions & 0 deletions VkNet/Utils/UsersLongPool/UsersLongPoolHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#nullable enable
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using VkNet.Model;

namespace VkNet.Utils.UsersLongPool;

/// <summary>
/// Методы для обработки событий лонгпула у сообществ.
/// </summary>
public static class UsersLongPoolHelpers
{
/// <summary>
/// Метод для получения сообщений из массива JObject, который не бросает исключений, но вместе с сообщениями возвращает ошибки при десериализации, если таковые имеются.
/// </summary>
/// <param name="jObjectMessages">Этот массив получается из метода api.Messages.GetLongPollHistory&lt;LongPollHistoryResponse&lt;JObject&gt;&gt;().Messages</param>
/// <returns>
/// Возвращает список сообщений пользователя
/// </returns>
public static List<UserMessageEvent> GetUserMessageEvents(IEnumerable<JObject> jObjectMessages)
{
var userMessageEvents = new List<UserMessageEvent>();

foreach (var jObjectMessage in jObjectMessages)
{
try
{
var message = jObjectMessage.ToObject<Message>();

userMessageEvents.Add(new()
{
Message = message,
RawMessage = jObjectMessage
});
}
catch (System.Exception ex)
{
userMessageEvents.Add(new()
{
Exception = ex,
RawMessage = jObjectMessage
});
}
}

return userMessageEvents;
}
}
22 changes: 22 additions & 0 deletions VkNet/Utils/UsersLongPool/UsersLongPoolOnUpdatesEvent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#nullable enable
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using VkNet.Model;

namespace VkNet.Utils.UsersLongPool;

/// <summary>
/// Обёртка для UsersLongPoolUpdatesHandlerParams.OnUpdates, в которой содержится вся информация о текущем массиве событий лонгпула для пользователя.
/// </summary>
public class UsersLongPoolOnUpdatesEvent
{
/// <summary>
/// Обновление в событиях пользователя.
/// </summary>
public LongPollHistoryResponse<JObject> Response;

/// <summary>
/// Обработанные сообщения из Response
/// </summary>
public List<UserMessageEvent> Messages;
}
Loading
Loading