Skip to content

Commit

Permalink
Merge pull request #1401 from TelegramBots/develop
Browse files Browse the repository at this point in the history
OnMessage/OnUpdate & other stuff
  • Loading branch information
wiz0u authored Jul 17, 2024
2 parents 91dc795 + 2dfa291 commit 437f088
Show file tree
Hide file tree
Showing 118 changed files with 395 additions and 685 deletions.
2 changes: 1 addition & 1 deletion .azure-pipelines/variables.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
variables:
- group: Integration Tests Variables
- name: versionPrefix
value: 21.6.2
value: 21.7.0
- name: versionSuffix
value: ''
- name: ciVersionSuffix
Expand Down
4 changes: 2 additions & 2 deletions src/EnumSerializer.Generator/EnumConverterGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ static void Execute(
}

//Seems not needed for now (maybe later when we support AOT)
//var optionsTemplate = Template.Parse(SourceGenerationHelper.JsonSerializerOptionsProviderTemplate);
//var optionsTemplate = Template.Parse(SourceGenerationHelper.JsonBotAPITemplate);
//var generatedOptionsProviderClass = SourceGenerationHelper.GenerateOptionsProviderClass(optionsTemplate, enumsToProcess);
//context.AddSource(
// hintName: "JsonSerializerOptionsProvider.g.cs",
// hintName: "JsonBotAPI.g.cs",
// sourceText: SourceText.From(generatedOptionsProviderClass, Encoding.UTF8)
//);
}
Expand Down
6 changes: 3 additions & 3 deletions src/EnumSerializer.Generator/SourceGenerationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ namespace EnumSerializer.Generator;

