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

Revert "feat: Make all API cancellable" #650

Closed
wants to merge 1 commit into from
Closed
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
34 changes: 6 additions & 28 deletions Lagrange.Core/Common/Interface/Api/BotExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,18 @@ public static class BotExt
/// </summary>
/// <returns>return url and qrcode image in PNG format</returns>
public static Task<(string Url, byte[] QrCode)?> FetchQrCode(this BotContext bot)
=> bot.ContextCollection.Business.WtExchangeLogic.FetchQrCode(CancellationToken.None);

/// <summary>
/// Fetch the qrcode for QRCode Login
/// </summary>
/// <returns>return url and qrcode image in PNG format</returns>
public static Task<(string Url, byte[] QrCode)?> FetchQrCode(this BotContext bot, CancellationToken cancellationToken)
=> bot.ContextCollection.Business.WtExchangeLogic.FetchQrCode(cancellationToken);
=> bot.ContextCollection.Business.WtExchangeLogic.FetchQrCode();

/// <summary>
/// Use this method to login by QrCode, you should call <see cref="FetchQrCode"/> first
/// </summary>
public static Task LoginByQrCode(this BotContext bot)
=> bot.ContextCollection.Business.WtExchangeLogic.LoginByQrCode(CancellationToken.None);

/// <summary>
/// Use this method to login by QrCode, you should call <see cref="FetchQrCode"/> first
/// </summary>
public static Task LoginByQrCode(this BotContext bot, CancellationToken cancellationToken)
public static Task LoginByQrCode(this BotContext bot, CancellationToken cancellationToken = default)
=> bot.ContextCollection.Business.WtExchangeLogic.LoginByQrCode(cancellationToken);

/// <summary>
/// Use this method to login by password, EasyLogin may be preformed if there is sig in <see cref="BotKeystore"/>
/// </summary>
public static Task<bool> LoginByPassword(this BotContext bot)
=> bot.ContextCollection.Business.WtExchangeLogic.LoginByPassword(CancellationToken.None);

/// <summary>
/// Use this method to login by password, EasyLogin may be preformed if there is sig in <see cref="BotKeystore"/>
/// </summary>
public static Task<bool> LoginByPassword(this BotContext bot, CancellationToken cancellationToken)
public static Task<bool> LoginByPassword(this BotContext bot, CancellationToken cancellationToken = default)
=> bot.ContextCollection.Business.WtExchangeLogic.LoginByPassword(cancellationToken);

/// <summary>
Expand All @@ -49,11 +30,8 @@ public static Task<bool> LoginByPassword(this BotContext bot, CancellationToken
public static bool SubmitCaptcha(this BotContext bot, string ticket, string randStr)
=> bot.ContextCollection.Business.WtExchangeLogic.SubmitCaptcha(ticket, randStr);

public static Task<bool> SetNeedToConfirmSwitch(this BotContext bot, bool needToConfirm)
=> bot.ContextCollection.Business.OperationLogic.SetNeedToConfirmSwitch(needToConfirm, CancellationToken.None);

public static Task<bool> SetNeedToConfirmSwitch(this BotContext bot, bool needToConfirm, CancellationToken cancellationToken)
=> bot.ContextCollection.Business.OperationLogic.SetNeedToConfirmSwitch(needToConfirm, cancellationToken);
public static Task<bool> SetNeedToConfirmSwitch(this BotContext bot, bool needToConfirm)
=> bot.ContextCollection.Business.OperationLogic.SetNeedToConfirmSwitch(needToConfirm);

/// <summary>
/// Use this method to update keystore, so EasyLogin may be preformed next time by using this keystore
Expand All @@ -68,4 +46,4 @@ public static BotKeystore UpdateKeystore(this BotContext bot)
/// <param name="bot"></param>
public static BotDeviceInfo UpdateDeviceInfo(this BotContext bot)
=> bot.ContextCollection.Device;
}
}
217 changes: 39 additions & 178 deletions Lagrange.Core/Common/Interface/Api/GroupExt.cs

