73 lines
2.9 KiB
C#
73 lines
2.9 KiB
C#
using System.IO.Compression;
|
|
using System.Text;
|
|
|
|
namespace PlotLine.Services;
|
|
|
|
public static class StoryElementAttachmentPolicy
|
|
{
|
|
public const string AcceptedExtensions = ".png,.jpg,.jpeg,.webp,.mp3,.wav,.flac,.ogg,.pdf,.txt,.csv,.tsv,.docx,.xlsx";
|
|
|
|
public static bool IsImage(string filename) => Extension(filename) is ".png" or ".jpg" or ".jpeg" or ".webp";
|
|
|
|
public static string? AudioType(string filename) => Extension(filename) switch
|
|
{
|
|
".mp3" => "audio/mpeg",
|
|
".wav" => "audio/wav",
|
|
".flac" => "audio/flac",
|
|
".ogg" => "audio/ogg",
|
|
_ => null
|
|
};
|
|
|
|
public static bool IsAudio(string filename, ReadOnlySpan<byte> bytes) => Extension(filename) switch
|
|
{
|
|
".mp3" => bytes.Length >= 4 && (bytes.StartsWith("ID3"u8) ||
|
|
(bytes[0] == 0xff && (bytes[1] & 0xe6) == 0xe2)),
|
|
".wav" => bytes.Length >= 12 && bytes.StartsWith("RIFF"u8) && bytes[8..].StartsWith("WAVE"u8),
|
|
".flac" => bytes.StartsWith("fLaC"u8),
|
|
".ogg" => bytes.Length > 27 && bytes.StartsWith("OggS"u8) &&
|
|
bytes.Length > 27 + bytes[26] &&
|
|
(bytes[(27 + bytes[26])..].StartsWith("OpusHead"u8) ||
|
|
bytes[(27 + bytes[26])..].StartsWith("\x01vorbis"u8)),
|
|
_ => false
|
|
};
|
|
|
|
public static bool IsPdf(string filename, ReadOnlySpan<byte> bytes) =>
|
|
Extension(filename) == ".pdf" && bytes.StartsWith("%PDF-"u8);
|
|
|
|
public static bool IsAllowedDocument(string filename, byte[] bytes) => Extension(filename) switch
|
|
{
|
|
".pdf" => IsPdf(filename, bytes),
|
|
".txt" or ".csv" or ".tsv" => IsText(bytes),
|
|
".docx" => IsOfficeDocument(bytes, "word/document.xml"),
|
|
".xlsx" => IsOfficeDocument(bytes, "xl/workbook.xml"),
|
|
_ => false
|
|
};
|
|
|
|
private static string Extension(string filename) => Path.GetExtension(filename).ToLowerInvariant();
|
|
|
|
private static bool IsText(byte[] bytes)
|
|
{
|
|
try
|
|
{
|
|
return new UTF8Encoding(false, true).GetString(bytes)
|
|
.All(character => !char.IsControl(character) || character is '\r' or '\n' or '\t');
|
|
}
|
|
catch (DecoderFallbackException) { return false; }
|
|
}
|
|
|
|
private static bool IsOfficeDocument(byte[] bytes, string mainPart)
|
|
{
|
|
try
|
|
{
|
|
using var archive = new ZipArchive(new MemoryStream(bytes), ZipArchiveMode.Read);
|
|
return archive.GetEntry("[Content_Types].xml") is not null &&
|
|
archive.GetEntry(mainPart) is not null &&
|
|
!archive.Entries.Any(entry =>
|
|
entry.Name.Equals("vbaProject.bin", StringComparison.OrdinalIgnoreCase) ||
|
|
entry.FullName.Contains("/embeddings/", StringComparison.OrdinalIgnoreCase) ||
|
|
entry.FullName.Contains("/activeX/", StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
catch (InvalidDataException) { return false; }
|
|
}
|
|
}
|