| 1 |
using System.Globalization; |
| 2 |
using System.IO; |
| 3 |
using System.Linq; |
| 4 |
using System.Threading; |
| 5 |
using System.Threading.Tasks; |
| 6 |
using GodotTools.IdeMessaging.Utils; |
| 7 |
|
| 8 |
namespace GodotTools.IdeMessaging.CLI |
| 9 |
{ |
| 10 |
public class ForwarderMessageHandler : IMessageHandler |
| 11 |
{ |
| 12 |
private readonly StreamWriter outputWriter; |
| 13 |
private readonly SemaphoreSlim outputWriteSem = new SemaphoreSlim(1); |
| 14 |
|
| 15 |
public ForwarderMessageHandler(StreamWriter outputWriter) |
| 16 |
{ |
| 17 |
this.outputWriter = outputWriter; |
| 18 |
} |
| 19 |
|
| 20 |
public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger) |
| 21 |
{ |
| 22 |
await WriteRequestToOutput(id, content); |
| 23 |
return new MessageContent(MessageStatus.RequestNotSupported, "null"); |
| 24 |
} |
| 25 |
|
| 26 |
private async Task WriteRequestToOutput(string id, MessageContent content) |
| 27 |
{ |
| 28 |
using (await outputWriteSem.UseAsync()) |
| 29 |
{ |
| 30 |
await outputWriter.WriteLineAsync("======= Request ======="); |
| 31 |
await outputWriter.WriteLineAsync(id); |
| 32 |
await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString(CultureInfo.InvariantCulture)); |
| 33 |
await outputWriter.WriteLineAsync(content.Body); |
| 34 |
await outputWriter.WriteLineAsync("======================="); |
| 35 |
await outputWriter.FlushAsync(); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
public async Task WriteResponseToOutput(string id, MessageContent content) |
| 40 |
{ |
| 41 |
using (await outputWriteSem.UseAsync()) |
| 42 |
{ |
| 43 |
await outputWriter.WriteLineAsync("======= Response ======="); |
| 44 |
await outputWriter.WriteLineAsync(id); |
| 45 |
await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString(CultureInfo.InvariantCulture)); |
| 46 |
await outputWriter.WriteLineAsync(content.Body); |
| 47 |
await outputWriter.WriteLineAsync("========================"); |
| 48 |
await outputWriter.FlushAsync(); |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
public async Task WriteLineToOutput(string eventName) |
| 53 |
{ |
| 54 |
using (await outputWriteSem.UseAsync()) |
| 55 |
await outputWriter.WriteLineAsync($"======= {eventName} ======="); |
| 56 |
} |
| 57 |
} |
| 58 |
} |