AbstractISOBaseMediaFileDetailDetector.cs 1.4 KB

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