internal static class SourceGenerationHelper
{
internal const string JsonSerializerOptionsProviderTemplate =
internal const string JsonBotAPITemplate =
"""
using System.Collections.Generic;

namespace Telegram.Bot.Serialization;
namespace Telegram.Bot;

public static partial class JsonSerializerOptionsProvider
public static partial class JsonBotAPI
{
static partial void AddGeneratedConverters(IList<JsonConverter> converters)
{
Expand Down
3 changes: 0 additions & 3 deletions src/Telegram.Bot/Args/ApiRequestEventArgs.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using System.Net.Http;
using Telegram.Bot.Requests.Abstractions;

namespace Telegram.Bot.Args;

/// <summary>
Expand Down
2 changes: 0 additions & 2 deletions src/Telegram.Bot/Args/ApiResponseEventArgs.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Net.Http;

namespace Telegram.Bot.Args;

/// <summary>
Expand Down
13 changes: 0 additions & 13 deletions src/Telegram.Bot/AsyncEventHandler`T.cs

This file was deleted.

12 changes: 12 additions & 0 deletions src/Telegram.Bot/Delegates.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Threading;
using System.Threading.Tasks;

#pragma warning disable 1591

namespace Telegram.Bot;

public delegate ValueTask AsyncEventHandler<in TArgs>(ITelegramBotClient botClient, TArgs args, CancellationToken cancellationToken = default);
public delegate Task OnUpdateHandler(Update update);
public delegate Task OnMessageHandler(Message message, UpdateType type);
public delegate Task OnErrorHandler(Exception exception, Polling.HandleErrorSource source);

305 changes: 59 additions & 246 deletions src/Telegram.Bot/Extend.Types.cs

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions src/Telegram.Bot/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
#if NET6_0_OR_GREATER
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Text;
using System.Threading.Tasks;
#endif

namespace Telegram.Bot.Extensions
Expand All @@ -24,6 +24,8 @@ internal static T ThrowIfNull<T>(

namespace Microsoft.Extensions.DependencyInjection
{
using Telegram.Bot;

/// <summary>Helpers for WebApp service configuration</summary>
public static class TelegramBotConfigureExtensions
{
Expand All @@ -32,7 +34,7 @@ public static class TelegramBotConfigureExtensions
/// <param name="opt">Accessor to JsonSerializerOptions</param>
public static IServiceCollection ConfigureTelegramBot<TOptions>(this IServiceCollection services, Func<TOptions, JsonSerializerOptions> opt)
where TOptions : class
=> services.Configure<TOptions>(options => JsonSerializerOptionsProvider.Configure(opt(options)));
=> services.Configure<TOptions>(options => JsonBotAPI.Configure(opt(options)));

#if NET6_0_OR_GREATER
/// <summary>Configure ASP.NET MVC Json (de)serialization for Telegram.Bot types</summary>
Expand Down Expand Up @@ -60,7 +62,7 @@ public TelegramBotInputFormatter()

public sealed override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
var model = await JsonSerializer.DeserializeAsync(context.HttpContext.Request.Body, context.ModelType, JsonSerializerOptionsProvider.Options, context.HttpContext.RequestAborted);
var model = await JsonSerializer.DeserializeAsync(context.HttpContext.Request.Body, context.ModelType, JsonBotAPI.Options, context.HttpContext.RequestAborted);
return await InputFormatterResult.SuccessAsync(model);
}
}
Expand All @@ -78,7 +80,7 @@ public TelegramBotOutputFormatter()
public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var stream = context.HttpContext.Response.Body;
await JsonSerializer.SerializeAsync(stream, context.Object, JsonSerializerOptionsProvider.Options, context.HttpContext.RequestAborted);
await JsonSerializer.SerializeAsync(stream, context.Object, JsonBotAPI.Options, context.HttpContext.RequestAborted);
}
}
#pragma warning restore MA0004 // Use Task.ConfigureAwait
Expand Down
2 changes: 0 additions & 2 deletions src/Telegram.Bot/Extensions/FormatExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Telegram.Bot.Extensions;
Expand Down
1 change: 0 additions & 1 deletion src/Telegram.Bot/Extensions/HttpContentExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Net.Http;
using System.Runtime.CompilerServices;

namespace Telegram.Bot.Extensions;
Expand Down
5 changes: 1 addition & 4 deletions src/Telegram.Bot/Extensions/HttpResponseMessageExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using System.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using JsonSerializerOptionsProvider = Telegram.Bot.Serialization.JsonSerializerOptionsProvider;

namespace Telegram.Bot.Extensions;

Expand Down Expand Up @@ -55,7 +52,7 @@ internal static async Task<T> DeserializeContentAsync<T>(
deserializedObject = await JsonSerializer
.DeserializeAsync<T>(
utf8Json: contentStream,
options: JsonSerializerOptionsProvider.Options,
options: JsonBotAPI.Options,
cancellationToken: cancellationToken
).ConfigureAwait(false);
}
Expand Down
4 changes: 1 addition & 3 deletions src/Telegram.Bot/Extensions/StreamExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using JsonSerializerOptionsProvider = Telegram.Bot.Serialization.JsonSerializerOptionsProvider;

namespace Telegram.Bot.Extensions;

Expand All @@ -26,7 +24,7 @@ internal static class StreamExtensions
return await JsonSerializer
.DeserializeAsync<T>(
utf8Json: stream,
options: JsonSerializerOptionsProvider.Options,
options: JsonBotAPI.Options,
cancellationToken: cancellationToken
).ConfigureAwait(false);
}
Expand Down
1 change: 0 additions & 1 deletion src/Telegram.Bot/ITelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using JetBrains.Annotations;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Requests.Abstractions;

namespace Telegram.Bot;

Expand Down
28 changes: 28 additions & 0 deletions src/Telegram.Bot/JsonBotAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace Telegram.Bot;

/// <summary>Static class offering JsonSerializerOptions configured for Bot API serialization</summary>
public static class JsonBotAPI
{
/// <summary>JsonSerializerOptions configured for Bot API serialization</summary>
public static JsonSerializerOptions Options { get; }

static JsonBotAPI() => Configure(Options = new());

/// <summary>Configure JsonSerializerOptions for Bot API serialization</summary>
/// <param name="options">JsonSerializerOptions to configure</param>
public static void Configure(JsonSerializerOptions options)
{
options.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
options.UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip;
//options.AllowOutOfOrderMetadataProperties = true; // when System.Text.Json 9.0 is available, so we don't need custom PolymorphicJsonConverterFactory
options.Converters.Add(new PolymorphicJsonConverterFactory());
//options.Converters.Add(new BanTimeConverter());
//options.Converters.Add(new ChatIdConverter());
//options.Converters.Add(new InputFileConverter());
//options.Converters.Add(new UnixDateTimeConverter());
//AddGeneratedConverters(Options.Converters);
}

//static partial void AddGeneratedConverters(IList<JsonConverter> converters);
}
1 change: 0 additions & 1 deletion src/Telegram.Bot/Polling/Abstractions/ReceiverOptions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using JetBrains.Annotations;
using Telegram.Bot.Types.Enums;

// ReSharper disable once CheckNamespace
namespace Telegram.Bot.Polling;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,8 @@ async Task<bool> ReceiveUpdatesAsync()
{
try
{
_messageOffset = await _receiver._botClient.DropPendingUpdatesAsync(
cancellationToken: _token
).ConfigureAwait(false);
var updates = await _receiver._botClient.GetUpdatesAsync(-1, 1, 0, [], _token).ConfigureAwait(false);
_messageOffset = updates.Length == 0 ? 0 : updates[^1].Id + 1;
}
catch (OperationCanceledException)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,8 @@ async Task ReceiveUpdatesAsync()
{
try
{
_messageOffset = await _receiver._botClient.DropPendingUpdatesAsync(
cancellationToken: _token
).ConfigureAwait(false);
var updates = await _receiver._botClient.GetUpdatesAsync(-1, 1, 0, [], _token).ConfigureAwait(false);
_messageOffset = updates.Length == 0 ? 0 : updates[^1].Id + 1;
}
catch (OperationCanceledException)
{
Expand Down
5 changes: 2 additions & 3 deletions src/Telegram.Bot/Polling/DefaultUpdateReceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@ public async Task ReceiveAsync(IUpdateHandler updateHandler, CancellationToken c
{
try
{
messageOffset = await _botClient.DropPendingUpdatesAsync(
cancellationToken: cancellationToken
).ConfigureAwait(false);
var updates = await _botClient.GetUpdatesAsync(-1, 1, 0, [], cancellationToken).ConfigureAwait(false);
messageOffset = updates.Length == 0 ? 0 : updates[^1].Id + 1;
}
catch (OperationCanceledException)
{
Expand Down
35 changes: 0 additions & 35 deletions src/Telegram.Bot/Polling/TelegramBotClientExtensions.cs

This file was deleted.

4 changes: 1 addition & 3 deletions src/Telegram.Bot/Requests/Abstractions/IRequest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Net.Http;

// ReSharper disable once UnusedTypeParameter
// ReSharper disable once UnusedTypeParameter
namespace Telegram.Bot.Requests.Abstractions;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using System.Diagnostics.CodeAnalysis;
using Telegram.Bot.Requests.Abstractions;

// ReSharper disable once CheckNamespace
namespace Telegram.Bot.Requests;

Expand Down
5 changes: 2 additions & 3 deletions src/Telegram.Bot/Requests/FileRequestBase.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Globalization;
using System.Linq;
using System.Net.Http;
using Telegram.Bot.Extensions;

namespace Telegram.Bot.Requests;

/// <summary>
Expand Down Expand Up @@ -57,7 +56,7 @@ protected MultipartFormDataContent GenerateMultipartFormDataContent(params strin
var boundary = $"{Guid.NewGuid()}{DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture)}";
var multipartContent = new MultipartFormDataContent(boundary);

var stringContents = JsonSerializer.SerializeToElement(this, GetType(), JsonSerializerOptionsProvider.Options)
var stringContents = JsonSerializer.SerializeToElement(this, GetType(), JsonBotAPI.Options)
.EnumerateObject()
.Where(prop => exceptPropertyNames.Contains(prop.Name, StringComparer.InvariantCulture) is false)
.Select(prop => (name: prop.Name, content: new StringContent(prop.Value.ToString())));
Expand Down
4 changes: 1 addition & 3 deletions src/Telegram.Bot/Requests/ParameterlessRequest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Net.Http;

namespace Telegram.Bot.Requests;
namespace Telegram.Bot.Requests;

/// <summary>
/// Represents a request that doesn't require any parameters
Expand Down
5 changes: 1 addition & 4 deletions src/Telegram.Bot/Requests/RequestBase.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.Net.Http;
using System.Text;
using Telegram.Bot.Requests.Abstractions;
using JsonSerializerOptionsProvider = Telegram.Bot.Serialization.JsonSerializerOptionsProvider;

namespace Telegram.Bot.Requests;

Expand Down Expand Up @@ -42,7 +39,7 @@ protected RequestBase(string methodName, HttpMethod method) =>
/// <returns>Content of HTTP request</returns>
public virtual HttpContent? ToHttpContent() =>
new StringContent(
content: JsonSerializer.Serialize(this, GetType(), JsonSerializerOptionsProvider.Options),
content: JsonSerializer.Serialize(this, GetType(), JsonBotAPI.Options),
encoding: Encoding.UTF8,
mediaType: "application/json"
);
Expand Down
2 changes: 0 additions & 2 deletions src/Telegram.Bot/Serialization/InputFileConverter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.IO;

namespace Telegram.Bot.Serialization;

internal class InputFileConverter : JsonConverter<InputFile?>
Expand Down
23 changes: 4 additions & 19 deletions src/Telegram.Bot/Serialization/JsonSerializerOptionsProvider.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,13 @@
namespace Telegram.Bot.Serialization;

/// <summary>Static class offering JsonSerializerOptions configured for Telegram.Bot serialization</summary>
public static partial class JsonSerializerOptionsProvider
public static class JsonSerializerOptionsProvider
{
/// <summary>JsonSerializerOptions configured for Telegram.Bot serialization</summary>
public static JsonSerializerOptions Options { get; }

static JsonSerializerOptionsProvider() => Configure(Options = new JsonSerializerOptions());
public static JsonSerializerOptions Options => JsonBotAPI.Options;

/// <summary>Configure JsonSerializerOptions for Telegram.Bot serialization</summary>
/// <param name="options">JsonSerializerOptions to configure</param>
public static void Configure(JsonSerializerOptions options)
{
options.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
options.UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip;
//options.AllowOutOfOrderMetadataProperties = true; // when System.Text.Json 9.0 is available, so we don't need custom PolymorphicJsonConverterFactory
options.Converters.Add(new PolymorphicJsonConverterFactory());
//options.Converters.Add(new BanTimeConverter());
//options.Converters.Add(new ChatIdConverter());
//options.Converters.Add(new InputFileConverter());
//options.Converters.Add(new UnixDateTimeConverter());
//AddGeneratedConverters(Options.Converters);
}

//static partial void AddGeneratedConverters(IList<JsonConverter> converters);
[Obsolete("Use JsonBotAPI.Configure()")]
public static void Configure(JsonSerializerOptions options) => JsonBotAPI.Configure(options);
}
1 change: 0 additions & 1 deletion src/Telegram.Bot/Serialization/PolymorphicJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// The original implementation is taken from there
// https://github.com/dotnet/runtime/issues/72604#issuecomment-1932302266

using System.Collections.Generic;
using System.Reflection;

namespace Telegram.Bot.Serialization;
Expand Down
Loading

0 comments on commit 437f088

Please sign in to comment.