Skip to content

Commit

Permalink
Merge pull request #14 from LloydLion/update
Browse files Browse the repository at this point in the history
File work bug fix (v1.4.1)
  • Loading branch information
LloydLion authored Nov 5, 2022
2 parents b752b7b + fd0e80b commit e7c0daa
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 82 deletions.
89 changes: 9 additions & 80 deletions DidiFrame.Clients.DSharp/MessageConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ public static MessageSendModel ConvertDown(DiscordMessage message)

foreach (var file in message.Attachments)
{
files.Add(new MessageFile(file.FileName, new DiscordFileReader(file)));
files.Add(new MessageFile(file.FileName, async (target) =>
{
var http = new HttpClient();
var result = await http.GetAsync(file.Url);
await result.Content.CopyToAsync(target);
}));
}
}

Expand Down Expand Up @@ -101,7 +106,9 @@ public static DiscordMessageBuilder ConvertUp(MessageSendModel messageSendModel)
if (messageSendModel.Files is not null)
foreach (var file in messageSendModel.Files)
{
var stream = new MemoryStream(Encoding.Default.GetBytes(file.Reader.ReadToEnd()));
var stream = new MemoryStream();
file.CopyTo(stream).Wait();
stream.Position = 0;
builder.WithFile(file.FileName, stream);
}

Expand Down Expand Up @@ -147,83 +154,5 @@ public static DiscordMessageBuilder ConvertUp(MessageSendModel messageSendModel)

return builder;
}


private sealed class DiscordFileReader : TextReader
{
private HttpClient? httpClient;
private StreamReader? cachedReader;
private readonly DiscordAttachment attachment;


public DiscordFileReader(DiscordAttachment attachment)
{
this.httpClient = new HttpClient();
this.attachment = attachment;
}


public override void Close() => cachedReader?.Close();

public override int Peek() => WorkWithReader(s => s.Peek());

public override int Read() => WorkWithReader(s => s.Read());

public override int Read(char[] buffer, int index, int count) => WorkWithReader(s => s.Read(buffer, index, count));

public override int Read(Span<char> buffer)
{
InitReader();
if (cachedReader is null) throw new ImpossibleVariantException();
return cachedReader.Read(buffer);
}

public override Task<int> ReadAsync(char[] buffer, int index, int count) => WorkWithReader(s => s.ReadAsync(buffer, index, count));

public override ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => WorkWithReader(s => s.ReadAsync(buffer, cancellationToken));

public override int ReadBlock(char[] buffer, int index, int count) => WorkWithReader(s => s.ReadBlock(buffer, index, count));

public override int ReadBlock(Span<char> buffer)
{
InitReader();
if (cachedReader is null) throw new ImpossibleVariantException();
return cachedReader.ReadBlock(buffer);
}

public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) => WorkWithReader(s => s.ReadBlockAsync(buffer, index, count));

public override ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => WorkWithReader(s => s.ReadBlockAsync(buffer, cancellationToken));

public override string? ReadLine() => WorkWithReader(s => s.ReadLine());

public override Task<string?> ReadLineAsync() => WorkWithReader(s => s.ReadLineAsync());

public override string ReadToEnd() => WorkWithReader(s => s.ReadToEnd());

public override Task<string> ReadToEndAsync() => WorkWithReader(s => s.ReadToEndAsync());

[Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException")]
public override object InitializeLifetimeService() => WorkWithReader(s => s.InitializeLifetimeService());


private TOutput WorkWithReader<TOutput>(Func<StreamReader, TOutput> operatingFunction)
{
InitReader();
if (cachedReader is null) throw new ImpossibleVariantException();
return operatingFunction(cachedReader);
}

private void InitReader()
{
if (cachedReader is null)
{
if (httpClient is null) throw new ImpossibleVariantException();
cachedReader = new StreamReader(httpClient.GetStreamAsync(attachment.Url).Result);
httpClient.Dispose();
httpClient = null;
}
}
}
}
}
20 changes: 18 additions & 2 deletions DidiFrame/Entities/Message/MessageFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@
/// Model to attach files to messages
/// </summary>
/// <param name="FileName">Name of file for discord</param>
/// <param name="Reader">Stream reader, it can be no file</param>
public record MessageFile(string FileName, TextReader Reader);
/// <param name="CopyToDelegate">Delegate that copies data message data</param>
public record MessageFile(string FileName, CopyToDelegate CopyToDelegate)
{
/// <summary>
/// Asynchrony copies data to target stream
/// </summary>
/// <param name="targetStream">Target stream</param>
/// <returns>Wait task</returns>
public Task CopyTo(Stream targetStream) => CopyToDelegate(targetStream);
}


/// <summary>
/// Delegate that copies some data to target stream
/// </summary>
/// <param name="targetStream">Target stream</param>
/// <returns>Wait task</returns>
public delegate Task CopyToDelegate(Stream targetStream);
}
23 changes: 23 additions & 0 deletions TestBot/Systems/Test/CommandsHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using System.Diagnostics.CodeAnalysis;
using TestBot.Systems.Test.ClientExtensions.NewsChannels;
using TestBot.Systems.Test.ClientExtensions.ReactionExtension;
using DidiFrame.Utils.Collections;
using System.Text;
using System;

namespace TestBot.Systems.Test
{
Expand Down Expand Up @@ -126,6 +129,26 @@ public async Task<UserCommandResult> PostLastMessage(UserCommandContext ctx)
else return UserCommandResult.CreateWithMessage(UserCommandCode.InvalidInput, new("Enable to post message in non-news channel"));
}

[Command("senddown")]
public async Task<UserCommandResult> SendAndDownloadFile(UserCommandContext ctx)
{
using var fs = File.OpenRead("TextFile1.txt");
var buffer = new byte[fs.Length];
await fs.ReadAsync(buffer.AsMemory());

var message = await ctx.SendData.Channel.SendMessageAsync(new() { Files = new MessageFile("File1.txt", (target) => target.WriteAsync(buffer.AsMemory()).AsTask()).StoreSingle() });

var memory = new MemoryStream();
#nullable disable
await message.SendModel.Files.Single().CopyTo(memory);
#nullable restore

var str = Encoding.UTF8.GetString(memory.ToArray());
Console.WriteLine(str);

return UserCommandResult.CreateWithMessage(UserCommandCode.Sucssesful, new("Qwerty"));
}


private class Modal : IModalForm
{
Expand Down
3 changes: 3 additions & 0 deletions TestBot/TestBot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@
<None Update="settings\780833811566166037.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="TextFile1.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
5 changes: 5 additions & 0 deletions TestBot/TextFile1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

some
text
data
qwerty

0 comments on commit e7c0daa

Please sign in to comment.