Skip to content

Commit

Permalink
Merge pull request #711 from TelegramBots/develop
Browse files Browse the repository at this point in the history
v14.4.0
  • Loading branch information
Poulad authored May 16, 2018
2 parents 90d8213 + 9fa41b2 commit d851b27
Show file tree
Hide file tree
Showing 51 changed files with 849 additions and 481 deletions.
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added
### Changed

- `MakeRequestAsync` throws `ApiRequestException` with `ErrorCode = HttpStatusCode.Unauthorized` and `Message = apiResponse.Description` ("Unauthorized"), to be consistent with Telegram Bot API
- `TelegramBotClient` ctor does not check API token format: Telegram Bot API does not provide token format specification
- `TestApiAsync` return `false` when `ApiRequestException.ErrorCode == 401` (API Token is modified or recalled)
- Stop catching user exceptions from event handlers

### Fixed

- `EditMessageTextAsync` pass `ParseMode` to request

### Removed

## [14.3.0] - 2018-05-05

### Added

- Implicit cast of `IEnumerable<InlineKeyboardButton>[]` to `InlineKeyboardMarkup`
Expand Down
37 changes: 0 additions & 37 deletions src/Telegram.Bot/Converters/PhotoSizeConverter.cs

This file was deleted.

10 changes: 5 additions & 5 deletions src/Telegram.Bot/Helpers/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Linq;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Serialization;

