AbstractISOBaseMediaFileDetailDetector.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System.Reflection;
  2. using System.Text;
  3. using Masuit.Tools.Mime;
  4. namespace Masuit.Tools.Files.FileDetector;
  5. public abstract class AbstractISOBaseMediaFileDetailDetector : IDetector
  6. {
  7. protected abstract IEnumerable<string> NextSignature { get; }
  8. public abstract string Extension { get; }
  9. public virtual string Precondition => null;
  10. public virtual string MimeType => new MimeMapper().GetMimeFromExtension("." + Extension);
  11. public virtual List<FormatCategory> FormatCategories => GetType().GetCustomAttributes<FormatCategoryAttribute>().Select(a => a.Category).ToList();
  12. public virtual bool Detect(Stream stream)
  13. {
  14. var reader = new BinaryReader(stream, Encoding.UTF8, true);
  15. _ = reader.ReadInt32();
  16. if (reader.ReadByte() == 0x66 && reader.ReadByte() == 0x74 && reader.ReadByte() == 0x79 && reader.ReadByte() == 0x70)
  17. {
  18. foreach (var ns in NextSignature)
  19. {
  20. stream.Position = 8;
  21. var readed = Encoding.GetEncoding("ascii").GetString(reader.ReadBytes(ns.Length), 0, ns.Length);
  22. stream.Position = 0;
  23. if (ns == readed)
  24. {
  25. return true;
  26. }
  27. }
  28. }
  29. return false;
  30. }
  31. }