CommunicationService.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Text.Json;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using SkiaSharp;
  8. namespace QuestPDF.Previewer;
  9. class CommunicationService
  10. {
  11. public static CommunicationService Instance { get; } = new ();
  12. public event Action<ICollection<PreviewPage>>? OnDocumentRefreshed;
  13. private WebApplication? Application { get; set; }
  14. private readonly JsonSerializerOptions JsonSerializerOptions = new()
  15. {
  16. PropertyNameCaseInsensitive = true
  17. };
  18. private CommunicationService()
  19. {
  20. }
  21. public Task Start(int port)
  22. {
  23. var builder = WebApplication.CreateBuilder();
  24. builder.Services.AddLogging(x => x.ClearProviders());
  25. builder.WebHost.UseKestrel(options => options.Limits.MaxRequestBodySize = null);
  26. Application = builder.Build();
  27. Application.MapGet("ping", HandlePing);
  28. Application.MapGet("version", HandleVersion);
  29. Application.MapPost("update/preview", HandleUpdatePreview);
  30. return Application.RunAsync($"http://localhost:{port}/");
  31. }
  32. public async Task Stop()
  33. {
  34. await Application.StopAsync();
  35. await Application.DisposeAsync();
  36. }
  37. private async Task<IResult> HandlePing()
  38. {
  39. return OnDocumentRefreshed == null
  40. ? Results.StatusCode(StatusCodes.Status503ServiceUnavailable)
  41. : Results.Ok();
  42. }
  43. private async Task<IResult> HandleVersion()
  44. {
  45. return Results.Json(GetType().Assembly.GetName().Version);
  46. }
  47. private async Task<IResult> HandleUpdatePreview(HttpRequest request)
  48. {
  49. var command = JsonSerializer.Deserialize<DocumentSnapshot>(request.Form["command"], JsonSerializerOptions);
  50. var pages = command
  51. .Pages
  52. .Select(page =>
  53. {
  54. using var stream = request.Form.Files[page.Id].OpenReadStream();
  55. var picture = SKPicture.Deserialize(stream);
  56. return new PreviewPage(picture, page.Width, page.Height);
  57. })
  58. .ToList();
  59. Task.Run(() => OnDocumentRefreshed(pages));
  60. return Results.Ok();
  61. }
  62. }