MobileDocumentSource.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Avalonia.Controls;
  2. using InABox.Avalonia.Dialogs;
  3. using InABox.Avalonia.Platform;
  4. namespace InABox.Avalonia
  5. {
  6. public abstract class MobileDocumentSource
  7. {
  8. public abstract Task<MobileDocument> From(TopLevel window);
  9. }
  10. public abstract class MobileDocumentSource<TOptions> : MobileDocumentSource
  11. where TOptions : class, IMobileDocumentOptions, new()
  12. {
  13. public TOptions Options { get; set; }
  14. protected MobileDocumentSource(TOptions options)
  15. {
  16. Options = options;
  17. }
  18. protected abstract Task<bool> IsEnabled();
  19. // protected async Task<bool> IsEnabled<TPermission>()
  20. // where TPermission : Permissions.BasePermission, new()
  21. // {
  22. // var status = await Permissions.CheckStatusAsync<TPermission>();
  23. // if (status != PermissionStatus.Granted && status != PermissionStatus.Restricted)
  24. // status = await Permissions.RequestAsync<TPermission>();
  25. // return status == PermissionStatus.Granted;
  26. // }
  27. protected abstract Task<ImageFile?> Capture(TopLevel window);
  28. public override async Task<MobileDocument> From(TopLevel window)
  29. {
  30. var result = new MobileDocument();
  31. if (await IsEnabled())
  32. {
  33. try
  34. {
  35. var file = await Capture(window);
  36. if(file is not null)
  37. {
  38. if(file.Data is null)
  39. {
  40. result.FileName = file.FileName;
  41. var bytes = await File.ReadAllBytesAsync(file.FileName);
  42. result.Data = bytes;
  43. }
  44. else
  45. {
  46. result.FileName = Path.GetFileName(file.FileName);
  47. result.Data = file.Data;
  48. //file.OriginalFilename ?? file.Path);
  49. //await using (var stream = await file.OpenReadAsync())
  50. //{
  51. // BinaryReader br = new BinaryReader(file.Stream);
  52. // result.Data = br.ReadBytes((int)file.Stream.Length);
  53. //}
  54. }
  55. }
  56. ApplyOptions(result);
  57. }
  58. // catch (FeatureNotSupportedException fnsEx)
  59. // {
  60. // MobileLogging.Log(fnsEx, "Capture(FNS)");
  61. // MobileDialog.ShowMessage("This operation is not Supported on this Device!");
  62. // }
  63. // catch (PermissionException pEx)
  64. // {
  65. // MobileLogging.Log(pEx, "Capture(PERM)");
  66. // MobileDialog.ShowMessage("This operation is not Permitted on this Device!");
  67. // }
  68. catch (Exception ex)
  69. {
  70. MobileLogging.Log(ex, "Capture(ERR)");
  71. await MessageDialog.ShowMessage($"Oops! Something went wrong!\n{ex.Message}");
  72. }
  73. }
  74. return result;
  75. }
  76. protected abstract void ApplyOptions(MobileDocument document);
  77. }
  78. }