218 lines
6.7 KiB
C#
218 lines
6.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Threading.Tasks;
|
|
using GsDChat.Core.Models;
|
|
using GsDChat.Server.Configuration;
|
|
using GsDChat.Server.Data;
|
|
|
|
namespace GsDChat.Server.Services;
|
|
|
|
public class FileStorageService
|
|
{
|
|
private readonly ChatDatabase _db;
|
|
private readonly ServerOptions _options;
|
|
private readonly string _filesDirectory;
|
|
|
|
// Whitelist of allowed MIME types
|
|
private static readonly HashSet<string> AllowedContentTypes = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
// Images
|
|
"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml",
|
|
// Documents
|
|
"application/pdf", "text/plain", "text/csv", "application/octet-stream",
|
|
// Archives
|
|
"application/zip", "application/x-rar-compressed", "application/x-7z-compressed",
|
|
// Audio
|
|
"audio/mpeg", "audio/wav", "audio/ogg",
|
|
// Video
|
|
"video/mp4", "video/webm", "video/quicktime"
|
|
};
|
|
|
|
public FileStorageService(ChatDatabase db, ServerOptions options)
|
|
{
|
|
_db = db;
|
|
_options = options;
|
|
_filesDirectory = Path.Combine(options.DataDirectory, "files");
|
|
Directory.CreateDirectory(_filesDirectory);
|
|
}
|
|
|
|
private bool IsContentTypeAllowed(string contentType)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(contentType))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return AllowedContentTypes.Contains(contentType.Trim());
|
|
}
|
|
|
|
public async Task<FileRecord> StoreFileAsync(
|
|
string channelId,
|
|
string uploaderId,
|
|
string uploaderUsername,
|
|
string originalFileName,
|
|
string contentType,
|
|
Stream stream,
|
|
long length,
|
|
string uploaderRole = UserRoles.Member)
|
|
{
|
|
var (record, _) = await StoreFileWithMessageAsync(
|
|
channelId,
|
|
uploaderId,
|
|
uploaderUsername,
|
|
originalFileName,
|
|
contentType,
|
|
stream,
|
|
length,
|
|
uploaderRole);
|
|
return record;
|
|
}
|
|
|
|
public async Task<(FileRecord Record, ChatMessage Message)> StoreFileWithMessageAsync(
|
|
string channelId,
|
|
string uploaderId,
|
|
string uploaderUsername,
|
|
string originalFileName,
|
|
string contentType,
|
|
Stream stream,
|
|
long length,
|
|
string uploaderRole = UserRoles.Member)
|
|
{
|
|
long maxBytes = _options.MaxFileSizeMb * 1024 * 1024;
|
|
if (length > maxBytes)
|
|
{
|
|
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
|
}
|
|
|
|
// Validate content type
|
|
if (!IsContentTypeAllowed(contentType))
|
|
{
|
|
throw new InvalidOperationException($"File type '{contentType}' is not allowed.");
|
|
}
|
|
|
|
string safeName = Path.GetFileName(originalFileName);
|
|
if (string.IsNullOrWhiteSpace(safeName))
|
|
{
|
|
safeName = "unnamed_file.bin";
|
|
}
|
|
|
|
// Sanitize filename
|
|
safeName = InputSanitizer.SanitizeForDisplay(safeName, 255);
|
|
|
|
string fileId = Guid.NewGuid().ToString("N");
|
|
string diskFileName = $"{fileId}_{safeName}";
|
|
string diskFilePath = Path.Combine(_filesDirectory, diskFileName);
|
|
|
|
string sha256Hex;
|
|
long writtenBytes = 0;
|
|
|
|
using (var sha256 = SHA256.Create())
|
|
using (var fileStream = new FileStream(diskFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true))
|
|
{
|
|
byte[] buffer = new byte[81920];
|
|
int read;
|
|
while ((read = await stream.ReadAsync(buffer)) > 0)
|
|
{
|
|
writtenBytes += read;
|
|
if (writtenBytes > maxBytes)
|
|
{
|
|
fileStream.Close();
|
|
File.Delete(diskFilePath);
|
|
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
|
}
|
|
|
|
await fileStream.WriteAsync(buffer.AsMemory(0, read));
|
|
sha256.TransformBlock(buffer, 0, read, null, 0);
|
|
}
|
|
|
|
sha256.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
|
|
sha256Hex = Convert.ToHexString(sha256.Hash ?? Array.Empty<byte>());
|
|
}
|
|
|
|
var now = DateTime.UtcNow;
|
|
var record = new FileRecord
|
|
{
|
|
Id = fileId,
|
|
ChannelId = channelId,
|
|
UploaderId = uploaderId,
|
|
UploaderUsername = uploaderUsername,
|
|
OriginalFileName = safeName,
|
|
ContentType = string.IsNullOrWhiteSpace(contentType) ? "application/octet-stream" : contentType,
|
|
FileSizeBytes = writtenBytes,
|
|
StoragePath = diskFilePath,
|
|
Sha256Checksum = sha256Hex,
|
|
CreatedAt = now
|
|
};
|
|
|
|
await _db.SaveFileRecordAsync(record);
|
|
|
|
// Also create a chat message in the channel announcing the file
|
|
var msg = new ChatMessage
|
|
{
|
|
ChannelId = channelId,
|
|
SenderId = uploaderId,
|
|
SenderUsername = uploaderUsername,
|
|
SenderRole = string.IsNullOrWhiteSpace(uploaderRole) ? UserRoles.Member : uploaderRole,
|
|
Content = $"Shared file: {safeName} ({FormatBytes(writtenBytes)})",
|
|
CreatedAt = now,
|
|
AttachmentId = record.Id,
|
|
AttachmentName = safeName,
|
|
AttachmentSizeBytes = writtenBytes
|
|
};
|
|
await _db.SaveMessageAsync(msg);
|
|
|
|
return (record, msg);
|
|
}
|
|
|
|
public async Task<FileRecord?> GetFileRecordAsync(string fileId)
|
|
{
|
|
return await _db.GetFileRecordAsync(fileId);
|
|
}
|
|
|
|
public async Task<bool> DeleteFileAsync(string fileId)
|
|
{
|
|
var record = await _db.GetFileRecordAsync(fileId);
|
|
if (record == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(record.StoragePath) && File.Exists(record.StoragePath))
|
|
{
|
|
File.Delete(record.StoragePath);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Best effort disk cleanup
|
|
}
|
|
|
|
return await _db.DeleteFileRecordAsync(fileId);
|
|
}
|
|
|
|
public Stream? OpenFileStream(FileRecord record)
|
|
{
|
|
if (File.Exists(record.StoragePath))
|
|
{
|
|
return new FileStream(record.StoragePath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static string FormatBytes(long bytes)
|
|
{
|
|
string[] suffixes = { "B", "KB", "MB", "GB" };
|
|
int order = 0;
|
|
double size = bytes;
|
|
while (size >= 1024 && order < suffixes.Length - 1)
|
|
{
|
|
order++;
|
|
size /= 1024;
|
|
}
|
|
return $"{size:0.##} {suffixes[order]}";
|
|
}
|
|
}
|