ErrorHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using PicView.Core.FileHandling;
  2. using PicView.Core.ImageDecoding;
  3. namespace PicView.Core.Navigation;
  4. public static class ErrorHelper
  5. {
  6. /// <summary>
  7. /// Represents a structure containing a loadable file type and its associated data.
  8. /// </summary>
  9. /// <param name="type">The type of the loadable file.</param>
  10. /// <param name="data">The data associated with the loadable file.</param>
  11. public readonly struct FileTypeStruct(LoadAbleFileType type, string data)
  12. {
  13. /// <summary>
  14. /// Gets the type of the loadable file.
  15. /// </summary>
  16. public LoadAbleFileType Type => type;
  17. /// <summary>
  18. /// Gets the data associated with the loadable file.
  19. /// </summary>
  20. public string Data => data;
  21. }
  22. /// <summary>
  23. /// Specifies the different types of loadable files.
  24. /// </summary>
  25. public enum LoadAbleFileType
  26. {
  27. /// <summary>
  28. /// Represents a regular file.
  29. /// </summary>
  30. File,
  31. /// <summary>
  32. /// Represents a directory.
  33. /// </summary>
  34. Directory,
  35. /// <summary>
  36. /// Represents a web URL.
  37. /// </summary>
  38. Web,
  39. /// <summary>
  40. /// Represents a Base64 encoded string.
  41. /// </summary>
  42. Base64,
  43. /// <summary>
  44. /// Represents a zip archive.
  45. /// </summary>
  46. Zip
  47. }
  48. /// <summary>
  49. /// Checks if the provided string is a loadable file type and returns its type and associated data.
  50. /// </summary>
  51. /// <param name="s">The string to check.</param>
  52. /// <returns>
  53. /// A <see cref="FileTypeStruct"/> containing the type and data of the loadable file if the string is loadable, otherwise null.
  54. /// </returns>
  55. public static FileTypeStruct? CheckIfLoadableString(string s)
  56. {
  57. if (s.StartsWith('"') && s.EndsWith('"'))
  58. {
  59. s = s[1..^1];
  60. }
  61. if (s.StartsWith("file:///"))
  62. {
  63. s = s.Replace("file:///", "");
  64. s = s.Replace("%20", " ");
  65. }
  66. if (File.Exists(s))
  67. {
  68. var type = s.IsArchive() ? LoadAbleFileType.Zip : LoadAbleFileType.File;
  69. return new FileTypeStruct(type, s);
  70. }
  71. if (Directory.Exists(s))
  72. {
  73. return new FileTypeStruct(LoadAbleFileType.Directory, s);
  74. }
  75. if (!string.IsNullOrWhiteSpace(s.GetURL()))
  76. {
  77. return new FileTypeStruct(LoadAbleFileType.Web, s);
  78. }
  79. var base64String = Base64Helper.IsBase64String(s);
  80. if (!string.IsNullOrEmpty(base64String))
  81. {
  82. return new FileTypeStruct(LoadAbleFileType.Base64, base64String);
  83. }
  84. return null;
  85. }
  86. }