init
This commit is contained in:
commit
f25ba8adcd
64 changed files with 5959 additions and 0 deletions
135
src/GsDChat.Server/Services/FileStorageService.cs
Normal file
135
src/GsDChat.Server/Services/FileStorageService.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
using System;
|
||||
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;
|
||||
|
||||
public FileStorageService(ChatDatabase db, ServerOptions options)
|
||||
{
|
||||
_db = db;
|
||||
_options = options;
|
||||
_filesDirectory = Path.Combine(options.DataDirectory, "files");
|
||||
Directory.CreateDirectory(_filesDirectory);
|
||||
}
|
||||
|
||||
public async Task<FileRecord> StoreFileAsync(
|
||||
string channelId,
|
||||
string uploaderId,
|
||||
string uploaderUsername,
|
||||
string originalFileName,
|
||||
string contentType,
|
||||
Stream stream,
|
||||
long length)
|
||||
{
|
||||
long maxBytes = _options.MaxFileSizeMb * 1024 * 1024;
|
||||
if (length > maxBytes)
|
||||
{
|
||||
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
||||
}
|
||||
|
||||
string safeName = Path.GetFileName(originalFileName);
|
||||
if (string.IsNullOrWhiteSpace(safeName))
|
||||
{
|
||||
safeName = "unnamed_file.bin";
|
||||
}
|
||||
|
||||
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 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 = DateTime.UtcNow
|
||||
};
|
||||
|
||||
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,
|
||||
Content = $"Shared file: {safeName} ({FormatBytes(writtenBytes)})",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
AttachmentId = record.Id,
|
||||
AttachmentName = safeName,
|
||||
AttachmentSizeBytes = writtenBytes
|
||||
};
|
||||
await _db.SaveMessageAsync(msg);
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
public async Task<FileRecord?> GetFileRecordAsync(string fileId)
|
||||
{
|
||||
return await _db.GetFileRecordAsync(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]}";
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue