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)
@@ -22,4 +19,16 @@ public class MediaService(IMongoDatabase db, AobaService aobaService)
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);
}
}
}

View File

@@ -2,11 +2,11 @@
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;
namespace AobaV2;
namespace AobaServer;
internal class AobaAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public AobaAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
public AobaAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
{
}

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
@@ -10,14 +10,11 @@
<ItemGroup>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="MaybeError" Version="1.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="9.0.3" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.7.0" />
<PackageReference Include="MaybeError" Version="1.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.8.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="3.0.71" />
<PackageReference Include="MongoDB.Analyzer" Version="1.5.0" />
<PackageReference Include="MongoDB.Bson" Version="3.3.0" />
<PackageReference Include="MimeTypesMap" Version="1.0.9" />
</ItemGroup>
<ItemGroup>

1
AobaServer/Auth.json Normal file
View File

@@ -0,0 +1 @@
{"Issuer":"aobaV2","Audience":"aoba","SecureKey":"iOx/85/SdBG4xji/aNzNMNpwOIZgPgr3hul4ddDrcp8jHxVL4uGPKvOBjVfOqG0IOMDZvaxOjieKdqdJnU9eNA=="}

View File

@@ -1,14 +1,15 @@
using MongoDB.Bson.IO;
using System.Security.Cryptography;
using System.Text.Json;
namespace AobaV2;
namespace AobaServer;
public class AuthInfo
{
public required string Issuer;
public required string Audience;
public required byte[] SecureKey;
public required string Issuer { get; set; }
public required string Audience { get; set; }
public required byte[] SecureKey { get; set; }
/// <summary>
/// Save this auth into in a json format to the sepcified file
@@ -53,7 +54,7 @@ public class AuthInfo
if (File.Exists(path))
{
var loaded = Load(path);
if(loaded != null)
if (loaded != null)
return loaded;
}
var info = Create(issuer, audience);

View File

@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Mvc;
namespace AobaV2.Controllers.Api;
namespace AobaServer.Controllers.Api;
[Route("/api/auth")]
public class AuthApi : ControllerBase

View File

@@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AobaV2.Controllers;
namespace AobaServer.Controllers;
[AllowAnonymous]
[Route("auth")]

View File

@@ -1,27 +1,44 @@
using AobaCore;
using HeyRed.Mime;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
namespace AobaV2.Controllers;
namespace AobaServer.Controllers;
[Route("/m")]
public class MediaController(MediaService media) : Controller
public class MediaController(MediaService mediaService, ILogger<MediaController> logger) : Controller
{
[HttpGet("{id}")]
public IActionResult Media(ObjectId id)
[ResponseCache(Duration = int.MaxValue)]
public async Task<IActionResult> MediaAsync(ObjectId id)
{
return View();
var file = await mediaService.GetMediaStreamAsync(id);
if (file.HasError)
{
logger.LogError(file.Error.Exception, "Failed to load media stream");
return NotFound();
}
var mime = MimeTypesMap.GetMimeType(file.Value.FileInfo.Filename);
return File(file, mime, true);
}
/// <summary>
/// Redirect legacy media urls to the new url
/// </summary>
/// <param name="id"></param>
/// <param name="rest"></param>
/// <param name="aoba"></param>
/// <returns></returns>
[HttpGet("/i/{id}/{*rest}")]
public async Task<IActionResult> LegacyRedirectAsync(ObjectId id, string rest, [FromServices] AobaService aoba)
{
var media = await aoba.GetMediaAsync(id);
if (media == null)
return NotFound();
return LocalRedirectPermanent($"/m/{media.Id}/{rest}");
return LocalRedirectPermanent($"/m/{media.MediaId}/{rest}");
}
}

View File

@@ -14,7 +14,6 @@ ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["AobaV2/AobaV2.csproj", "AobaV2/"]
RUN dotnet restore "./AobaV2/AobaV2.csproj"
RUN npm install
COPY . .
WORKDIR "/src/AobaV2"
RUN dotnet build "./AobaV2.csproj" -c $BUILD_CONFIGURATION -o /app/build

View File

@@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using MongoDB.Bson;
namespace AobaV2.Models;
namespace AobaServer.Models;
public class BsonIdModelBinderProvider : IModelBinderProvider
{

View File

@@ -1,10 +1,9 @@
using AobaCore;
using AobaV2;
using AobaV2.Models;
using AobaServer;
using AobaServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.IdentityModel.Tokens;
@@ -12,8 +11,7 @@ using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services
.AddControllers(opt => opt.ModelBinderProviders.Add(new BsonIdModelBinderProvider()));
builder.Services.AddControllers(opt => opt.ModelBinderProviders.Add(new BsonIdModelBinderProvider()));
var authInfo = AuthInfo.LoadOrCreate("Auth.json", "aobaV2", "aoba");
@@ -89,12 +87,8 @@ app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapStaticAssets();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
app.MapControllers();
app.Run();