Large diffs are not rendered by default.

338 changes: 36 additions & 302 deletions Lagrange.Core/Common/Interface/Api/OperationExt.cs

Large diffs are not rendered by default.

47 changes: 13 additions & 34 deletions Lagrange.Core/Internal/Context/BusinessContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,16 +73,12 @@ private void RegisterLogics()
}
}

public async Task<bool> PushEvent(ProtocolEvent @event, CancellationToken cancellationToken)
public async Task<bool> PushEvent(ProtocolEvent @event)
{
try
{
var packets = Collection.Service.ResolvePacketByEvent(@event);
foreach (var packet in packets)
{
cancellationToken.ThrowIfCancellationRequested();
await Collection.Packet.PostPacket(packet);
}
foreach (var packet in packets) await Collection.Packet.PostPacket(packet);
}
catch
{
Expand All @@ -95,32 +91,25 @@ public async Task<bool> PushEvent(ProtocolEvent @event, CancellationToken cancel
/// <summary>
/// Send Event to the Server, goes through the given context
/// </summary>
public async Task<List<ProtocolEvent>> SendEvent(ProtocolEvent @event, CancellationToken cancellationToken)
public async Task<List<ProtocolEvent>> SendEvent(ProtocolEvent @event)
{
await HandleOutgoingEvent(@event, cancellationToken);
await HandleOutgoingEvent(@event);
var result = new List<ProtocolEvent>();

cancellationToken.ThrowIfCancellationRequested();


try
{
var packets = Collection.Service.ResolvePacketByEvent(@event);
foreach (var packet in packets)
{
var returnVal = await Collection.Packet.SendPacket(packet, cancellationToken);
var returnVal = await Collection.Packet.SendPacket(packet);
var resolved = Collection.Service.ResolveEventByPacket(returnVal);
foreach (var protocol in resolved)
{
await HandleIncomingEvent(protocol, cancellationToken);
await HandleIncomingEvent(protocol);
result.Add(protocol);
}
}
}
catch (TaskCanceledException)
{
// if task is cancelled, we should throw the exception
throw;
}
catch (Exception e)
{
Collection.Log.LogWarning(Tag, $"Error when processing the event: {@event}");
Expand All @@ -130,7 +119,7 @@ public async Task<List<ProtocolEvent>> SendEvent(ProtocolEvent @event, Cancellat
return result;
}

public async Task<bool> HandleIncomingEvent(ProtocolEvent @event, CancellationToken cancellationToken)
public async Task<bool> HandleIncomingEvent(ProtocolEvent @event)
{
_businessLogics.TryGetValue(typeof(ProtocolEvent), out var baseLogics);
_businessLogics.TryGetValue(@event.GetType(), out var normalLogics);
Expand All @@ -143,12 +132,7 @@ public async Task<bool> HandleIncomingEvent(ProtocolEvent @event, CancellationTo
{
try
{
await logic.Incoming(@event, cancellationToken);
}
catch (TaskCanceledException)
{
// if task is cancelled, we should throw the exception
throw;
await logic.Incoming(@event);
}
catch (Exception e)
{
Expand All @@ -161,7 +145,7 @@ public async Task<bool> HandleIncomingEvent(ProtocolEvent @event, CancellationTo
return true;
}

public async Task<bool> HandleOutgoingEvent(ProtocolEvent @event, CancellationToken cancellationToken)
public async Task<bool> HandleOutgoingEvent(ProtocolEvent @event)
{
_businessLogics.TryGetValue(typeof(ProtocolEvent), out var baseLogics);
_businessLogics.TryGetValue(@event.GetType(), out var normalLogics);
Expand All @@ -174,12 +158,7 @@ public async Task<bool> HandleOutgoingEvent(ProtocolEvent @event, CancellationTo
{
try
{
await logic.Outgoing(@event, cancellationToken);
}
catch (TaskCanceledException)
{
// if task is cancelled, we should throw the exception
throw;
await logic.Outgoing(@event);
}
catch (Exception e)
{
Expand All @@ -204,7 +183,7 @@ public async Task<bool> HandleServerPacket(SsoPacket packet)
var events = Collection.Service.ResolveEventByPacket(packet);
foreach (var @event in events)
{
var isSuccessful = await Collection.Business.HandleIncomingEvent(@event, CancellationToken.None);
var isSuccessful = await Collection.Business.HandleIncomingEvent(@event);
if (!isSuccessful) break;

success = true;
Expand All @@ -220,4 +199,4 @@ public async Task<bool> HandleServerPacket(SsoPacket packet)

return success;
}
}
}
34 changes: 17 additions & 17 deletions Lagrange.Core/Internal/Context/HighwayContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,16 @@ public HighwayContext(ContextCollection collection, BotKeystore keystore, BotApp
_concurrent = config.HighwayConcurrent;
}

public async Task UploadResources(MessageChain chain, CancellationToken cancellationToken = default)
public async Task UploadResources(MessageChain chain)
{
foreach (var entity in chain)
{
if (_uploaders.TryGetValue(entity.GetType(), out var uploader))
{
try
{
if (chain.IsGroup) await uploader.UploadGroup(Collection, chain, entity, cancellationToken);
else await uploader.UploadPrivate(Collection, chain, entity, cancellationToken);
if (chain.IsGroup) await uploader.UploadGroup(Collection, chain, entity);
else await uploader.UploadPrivate(Collection, chain, entity);
}
catch
{
Expand All @@ -76,7 +76,7 @@ public async Task UploadResources(MessageChain chain, CancellationToken cancella
}
}

public async Task ManualUploadEntity(IMessageEntity entity, CancellationToken cancellationToken = default)
public async Task ManualUploadEntity(IMessageEntity entity)
{
if (_uploaders.TryGetValue(entity.GetType(), out var uploader))
{
Expand All @@ -86,7 +86,7 @@ public async Task ManualUploadEntity(IMessageEntity entity, CancellationToken ca
string uid = Collection.Keystore.Uid ?? "";
var chain = new MessageChain(uin, uid, uid) { entity };

await uploader.UploadPrivate(Collection, chain, entity, cancellationToken);
await uploader.UploadPrivate(Collection, chain, entity);
}
catch
{
Expand All @@ -95,11 +95,11 @@ public async Task ManualUploadEntity(IMessageEntity entity, CancellationToken ca
}
}

public async Task<bool> UploadSrcByStreamAsync(int commonId, Stream data, byte[] ticket, byte[] md5, byte[]? extendInfo = null, CancellationToken cancellation = default)
public async Task<bool> UploadSrcByStreamAsync(int commonId, Stream data, byte[] ticket, byte[] md5, byte[]? extendInfo = null)
{
if (_uri == null)
{
var highwayUrlEvent = await Collection.Business.SendEvent(HighwayUrlEvent.Create(), cancellation);
var highwayUrlEvent = await Collection.Business.SendEvent(HighwayUrlEvent.Create());
var result = (HighwayUrlEvent)highwayUrlEvent[0];
_uri = result.HighwayUrls[1][0];
}
Expand All @@ -114,7 +114,7 @@ public async Task<bool> UploadSrcByStreamAsync(int commonId, Stream data, byte[]
while (offset < fileSize)
{
var buffer = new byte[Math.Min(_chunkSize, fileSize - offset)];
int payload = await data.ReadAsync(buffer.AsMemory(), cancellation);
int payload = await data.ReadAsync(buffer.AsMemory());
uint uin = Collection.Keystore.Uin;
uint sequence = Interlocked.Increment(ref _sequence);
var reqBody = new UpBlock(commonId, uin, sequence, (ulong)fileSize, (ulong)offset, ticket, md5, buffer, extendInfo);
Expand All @@ -123,7 +123,7 @@ public async Task<bool> UploadSrcByStreamAsync(int commonId, Stream data, byte[]

if (upBlocks.Count >= _concurrent || data.Position == data.Length)
{
var tasks = upBlocks.Select(x => SendUpBlockAsync(x, _uri, cancellation)).ToArray();
var tasks = upBlocks.Select(x => SendUpBlockAsync(x, _uri)).ToArray();
var results = await Task.WhenAll(tasks);
success &= results.All(x => x);

Expand All @@ -134,7 +134,7 @@ public async Task<bool> UploadSrcByStreamAsync(int commonId, Stream data, byte[]
return success;
}

private async Task<bool> SendUpBlockAsync(UpBlock upBlock, Uri server, CancellationToken cancellation = default)
private async Task<bool> SendUpBlockAsync(UpBlock upBlock, Uri server)
{
var head = new DataHighwayHead
{
Expand Down Expand Up @@ -171,15 +171,15 @@ private async Task<bool> SendUpBlockAsync(UpBlock upBlock, Uri server, Cancellat
};

bool isEnd = upBlock.Offset + (ulong)upBlock.Block.Length == upBlock.FileSize;
var payload = await SendPacketAsync(highwayHead, new BinaryPacket(upBlock.Block), server, end: isEnd, cancellation: cancellation);
var payload = await SendPacketAsync(highwayHead, new BinaryPacket(upBlock.Block), server, isEnd);
var (respHead, resp) = ParsePacket(payload);

Collection.Log.LogDebug(Tag, $"Highway Block Result: {respHead.ErrorCode} | {respHead.MsgSegHead?.RetCode} | {respHead.BytesRspExtendInfo?.Hex()} | {resp.ToArray().Hex()}");

return respHead.ErrorCode == 0;
}

private Task<BinaryPacket> SendPacketAsync(ReqDataHighwayHead head, BinaryPacket buffer, Uri server, bool end = true, CancellationToken cancellation = default)
private Task<BinaryPacket> SendPacketAsync(ReqDataHighwayHead head, BinaryPacket buffer, Uri server, bool end = true)
{
using var stream = new MemoryStream();
Serializer.Serialize(stream, head);
Expand All @@ -192,7 +192,7 @@ private Task<BinaryPacket> SendPacketAsync(ReqDataHighwayHead head, BinaryPacket
.WritePacket(buffer)
.WriteByte(0x29); // packet end

return SendDataAsync(writer.ToArray(), server, end, cancellation);
return SendDataAsync(writer.ToArray(), server, end);
}

private static (RespDataHighwayHead, BinaryPacket) ParsePacket(BinaryPacket packet)
Expand All @@ -210,7 +210,7 @@ private static (RespDataHighwayHead, BinaryPacket) ParsePacket(BinaryPacket pack
throw new InvalidOperationException("Invalid packet");
}

private async Task<BinaryPacket> SendDataAsync(byte[] packet, Uri server, bool end, CancellationToken cancellation)
private async Task<BinaryPacket> SendDataAsync(byte[] packet, Uri server, bool end)
{
var content = new ByteArrayContent(packet);
var request = new HttpRequestMessage(HttpMethod.Post, server)
Expand All @@ -221,8 +221,8 @@ private async Task<BinaryPacket> SendDataAsync(byte[] packet, Uri server, bool e
{ "Connection" , end ? "close" : "keep-alive" },
}
};
var response = await _client.SendAsync(request, cancellation);
var data = await response.Content.ReadAsByteArrayAsync(cancellation);
var response = await _client.SendAsync(request);
var data = await response.Content.ReadAsByteArrayAsync();
return new BinaryPacket(data);
}

Expand All @@ -242,4 +242,4 @@ public void Dispose()
{
_client.Dispose();
}
}
}
Loading