MobileDocumentSource.cs 2.8 KB

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