namespace Telegram.Bot.Helpers
{
Expand All @@ -12,11 +11,14 @@ namespace Telegram.Bot.Helpers
/// </summary>
public static class Extensions
{
[Obsolete]
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

/// <summary>
/// Convert a long into a DateTime
/// </summary>
[Obsolete("This method will be removed in v15 " +
"due to v14 using UnixDateTimeConverter from Newtonsoft.Json")]
public static DateTime FromUnixTime(this long unixTime)
=> UnixEpoch.AddSeconds(unixTime);

Expand All @@ -25,6 +27,8 @@ public static DateTime FromUnixTime(this long unixTime)
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="OverflowException"></exception>
[Obsolete("This method will be removed in v15 " +
"due to v14 using UnixDateTimeConverter from Newtonsoft.Json")]
public static long ToUnixTime(this DateTime dateTime)
{
if (dateTime == DateTime.MinValue)
Expand Down Expand Up @@ -63,9 +67,5 @@ internal static void AddStreamContent(

multipartContent.Add(mediaPartContent, name, fileName);
}

[Obsolete]
internal static string ToSnakeCased(this string value)
=> new SnakeCaseNamingStrategy().GetPropertyName(value, false);
}
}
3 changes: 2 additions & 1 deletion src/Telegram.Bot/Telegram.Bot.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard1.1;net45</TargetFrameworks>
<VersionPrefix>14.3.0</VersionPrefix>
<VersionPrefix>14.4.0</VersionPrefix>
<VersionSuffix>alpha</VersionSuffix>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
Expand Down
61 changes: 29 additions & 32 deletions src/Telegram.Bot/TelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand All @@ -26,6 +25,8 @@ namespace Telegram.Bot
/// </summary>
public class TelegramBotClient : ITelegramBotClient
{
private static readonly Update[] EmptyUpdates = { };

private const string BaseUrl = "https://api.telegram.org/bot";

private const string BaseFileUrl = "https://api.telegram.org/file/bot";
Expand All @@ -34,8 +35,6 @@ public class TelegramBotClient : ITelegramBotClient

private readonly string _token;

private bool _invalidToken;

private readonly HttpClient _httpClient;

#region Config Properties
Expand Down Expand Up @@ -157,9 +156,6 @@ protected virtual void OnUpdateReceived(UpdateEventArgs e)
/// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception>
public TelegramBotClient(string token, HttpClient httpClient = null)
{
if (!Regex.IsMatch(token, @"^\d*:[\w\d-_]{35}$"))
throw new ArgumentException("Invalid token format", nameof(token));

_token = token;
_baseRequestUrl = $"{BaseUrl}{_token}/";
_httpClient = httpClient ?? new HttpClient();
Expand All @@ -173,9 +169,6 @@ public TelegramBotClient(string token, HttpClient httpClient = null)
/// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception>
public TelegramBotClient(string token, IWebProxy webProxy)
{
if (!Regex.IsMatch(token, @"^\d*:[\w\d-_]{35}$"))
throw new ArgumentException("Invalid token format", nameof(token));

var httpClientHander = new HttpClientHandler
{
Proxy = webProxy,
Expand All @@ -194,9 +187,6 @@ public async Task<TResponse> MakeRequestAsync<TResponse>(
IRequest<TResponse> request,
CancellationToken cancellationToken = default)
{
if (_invalidToken)
throw new ApiRequestException("Invalid token", 401);

string url = _baseRequestUrl + request.MethodName;

var httpRequest = new HttpRequestMessage(request.Method, url)
Expand Down Expand Up @@ -241,8 +231,6 @@ public async Task<TResponse> MakeRequestAsync<TResponse>(
case HttpStatusCode.OK:
break;
case HttpStatusCode.Unauthorized:
_invalidToken = true;
throw new ApiRequestException("Invalid token", 401);
case HttpStatusCode.BadRequest when !string.IsNullOrWhiteSpace(responseJson):
case HttpStatusCode.Forbidden when !string.IsNullOrWhiteSpace(responseJson):
case HttpStatusCode.Conflict when !string.IsNullOrWhiteSpace(responseJson):
Expand Down Expand Up @@ -278,7 +266,8 @@ public async Task<bool> TestApiAsync(CancellationToken cancellationToken = defau
await GetMeAsync(cancellationToken).ConfigureAwait(false);
return true;
}
catch (HttpRequestException e) when (e.Message.EndsWith("404 (Not Found)."))
catch (ApiRequestException e)
when (e.ErrorCode == 401)
{
return false;
}
Expand All @@ -293,9 +282,6 @@ public async Task<bool> TestApiAsync(CancellationToken cancellationToken = defau
public void StartReceiving(UpdateType[] allowedUpdates = null,
CancellationToken cancellationToken = default)
{
if (_invalidToken)
throw new ApiRequestException("Invalid token", 401);

_receivingCancellationTokenSource = new CancellationTokenSource();

cancellationToken.Register(() => _receivingCancellationTokenSource.Cancel());
Expand All @@ -304,28 +290,24 @@ public void StartReceiving(UpdateType[] allowedUpdates = null,
}

#pragma warning disable AsyncFixer03 // Avoid fire & forget async void methods
private async void ReceiveAsync(UpdateType[] allowedUpdates,
private async void ReceiveAsync(
UpdateType[] allowedUpdates,
CancellationToken cancellationToken = default)
{
IsReceiving = true;

while (!cancellationToken.IsCancellationRequested)
{
var timeout = Convert.ToInt32(Timeout.TotalSeconds);
var updates = EmptyUpdates;

try
{
var updates =
await
GetUpdatesAsync(MessageOffset, timeout: timeout, allowedUpdates: allowedUpdates,
cancellationToken: cancellationToken)
.ConfigureAwait(false);

foreach (var update in updates)
{
MessageOffset = update.Id + 1;
OnUpdateReceived(new UpdateEventArgs(update));
}
updates = await GetUpdatesAsync(
MessageOffset,
timeout: timeout,
allowedUpdates: allowedUpdates,
cancellationToken: cancellationToken
).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Expand All @@ -338,6 +320,20 @@ private async void ReceiveAsync(UpdateType[] allowedUpdates,
{
OnReceiveGeneralError?.Invoke(this, generalException);
}

try
{
foreach (var update in updates)
{
OnUpdateReceived(new UpdateEventArgs(update));
MessageOffset = update.Id + 1;
}
}
catch
{
IsReceiving = false;
throw;
}
}

IsReceiving = false;
Expand Down Expand Up @@ -928,7 +924,8 @@ public Task EditMessageTextAsync(
MakeRequestAsync(new EditInlineMessageTextRequest(inlineMessageId, text)
{
DisableWebPagePreview = disableWebPagePreview,
ReplyMarkup = replyMarkup
ReplyMarkup = replyMarkup,
ParseMode = parseMode
}, cancellationToken);

/// <inheritdoc />
Expand Down
2 changes: 0 additions & 2 deletions src/Telegram.Bot/Types/PhotoSize.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Converters;

namespace Telegram.Bot.Types
{
Expand All @@ -9,7 +8,6 @@ namespace Telegram.Bot.Types
/// </summary>
/// <remarks>A missing thumbnail for a file (or sticker) is presented as an empty object.</remarks>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
[JsonConverter(typeof(PhotoSizeConverter))]
public class PhotoSize : FileBase
{
/// <summary>
Expand Down
Loading

0 comments on commit d851b27

Please sign in to comment.