diff --git a/Configurations/XFileTypeDetectorConfiguration.cs b/Configurations/XFileTypeDetectorConfiguration.cs
new file mode 100644
index 0000000..7cd9865
--- /dev/null
+++ b/Configurations/XFileTypeDetectorConfiguration.cs
@@ -0,0 +1,18 @@
+namespace xCommons.Configurations
+{
+ ///
+ /// Configuration options for XFileTypeDetector ...
+ ///
+ public sealed class XFileTypeDetectorConfiguration
+ {
+ ///
+ /// When true, magic bytes are always read first ...
+ ///
+ public bool PreferMagicBytes { get; set; } = true;
+
+ ///
+ /// Number of bytes read from the stream header ...
+ ///
+ public int HeaderSize { get; set; } = 32;
+ }
+}
\ No newline at end of file
diff --git a/Constants/ConfigurationNodeNames.cs b/Constants/ConfigurationNodeNames.cs
index 6aaa330..de7eaa6 100644
--- a/Constants/ConfigurationNodeNames.cs
+++ b/Constants/ConfigurationNodeNames.cs
@@ -2,6 +2,7 @@ namespace xCommons.Constants {
public partial struct ConfigurationNodeNames {
public const string CERTIFICATES_NODE = "Certificates";
public const string SWAGGER_NODE = "SwaggerConfiguration";
+ public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration";
public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles";
}
}
\ No newline at end of file
diff --git a/Constants/XFileExtensions.cs b/Constants/XFileExtensions.cs
new file mode 100644
index 0000000..acd2d9e
--- /dev/null
+++ b/Constants/XFileExtensions.cs
@@ -0,0 +1,221 @@
+using xExceptions.Attributes;
+
+namespace xCommons.Constants
+{
+ ///
+ /// File Extensions Enumerable ...
+ ///
+ /// Document: 100–133
+ /// Archive: 200–202
+ /// Internal Supports: 300–302
+ /// Video: 400–405
+ /// Audio: 500–505
+ /// Image: 600–609
+ ///
+ public enum XFileExtensions
+ {
+ //
+ #region Document ...
+ [StringValue(".txt")]
+ TEXT = 100,
+
+ [StringValue(".pdf")]
+ PDF = 101,
+
+ [StringValue(".ppt")]
+ PPT = 102,
+
+ [StringValue(".pptx")]
+ PPTX = 103,
+
+ [StringValue(".odp")]
+ ODP = 104,
+
+ [StringValue(".pps")]
+ PPS = 105,
+
+ [StringValue(".ods")]
+ ODS = 106,
+
+ [StringValue(".xlr")]
+ XLR = 107,
+
+ [StringValue(".xls")]
+ XLS = 108,
+
+ [StringValue(".xlsx")]
+ XLSX = 109,
+
+ [StringValue(".xml")]
+ XML = 110,
+
+ [StringValue(".doc")]
+ DOC = 111,
+
+ [StringValue(".docx")]
+ DOCX = 112,
+
+ [StringValue(".odt")]
+ ODT = 113,
+
+ [StringValue(".rtf")]
+ RTF = 114,
+
+ [StringValue(".tex")]
+ TEX = 115,
+
+ [StringValue(".wpd")]
+ WPD = 116,
+
+ [StringValue(".md")]
+ MD = 117,
+
+ [StringValue(".cs")]
+ CSHARP = 118,
+
+ [StringValue(".py")]
+ PYTHON = 119,
+
+ [StringValue(".js")]
+ JAVASCRIPT = 120,
+
+ [StringValue(".ts")]
+ TYPESCRIPT = 121,
+
+ [StringValue(".java")]
+ JAVA = 122,
+
+ [StringValue(".go")]
+ GO = 123,
+
+ [StringValue(".rs")]
+ RUST = 124,
+
+ [StringValue(".rb")]
+ RUBY = 125,
+
+ [StringValue(".php")]
+ PHP = 126,
+
+ [StringValue(".csv")]
+ CSV = 127,
+
+ [StringValue(".json")]
+ JSON = 128,
+
+ [StringValue(".yml")]
+ YML = 129,
+
+ [StringValue(".yaml")]
+ YAML = 130,
+
+ [StringValue(".css")]
+ CSS = 131,
+
+ [StringValue(".htm")]
+ HTM = 132,
+
+ [StringValue(".html")]
+ HTML = 133,
+ #endregion
+
+ //
+ #region Archive ...
+ [StringValue(".zip")]
+ ZIP = 200,
+
+ [StringValue(".rar")]
+ RAR = 201,
+
+ [StringValue(".7z")]
+ SEVENZIP = 202,
+ #endregion
+
+ //
+ #region Internal Supports ...
+ [StringValue(".ttf")]
+ TTF = 300,
+
+ [StringValue(".sdw")]
+ SAHER_DASHBOARD_WIDGET = 301,
+
+ [StringValue(".sdwmanifest")]
+ SAHER_DASHBOARD_WIDGET_MANIFEST = 302,
+ #endregion
+
+ //
+ #region Video ...
+ [StringValue(".mp4")]
+ MP4 = 400,
+
+ [StringValue(".avi")]
+ AVI = 401,
+
+ [StringValue(".mpg")]
+ MPG = 402,
+
+ [StringValue(".mpeg")]
+ MPEG = 403,
+
+ [StringValue(".wmv")]
+ WMV = 404,
+
+ [StringValue(".webm")]
+ WEBM = 405,
+ #endregion
+
+ //
+ #region Audio ...
+ [StringValue(".mp3")]
+ MP3 = 500,
+
+ [StringValue(".ogg")]
+ OGG = 501,
+
+ [StringValue(".wav")]
+ WAV = 502,
+
+ [StringValue(".wma")]
+ WMA = 503,
+
+ [StringValue(".aac")]
+ AAC = 504,
+
+ [StringValue(".m4a")]
+ M4A = 505,
+ #endregion
+
+ //
+ #region Image ...
+ [StringValue(".png")]
+ PNG = 600,
+
+ [StringValue(".jpeg")]
+ JPEG = 601,
+
+ [StringValue(".jpg")]
+ JPG = 602,
+
+ [StringValue(".ico")]
+ ICON = 603,
+
+ [StringValue(".gif")]
+ GIF = 604,
+
+ [StringValue(".bmp")]
+ BITMAP = 605,
+
+ [StringValue(".webp")]
+ WEBP = 606,
+
+ [StringValue(".tif")]
+ TIF = 607,
+
+ [StringValue(".tiff")]
+ TIFF = 608,
+
+ [StringValue(".svg")]
+ SVG = 609,
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/Constants/XFileMimeTypes.cs b/Constants/XFileMimeTypes.cs
new file mode 100644
index 0000000..b231918
--- /dev/null
+++ b/Constants/XFileMimeTypes.cs
@@ -0,0 +1,221 @@
+using xExceptions.Attributes;
+
+namespace xCommons.Constants
+{
+ ///
+ /// MIME Types mapped to XFileExtensions ...
+ ///
+ /// Document: 100–133
+ /// Archive: 200–202
+ /// Internal Supports: 300–302
+ /// Video: 400–405
+ /// Audio: 500–505
+ /// Image: 600–609
+ ///
+ public enum XFileMimeTypes
+ {
+ //
+ #region Document ...
+ [StringValue("text/plain")]
+ TEXT = 100,
+
+ [StringValue("application/pdf")]
+ PDF = 101,
+
+ [StringValue("application/vnd.ms-powerpoint")]
+ PPT = 102,
+
+ [StringValue("application/vnd.openxmlformats-officedocument.presentationml.presentation")]
+ PPTX = 103,
+
+ [StringValue("application/vnd.oasis.opendocument.presentation")]
+ ODP = 104,
+
+ [StringValue("application/vnd.ms-powerpoint")]
+ PPS = 105,
+
+ [StringValue("application/vnd.oasis.opendocument.spreadsheet")]
+ ODS = 106,
+
+ [StringValue("application/vnd.ms-excel")]
+ XLR = 107,
+
+ [StringValue("application/vnd.ms-excel")]
+ XLS = 108,
+
+ [StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")]
+ XLSX = 109,
+
+ [StringValue("text/xml")]
+ XML = 110,
+
+ [StringValue("application/msword")]
+ DOC = 111,
+
+ [StringValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document")]
+ DOCX = 112,
+
+ [StringValue("application/vnd.oasis.opendocument.text")]
+ ODT = 113,
+
+ [StringValue("application/rtf")]
+ RTF = 114,
+
+ [StringValue("application/x-tex")]
+ TEX = 115,
+
+ [StringValue("application/vnd.wordperfect")]
+ WPD = 116,
+
+ [StringValue("text/markdown")]
+ MD = 117,
+
+ [StringValue("text/x-csharp")]
+ CSHARP = 118,
+
+ [StringValue("text/x-python")]
+ PYTHON = 119,
+
+ [StringValue("application/javascript")]
+ JAVASCRIPT = 120,
+
+ [StringValue("application/typescript")]
+ TYPESCRIPT = 121,
+
+ [StringValue("text/x-java")]
+ JAVA = 122,
+
+ [StringValue("text/x-go")]
+ GO = 123,
+
+ [StringValue("text/x-rust")]
+ RUST = 124,
+
+ [StringValue("text/x-ruby")]
+ RUBY = 125,
+
+ [StringValue("text/x-php")]
+ PHP = 126,
+
+ [StringValue("text/csv")]
+ CSV = 127,
+
+ [StringValue("application/json")]
+ JSON = 128,
+
+ [StringValue("application/x-yaml")]
+ YML = 129,
+
+ [StringValue("application/x-yaml")]
+ YAML = 130,
+
+ [StringValue("text/css")]
+ CSS = 131,
+
+ [StringValue("text/html")]
+ HTM = 132,
+
+ [StringValue("text/html")]
+ HTML = 133,
+ #endregion
+
+ //
+ #region Archive ...
+ [StringValue("application/zip")]
+ ZIP = 200,
+
+ [StringValue("application/x-rar-compressed")]
+ RAR = 201,
+
+ [StringValue("application/x-7z-compressed")]
+ SEVENZIP = 202,
+ #endregion
+
+ //
+ #region Internal Supports ...
+ [StringValue("font/ttf")]
+ TTF = 300,
+
+ [StringValue("application/x-sdw")]
+ SAHER_DASHBOARD_WIDGET = 301,
+
+ [StringValue("application/x-sdwmanifest")]
+ SAHER_DASHBOARD_WIDGET_MANIFEST = 302,
+ #endregion
+
+ //
+ #region Video ...
+ [StringValue("video/mp4")]
+ MP4 = 400,
+
+ [StringValue("video/x-msvideo")]
+ AVI = 401,
+
+ [StringValue("video/mpeg")]
+ MPG = 402,
+
+ [StringValue("video/mpeg")]
+ MPEG = 403,
+
+ [StringValue("video/x-ms-wmv")]
+ WMV = 404,
+
+ [StringValue("video/webm")]
+ WEBM = 405,
+ #endregion
+
+ //
+ #region Audio ...
+ [StringValue("audio/mpeg")]
+ MP3 = 500,
+
+ [StringValue("audio/ogg")]
+ OGG = 501,
+
+ [StringValue("audio/wav")]
+ WAV = 502,
+
+ [StringValue("audio/x-ms-wma")]
+ WMA = 503,
+
+ [StringValue("audio/aac")]
+ AAC = 504,
+
+ [StringValue("audio/mp4")]
+ M4A = 505,
+ #endregion
+
+ //
+ #region Image ...
+ [StringValue("image/png")]
+ PNG = 600,
+
+ [StringValue("image/jpeg")]
+ JPEG = 601,
+
+ [StringValue("image/jpeg")]
+ JPG = 602,
+
+ [StringValue("image/x-icon")]
+ ICON = 603,
+
+ [StringValue("image/gif")]
+ GIF = 604,
+
+ [StringValue("image/bmp")]
+ BITMAP = 605,
+
+ [StringValue("image/webp")]
+ WEBP = 606,
+
+ [StringValue("image/tiff")]
+ TIF = 607,
+
+ [StringValue("image/tiff")]
+ TIFF = 608,
+
+ [StringValue("image/svg+xml")]
+ SVG = 609,
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/Constants/XFileType.cs b/Constants/XFileType.cs
index db33494..cc1e72d 100644
--- a/Constants/XFileType.cs
+++ b/Constants/XFileType.cs
@@ -1,5 +1,9 @@
-namespace xCommons.Constants {
- public enum XFileType {
+using xExceptions.Attributes;
+
+namespace xCommons.Constants
+{
+ public enum XFileType
+ {
Image,
ProfileImasge,
CoverImage,
@@ -7,4 +11,25 @@ namespace xCommons.Constants {
Video,
Document
}
+
+ public enum XFileCategory
+ {
+ [StringValue("Document")]
+ Document = 100,
+
+ [StringValue("Archive")]
+ Archive = 200,
+
+ [StringValue("Internal")]
+ Internal = 300,
+
+ [StringValue("Video")]
+ Video = 400,
+
+ [StringValue("Audio")]
+ Audio = 500,
+
+ [StringValue("Image")]
+ Image = 600
+ }
}
\ No newline at end of file
diff --git a/Constants/XFileTypeDetectionSource.cs b/Constants/XFileTypeDetectionSource.cs
new file mode 100644
index 0000000..cd5ea23
--- /dev/null
+++ b/Constants/XFileTypeDetectionSource.cs
@@ -0,0 +1,25 @@
+using xExceptions.Attributes;
+
+namespace xCommons.Constants
+{
+ ///
+ /// File Type Detection Source ...
+ ///
+ public enum XFileTypeDetectionSource
+ {
+ [StringValue("None")]
+ None = 0,
+
+ [StringValue("MagicBytes")]
+ MagicBytes = 1,
+
+ [StringValue("Extension")]
+ Extension = 2,
+
+ [StringValue("ProvidedMime")]
+ ProvidedMime = 3,
+
+ [StringValue("Fallback")]
+ Fallback = 4
+ }
+}
\ No newline at end of file
diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs
index 642bacf..dc8700f 100644
--- a/DI/XDIHelperExtension.cs
+++ b/DI/XDIHelperExtension.cs
@@ -1,12 +1,27 @@
using xCommons.Providers;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Configuration;
+using xCommons.Extensions;
-public static partial class XDIHelperExtension {
+public static partial class XDIHelperExtension
+{
///
/// Register XCommons Module Services
///
///
- public static void AddXCommons (this IServiceCollection services) {
- services.AddSingleton ();
+ public static void AddXCommons(this IServiceCollection services)
+ {
+ services.AddSingleton();
}
+
+ public static void AddXCommons(
+ this IServiceCollection services,
+ IConfiguration configuration
+ )
+ {
+ //
+ services.AddXCommons();
+ services.AddXFileTypeDetector(configuration);
+ }
+
}
\ No newline at end of file
diff --git a/Extensions/DIExtensions.cs b/Extensions/DIExtensions.cs
index 836ed9b..abf41b0 100644
--- a/Extensions/DIExtensions.cs
+++ b/Extensions/DIExtensions.cs
@@ -12,12 +12,13 @@ using Swashbuckle.AspNetCore.SwaggerUI;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using xCommons.Interfaces;
+using xCommons.Providers;
namespace xCommons.Extensions
{
public static partial class DIExtensions
{
-
///
/// Inject Specific Registered Service from IServiceCollection
///
@@ -43,6 +44,41 @@ namespace xCommons.Extensions
services.AddSingleton(appConfiguration);
}
+ ///
+ /// Retrieve and Register File Type Detector Configuration ...
+ ///
+ ///
+ ///
+ public static void AddXFileTypeDetectorConfiguration(
+ this IServiceCollection source,
+ IConfiguration configuration
+ )
+ {
+ //
+ var config = configuration.GetXFileTypeDetectorConfiguration();
+ source.AddXFileTypeDetectorConfiguration(config);
+ }
+
+ ///
+ /// Register File Type Detector Configuration ...
+ ///
+ ///
+ ///
+ public static void AddXFileTypeDetectorConfiguration(
+ this IServiceCollection source,
+ XFileTypeDetectorConfiguration configuration
+ )
+ {
+ //
+ if (configuration.IsNull())
+ {
+ configuration = new();
+ }
+
+ //
+ source.AddSingleton(configuration);
+ }
+
///
/// Search Assemblies, Extract XML Comments and
/// Integrate them inside swagger gen documents ...
@@ -440,6 +476,16 @@ namespace xCommons.Extensions
});
}
+ public static void AddXFileTypeDetector(
+ this IServiceCollection source,
+ IConfiguration configuration
+ )
+ {
+ //
+ source.AddXFileTypeDetectorConfiguration(configuration);
+ source.AddSingleton();
+ }
+
///
/// Use X Registered Cross Origin Resource Sharings
///
diff --git a/Extensions/IConfigurationExtensions.cs b/Extensions/IConfigurationExtensions.cs
index f7a1cfa..8631fc1 100644
--- a/Extensions/IConfigurationExtensions.cs
+++ b/Extensions/IConfigurationExtensions.cs
@@ -50,7 +50,29 @@ namespace xCommons.Extensions
.GetSection(ConfigurationNodeNames.SWAGGER_NODE);
return xSwaggerConfigSection.Get();
}
-
+
+ ///
+ /// Retrieve File Type Detector Configuration ...
+ ///
+ ///
+ ///
+ public static XFileTypeDetectorConfiguration GetXFileTypeDetectorConfiguration(this IConfiguration source)
+ {
+ //
+ var section = source
+ .GetSection(ConfigurationNodeNames.FILE_TYPE_DETECTOR_NODE);
+
+ //
+ var result = section.Get();
+ if (result.IsNull())
+ {
+ result = new();
+ }
+
+ //
+ return result;
+ }
+
///
/// Converts a ConfigurationSection to object Representation ...
///
@@ -174,6 +196,6 @@ namespace xCommons.Extensions
//
return result;
- }
+ }
}
}
\ No newline at end of file
diff --git a/Helpers/XFileHelper.cs b/Helpers/XFileHelper.cs
new file mode 100644
index 0000000..743a859
--- /dev/null
+++ b/Helpers/XFileHelper.cs
@@ -0,0 +1,420 @@
+using System;
+using System.Linq;
+using xCommons.Models;
+using System.Reflection;
+using xCommons.Constants;
+using xCommons.Extensions;
+using xExceptions.Attributes;
+using System.Collections.Generic;
+
+namespace xCommons.Helpers
+{
+ ///
+ /// File Helper ...
+ ///
+ public static class XFileHelper
+ {
+ ///
+ /// Cache Data ...
+ ///
+ private static readonly Lazy> _cache =
+ new(Build, isThreadSafe: true);
+
+ ///
+ /// Retrieve List ...
+ ///
+ ///
+ public static IReadOnlyList GetAll() => _cache.Value;
+
+ ///
+ /// Normalize File Extension ...
+ ///
+ ///
+ ///
+ public static string NormalizeExtension(string extension)
+ {
+ //
+ var result = extension;
+
+ //
+ if (result.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ result = result.Trim();
+ if (result.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ if (result == ".")
+ {
+ //
+ result = string.Empty;
+ return result;
+ }
+
+ //
+ result = result.StartsWith(".")
+ ? result.ToLowerInvariant()
+ : "." + result.ToLowerInvariant();
+
+ //
+ return result;
+ }
+
+ ///
+ /// Check a File Extension is Supported or not ...
+ ///
+ ///
+ ///
+ public static bool IsSupported(string extension)
+ {
+ //
+ var info = GetByExtension(extension);
+ var result = !info.IsNull();
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect File Info based On Extension ...
+ ///
+ ///
+ ///
+ public static XFileTypeInfo GetByExtension(string extension)
+ {
+ //
+ XFileTypeInfo result = null;
+
+ //
+ // Validate ...
+ if (extension.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ var normalized = NormalizeExtension(extension);
+
+ //
+ // Detect Item ...
+ result = GetAll()
+ .FirstOrDefault(x =>
+ x.Extension.Equals(
+ normalized,
+ StringComparison.OrdinalIgnoreCase));
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect File Info based on Mime Type ...
+ ///
+ ///
+ ///
+ public static XFileTypeInfo GetByMimeType(string mimeType)
+ {
+ //
+ XFileTypeInfo result = null;
+
+ //
+ // Validate ...
+ if (mimeType.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ result = GetAll()
+ .FirstOrDefault(x =>
+ x.MimeType.Equals(
+ mimeType.Trim(),
+ StringComparison.OrdinalIgnoreCase));
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect File Info based on Enum Member Name ...
+ ///
+ ///
+ ///
+ public static XFileTypeInfo GetByName(string name)
+ {
+ //
+ XFileTypeInfo result = null;
+
+ //
+ // Validate ...
+ if (name.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ result = GetAll()
+ .FirstOrDefault(x =>
+ x.Name.Equals(
+ name.Trim(),
+ StringComparison.OrdinalIgnoreCase));
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect File Info based on Enum Member Value ...
+ ///
+ ///
+ ///
+ public static XFileTypeInfo GetByValue(int value)
+ {
+ //
+ var result = GetAll()
+ .FirstOrDefault(x => x.Value == value);
+
+ //
+ return result;
+ }
+
+ ///
+ /// Try Get File Info By Extension ...
+ ///
+ ///
+ ///
+ ///
+ public static bool TryGetByExtension(
+ string extension,
+ out XFileTypeInfo result
+ )
+ {
+ result = GetByExtension(extension);
+ return result != null;
+ }
+
+ ///
+ /// Try Get File Info By Mime Type ...
+ ///
+ ///
+ ///
+ ///
+ public static bool TryGetByMimeType(
+ string mimeType,
+ out XFileTypeInfo result
+ )
+ {
+ result = GetByMimeType(mimeType);
+ return result != null;
+ }
+
+ ///
+ /// Get Mime Type based on Extension ...
+ ///
+ ///
+ ///
+ public static string GetMimeType(string extension)
+ {
+ //
+ var result = string.Empty;
+ var info = GetByExtension(extension);
+ if (!info.IsNull())
+ {
+ result = info.MimeType;
+ }
+
+ //
+ return result;
+
+ }
+
+ ///
+ /// Get Extension based on Mime Type ...
+ ///
+ ///
+ ///
+ public static string GetExtension(string mimeType)
+ {
+ //
+ var result = string.Empty;
+ var info = GetByMimeType(mimeType);
+ if (!info.IsNull())
+ {
+ result = info.Extension;
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Get File Category based on Value ...
+ ///
+ ///
+ ///
+ public static XFileCategory? GetCategory(int value)
+ {
+ //
+ if (value >= 100 && value < 200) return XFileCategory.Document;
+ if (value >= 200 && value < 300) return XFileCategory.Archive;
+ if (value >= 300 && value < 400) return XFileCategory.Internal;
+ if (value >= 400 && value < 500) return XFileCategory.Video;
+ if (value >= 500 && value < 600) return XFileCategory.Audio;
+ if (value >= 600 && value < 700) return XFileCategory.Image;
+
+ //
+ return null;
+ }
+
+ ///
+ /// Get File Category based on Extension ...
+ ///
+ ///
+ ///
+ public static XFileCategory? GetCategory(string extension)
+ {
+ //
+ var info = GetByExtension(extension);
+ var result = !info.IsNull()
+ ? GetCategory(info.Value)
+ : null;
+
+ //
+ return result;
+ }
+
+ ///
+ /// Get all Specified Category File Type Info ...
+ ///
+ ///
+ ///
+ public static IReadOnlyList GetByCategory(XFileCategory category)
+ {
+ //
+ var min = (int)category;
+ var max = min + 100;
+
+ //
+ var result = GetAll()
+ .Where(x => x.Value >= min && x.Value < max)
+ .ToList()
+ .AsReadOnly();
+
+ //
+ return result;
+ }
+
+ ///
+ /// Get All Supported Extensions ...
+ ///
+ ///
+ public static IReadOnlyList GetExtensions()
+ {
+ //
+ var result = GetAll()
+ .Select(x => x.Extension)
+ .ToList()
+ .AsReadOnly();
+
+ //
+ return result;
+ }
+
+ ///
+ /// Get All Supported Mime Types ...
+ ///
+ ///
+ public static IReadOnlyList GetMimeTypes()
+ {
+ //
+ var result = GetAll()
+ .Select(x => x.MimeType)
+ .Where(m => !string.IsNullOrWhiteSpace(m))
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList()
+ .AsReadOnly();
+
+ //
+ return result;
+ }
+
+ //
+ #region Private ...
+ ///
+ /// Build List ...
+ ///
+ ///
+ private static IReadOnlyList Build()
+ {
+ //
+ var extensions = ReadEnum();
+ var mimeTypes = ReadEnum();
+
+ //
+ var list = new List(extensions.Count);
+ foreach (var ext in extensions.Values.OrderBy(e => e.Value))
+ {
+ //
+ mimeTypes.TryGetValue(ext.Value, out var mime);
+ list.Add(new XFileTypeInfo
+ {
+ Name = ext.Name,
+ Value = ext.Value,
+ Extension = ext.StringValue,
+ MimeType = mime.StringValue ?? string.Empty
+ });
+ }
+
+ //
+ var result = list.AsReadOnly();
+ return result;
+ }
+
+ ///
+ /// Read Enum ...
+ ///
+ ///
+ ///
+ private static Dictionary ReadEnum()
+ where TEnum : struct, Enum
+ {
+ //
+ var map = new Dictionary();
+ foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static))
+ {
+ //
+ var attr = field.GetCustomAttribute();
+ if (attr == null) continue;
+ var value = Convert.ToInt32(field.GetValue(null));
+
+ //
+ map[value] = new EnumEntry
+ {
+ Value = value,
+ Name = field.Name,
+ StringValue = attr.StringValue
+ };
+ }
+
+ //
+ return map;
+ }
+
+ ///
+ /// Enum Entries for Read ...
+ ///
+ private struct EnumEntry
+ {
+ public int Value { get; set; }
+ public string Name { get; set; }
+ public string StringValue { get; set; }
+ }
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/Interfaces/IXFileTypeDetector.cs b/Interfaces/IXFileTypeDetector.cs
new file mode 100644
index 0000000..162954f
--- /dev/null
+++ b/Interfaces/IXFileTypeDetector.cs
@@ -0,0 +1,58 @@
+using System.IO;
+using xCommons.Models;
+using System.Threading;
+using xCommons.Constants;
+using System.Threading.Tasks;
+
+namespace xCommons.Interfaces
+{
+ public interface IXFileTypeDetector
+ {
+ ///
+ /// Detect MIME Type based on File Name ...
+ ///
+ ///
+ ///
+ string DetectFromExtension(string fileName);
+
+ ///
+ /// Detect XFileExtensions based on File Name ...
+ ///
+ ///
+ ///
+ XFileExtensions? DetectExtension(string fileName);
+
+ ///
+ /// Detect Type based on File's Magic Byte ...
+ ///
+ ///
+ ///
+ ///
+ Task DetectFromMagicBytesAsync(
+ Stream stream,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Complexity Detect Type ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task DetectAsync(
+ string fileName,
+ string providedMimeType,
+ Stream stream,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Check a File Extension is Known or not ...
+ ///
+ ///
+ ///
+ bool IsKnownExtension(string fileName);
+ }
+}
\ No newline at end of file
diff --git a/Models/XFileTypeDetectionResult.cs b/Models/XFileTypeDetectionResult.cs
new file mode 100644
index 0000000..9cab278
--- /dev/null
+++ b/Models/XFileTypeDetectionResult.cs
@@ -0,0 +1,22 @@
+using xCommons.Constants;
+
+namespace xCommons.Models
+{
+ public class XFileTypeDetectionResult
+ {
+ ///
+ /// File Mime Type ...
+ ///
+ public string MimeType { get; set; }
+
+ ///
+ /// File Extension ...
+ ///
+ public string Extension { get; set; }
+
+ ///
+ /// Type Detection Source ...
+ ///
+ public XFileTypeDetectionSource Source { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/Models/XFileTypeInfo.cs b/Models/XFileTypeInfo.cs
new file mode 100644
index 0000000..c8cc17c
--- /dev/null
+++ b/Models/XFileTypeInfo.cs
@@ -0,0 +1,36 @@
+namespace xCommons.Models
+{
+ public class XFileTypeInfo
+ {
+ ///
+ /// Enum Value ...
+ ///
+ public int Value { get; set; }
+
+ ///
+ /// Enum Item Name as String ...
+ ///
+ public string Name { get; set; } = string.Empty;
+
+ ///
+ /// Extension as String ...
+ ///
+ public string Extension { get; set; } = string.Empty;
+
+ ///
+ /// Mime Type as String ...
+ ///
+ public string MimeType { get; set; } = string.Empty;
+
+ ///
+ /// Override To String ...
+ ///
+ ///
+ public override string ToString()
+ {
+ //
+ var result = $"{Name} ({Extension}) -> {MimeType} [{Value}]";
+ return result;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Providers/XFileTypeDetector.cs b/Providers/XFileTypeDetector.cs
new file mode 100644
index 0000000..62eabdf
--- /dev/null
+++ b/Providers/XFileTypeDetector.cs
@@ -0,0 +1,289 @@
+using System;
+using System.IO;
+using xCommons.Models;
+using xCommons.Helpers;
+using System.Threading;
+using xCommons.Constants;
+using xCommons.Interfaces;
+using xCommons.Extensions;
+using System.Threading.Tasks;
+using xCommons.Configurations;
+using System.Collections.Generic;
+
+namespace xCommons.Providers
+{
+ public class XFileTypeDetector : IXFileTypeDetector
+ {
+ private readonly XFileTypeDetectorConfiguration configuration;
+
+ private readonly Dictionary MagicSignatures =
+ new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["image/png"] = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A },
+ ["image/jpeg"] = new byte[] { 0xFF, 0xD8, 0xFF },
+ ["image/gif"] = new byte[] { 0x47, 0x49, 0x46, 0x38 },
+ ["image/bmp"] = new byte[] { 0x42, 0x4D },
+ ["image/x-icon"] = new byte[] { 0x00, 0x00, 0x01, 0x00 },
+ ["application/pdf"] = new byte[] { 0x25, 0x50, 0x44, 0x46 },
+ ["application/zip"] = new byte[] { 0x50, 0x4B, 0x03, 0x04 },
+ ["application/x-rar-compressed"] = new byte[] { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07 },
+ ["application/x-7z-compressed"] = new byte[] { 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C },
+ ["audio/mpeg"] = new byte[] { 0xFF, 0xFB },
+ ["audio/ogg"] = new byte[] { 0x4F, 0x67, 0x67, 0x53 },
+ ["font/ttf"] = new byte[] { 0x00, 0x01, 0x00, 0x00 }
+ };
+
+ public XFileTypeDetector(
+ XFileTypeDetectorConfiguration configuration
+ )
+ {
+ this.configuration = configuration;
+ }
+
+ ///
+ /// Detect Type based on File Name ...
+ ///
+ ///
+ ///
+ public string DetectFromExtension(string fileName)
+ {
+ //
+ var result = string.Empty;
+
+ //
+ // Validate ...
+ if (fileName.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ var extension = Path.GetExtension(fileName);
+ if (extension.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ result = XFileHelper.GetMimeType(extension);
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect XFileExtensions based on File Name ...
+ ///
+ ///
+ ///
+ public XFileExtensions? DetectExtension(string fileName)
+ {
+ //
+ XFileExtensions? result = null;
+ if (fileName.IsNullOrEmpty())
+ {
+ return result;
+ }
+
+ //
+ var extension = Path.GetExtension(fileName);
+ var info = XFileHelper.GetByExtension(extension);
+ if (info.IsNull())
+ {
+ return result;
+ }
+
+ //
+ result = (XFileExtensions)info.Value;
+
+ //
+ return result;
+ }
+
+ ///
+ /// Check a File Extension is Known or not ...
+ ///
+ ///
+ ///
+ public bool IsKnownExtension(string fileName)
+ {
+ //
+ var result = !fileName.IsNullOrEmpty();
+ if (!result)
+ {
+ return result;
+ }
+
+ //
+ var extension = Path.GetExtension(fileName);
+ result = XFileHelper.IsSupported(extension);
+
+ //
+ return result;
+ }
+
+ ///
+ /// Detect Type based on File's Magic Byte ...
+ ///
+ ///
+ ///
+ ///
+ public async Task DetectFromMagicBytesAsync(
+ Stream stream,
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ var result = string.Empty;
+
+ //
+ // Validate ...
+ if (stream == null || !stream.CanRead)
+ {
+ return result;
+ }
+
+ //
+ var originalPosition = stream.CanSeek ? stream.Position : 0L;
+ try
+ {
+ //
+ var header = new byte[configuration.HeaderSize];
+ var read = await ReadHeaderAsync(stream, header, cancellationToken);
+ if (read < 2)
+ {
+ return result;
+ }
+
+ //
+ foreach (var signature in MagicSignatures)
+ {
+ //
+ if (MatchesSignature(header, read, signature.Value))
+ {
+ //
+ result = signature.Key;
+ return result;
+ }
+ }
+
+ //
+ return result;
+ }
+ finally
+ {
+ //
+ if (stream.CanSeek)
+ {
+ stream.Position = originalPosition;
+ }
+ }
+ }
+
+ ///
+ /// Complexity Detect Type ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task DetectAsync(
+ string fileName,
+ string providedMimeType,
+ Stream stream,
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ var result = new XFileTypeDetectionResult
+ {
+ Source = XFileTypeDetectionSource.None
+ };
+
+ //
+ if (configuration.PreferMagicBytes)
+ {
+ //
+ var magicMime = await DetectFromMagicBytesAsync(stream, cancellationToken);
+ if (!magicMime.IsNullOrEmpty())
+ {
+ //
+ result.MimeType = magicMime;
+ result.Extension = XFileHelper.GetExtension(magicMime);
+ result.Source = XFileTypeDetectionSource.MagicBytes;
+
+ //
+ return result;
+ }
+ }
+
+ //
+ var extensionMime = DetectFromExtension(fileName);
+ if (!extensionMime.IsNullOrEmpty())
+ {
+ //
+ result.MimeType = extensionMime;
+ result.Extension = Path.GetExtension(fileName)?.ToLowerInvariant();
+ result.Source = XFileTypeDetectionSource.Extension;
+
+ //
+ return result;
+ }
+
+ //
+ if (!string.IsNullOrWhiteSpace(providedMimeType))
+ {
+ //
+ var info = XFileHelper.GetByMimeType(providedMimeType);
+ if (info != null)
+ {
+ //
+ result.MimeType = info.MimeType;
+ result.Extension = info.Extension;
+ result.Source = XFileTypeDetectionSource.ProvidedMime;
+ }
+ }
+
+ //
+ return result;
+ }
+
+ //
+ #region Private ...
+ private static async Task ReadHeaderAsync(
+ Stream stream, byte[] buffer,
+ CancellationToken ct = default
+ )
+ {
+ //
+ var totalRead = 0;
+ while (totalRead < buffer.Length)
+ {
+ //
+ var read = await stream.ReadAsync(
+ buffer, totalRead, buffer.Length - totalRead, ct);
+
+ if (read == 0) break;
+ totalRead += read;
+ }
+
+ //
+ return totalRead;
+ }
+
+ private static bool MatchesSignature(byte[] header, int length, byte[] signature)
+ {
+ //
+ if (length < signature.Length) return false;
+ for (var i = 0; i < signature.Length; i++)
+ {
+ if (header[i] != signature[i]) return false;
+ }
+
+ //
+ return true;
+ }
+ #endregion
+ }
+}
\ No newline at end of file