CommunicationService.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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<DocumentSnapshot>? 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 documentSnapshot = JsonSerializer.Deserialize<DocumentSnapshot>(request.Form["command"], JsonSerializerOptions);
  50. foreach (var pageSnapshot in documentSnapshot.Pages)
  51. {
  52. using var stream = request.Form.Files[pageSnapshot.Id].OpenReadStream();
  53. pageSnapshot.Picture = SKPicture.Deserialize(stream);
  54. }
  55. Task.Run(() => OnDocumentRefreshed(documentSnapshot));
  56. return Results.Ok();
  57. }
  58. }