MobileDocumentSource.cs 2.8 KB

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