MobileDocumentSource.cs 2.7 KB

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