implement media serving

This commit is contained in:
2025-04-15 23:00:11 -04:00
parent 0e714a7ffe
commit 1c9127ca19
14 changed files with 72 additions and 43 deletions

View File

@@ -8,7 +8,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.3" />
<PackageReference Include="MongoDB.Bson" Version="3.3.0" />
<PackageReference Include="MaybeError" Version="1.0.5" />
<PackageReference Include="MongoDB.Analyzer" Version="1.5.0" />
<PackageReference Include="MongoDB.Driver" Version="2.30.0" />

View File

@@ -9,7 +9,6 @@ public class AobaService(IMongoDatabase db)
{
private readonly IMongoCollection<Media> _media = db.GetCollection<Media>("media");
public async Task<Media?> GetMediaAsync(ObjectId id)
{
return await _media.Find(m => m.Id == id).FirstOrDefaultAsync();
@@ -19,4 +18,9 @@ public class AobaService(IMongoDatabase db)
{
return _media.InsertOneAsync(media);
}
public Task IncrementViewCountAsync(ObjectId id)
{
return _media.UpdateOneAsync(m => m.Id == id, Builders<Media>.Update.Inc(m => m.ViewCount, 1));
}
}

View File

@@ -1,6 +1,8 @@
global using MaybeError;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -12,7 +14,13 @@ public static class Extensions
{
public static IServiceCollection AddAoba(this IServiceCollection services)
{
var dbClient = new MongoClient("mongodb://NinoIna:27017");
var db = dbClient.GetDatabase("Aoba");
services.AddSingleton(dbClient);
services.AddSingleton<IMongoDatabase>(db);
services.AddSingleton<AobaService>();
services.AddSingleton<MediaService>();
return services;
}
}

View File

@@ -1,14 +1,11 @@
using AobaV2.Models;
using AobaV2.Models;
using MaybeError.Errors;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AobaCore;
public class MediaService(IMongoDatabase db, AobaService aobaService)
@@ -18,8 +15,20 @@ public class MediaService(IMongoDatabase db, AobaService aobaService)
public async Task<Maybe<Media>> UploadMediaAsync(Stream data, string filename, ObjectId owner, CancellationToken cancellationToken = default)
{
var fileId = await _gridFs.UploadFromStreamAsync(filename, data, cancellationToken: cancellationToken);
var media = new Media(fileId, filename, owner);
var media = new Media(fileId, filename, owner);
await aobaService.AddMediaAsync(media);
return media;
}
public async Task<Maybe<GridFSDownloadStream, ExceptionError<GridFSException>>> GetMediaStreamAsync(ObjectId id, bool seekable = false)
{
try
{
return await _gridFs.OpenDownloadStreamAsync(id, new GridFSDownloadOptions { Seekable = seekable });
}
catch (GridFSException ex)
{
return new ExceptionError<GridFSException>(ex);
}
}
}