voidkitty/VoidCat/Controllers/UploadController.cs

286 lines
11 KiB
C#
Raw Normal View History

2022-02-26 23:32:19 +00:00
using Microsoft.AspNetCore.Mvc;
2022-01-28 10:32:00 +00:00
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
2022-03-14 09:40:18 +00:00
using Microsoft.AspNetCore.StaticFiles;
2022-01-25 23:39:51 +00:00
using Newtonsoft.Json;
2022-01-25 16:17:48 +00:00
using VoidCat.Model;
2022-02-21 09:39:59 +00:00
using VoidCat.Model.Paywall;
2022-02-16 16:33:00 +00:00
using VoidCat.Services.Abstractions;
2022-01-25 16:17:48 +00:00
namespace VoidCat.Controllers
{
[Route("upload")]
public class UploadController : Controller
{
2022-02-08 18:20:59 +00:00
private readonly IFileStore _storage;
2022-02-21 09:39:59 +00:00
private readonly IFileMetadataStore _metadata;
private readonly IPaywallStore _paywall;
2022-02-21 12:54:57 +00:00
private readonly IPaywallFactory _paywallFactory;
2022-02-27 13:54:25 +00:00
private readonly IFileInfoManager _fileInfo;
2022-06-08 16:17:53 +00:00
private readonly IUserUploadsStore _userUploads;
2022-01-25 16:17:48 +00:00
2022-02-21 12:54:57 +00:00
public UploadController(IFileStore storage, IFileMetadataStore metadata, IPaywallStore paywall,
2022-06-08 16:17:53 +00:00
IPaywallFactory paywallFactory, IFileInfoManager fileInfo, IUserUploadsStore userUploads)
2022-01-25 16:17:48 +00:00
{
2022-01-25 23:39:51 +00:00
_storage = storage;
2022-02-21 09:39:59 +00:00
_metadata = metadata;
_paywall = paywall;
2022-02-21 12:54:57 +00:00
_paywallFactory = paywallFactory;
2022-02-27 13:54:25 +00:00
_fileInfo = fileInfo;
2022-06-08 16:17:53 +00:00
_userUploads = userUploads;
2022-01-25 16:17:48 +00:00
}
2022-03-08 13:47:42 +00:00
/// <summary>
/// Primary upload endpoint
/// </summary>
/// <remarks>
/// Additional optional headers can be included to provide details about the file being uploaded:
///
/// `V-Content-Type` - Sets the `mimeType` of the file and is used on the preview page to display the file.
/// `V-Filename` - Sets the filename of the file.
/// `V-Description` - Sets the description of the file.
/// `V-Full-Digest` - Include a SHA256 hash of the entire file for verification purposes.
/// `V-Digest` - A SHA256 hash of the data you are sending in this request.
/// </remarks>
/// <param name="cli">True if you want to return only the url of the file in the response</param>
/// <returns>Returns <see cref="UploadResult"/></returns>
2022-01-25 16:17:48 +00:00
[HttpPost]
2022-01-25 23:39:51 +00:00
[DisableRequestSizeLimit]
2022-01-28 10:32:00 +00:00
[DisableFormValueModelBinding]
2022-02-28 20:47:57 +00:00
public async Task<IActionResult> UploadFile([FromQuery] bool cli = false)
2022-01-25 16:17:48 +00:00
{
2022-02-10 22:22:34 +00:00
try
2022-02-03 23:06:39 +00:00
{
2022-02-24 23:05:33 +00:00
var uid = HttpContext.GetUserId();
2022-03-14 09:40:18 +00:00
var mime = Request.Headers.GetHeader("V-Content-Type");
var filename = Request.Headers.GetHeader("V-Filename");
if (string.IsNullOrEmpty(mime) && !string.IsNullOrEmpty(filename))
{
if (new FileExtensionContentTypeProvider().TryGetContentType(filename, out var contentType))
{
mime = contentType;
}
}
2022-06-06 21:51:25 +00:00
var meta = new SecretVoidFileMeta
2022-02-10 22:22:34 +00:00
{
2022-03-14 09:40:18 +00:00
MimeType = mime,
Name = filename,
2022-02-17 15:52:49 +00:00
Description = Request.Headers.GetHeader("V-Description"),
2022-02-24 23:05:33 +00:00
Digest = Request.Headers.GetHeader("V-Full-Digest"),
2022-06-10 20:42:36 +00:00
Size = (ulong?) Request.ContentLength ?? 0UL
2022-02-10 22:22:34 +00:00
};
2022-02-17 09:32:34 +00:00
var digest = Request.Headers.GetHeader("V-Digest");
2022-02-28 20:47:57 +00:00
var vf = await _storage.Ingress(new(Request.Body, meta)
{
Hash = digest
}, HttpContext.RequestAborted);
2022-06-08 16:17:53 +00:00
// save metadata
await _metadata.Set(vf.Id, vf.Metadata!);
2022-06-10 20:42:36 +00:00
2022-06-08 16:17:53 +00:00
// attach file upload to user
if (uid.HasValue)
{
await _userUploads.AddFile(uid!.Value, vf);
}
2022-06-10 20:42:36 +00:00
2022-02-28 20:47:57 +00:00
if (cli)
{
2022-03-14 09:40:18 +00:00
var urlBuilder = new UriBuilder(Request.IsHttps ? "https" : "http", Request.Host.Host,
Request.Host.Port ?? 80,
2022-02-28 20:47:57 +00:00
$"/d/{vf.Id.ToBase58()}");
return Content(urlBuilder.Uri.ToString(), "text/plain");
}
return Json(UploadResult.Success(vf));
2022-02-10 22:22:34 +00:00
}
catch (Exception ex)
{
2022-02-28 20:47:57 +00:00
return Json(UploadResult.Error(ex.Message));
2022-02-10 22:22:34 +00:00
}
}
2022-03-08 13:47:42 +00:00
/// <summary>
/// Append data onto a file
/// </summary>
/// <remarks>
/// This endpoint is mainly used to bypass file upload limits enforced by CloudFlare.
/// Clients should split their uploads into segments, upload the first segment to the regular
/// upload endpoint, use the `editSecret` to append data to the file.
///
/// Set the edit secret in the header `V-EditSecret` otherwise you will not be able to append data.
/// </remarks>
/// <param name="id"></param>
/// <returns></returns>
2022-02-10 22:22:34 +00:00
[HttpPost]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
[Route("{id}")]
public async Task<UploadResult> UploadFileAppend([FromRoute] string id)
{
try
{
var gid = id.FromBase58Guid();
2022-02-27 13:54:25 +00:00
var meta = await _metadata.Get<SecretVoidFileMeta>(gid);
if (meta == default) return UploadResult.Error("File not found");
2022-02-10 22:22:34 +00:00
2022-02-17 09:32:34 +00:00
var editSecret = Request.Headers.GetHeader("V-EditSecret");
var digest = Request.Headers.GetHeader("V-Digest");
2022-02-28 20:47:57 +00:00
var vf = await _storage.Ingress(new(Request.Body, meta)
2022-02-10 22:22:34 +00:00
{
2022-02-28 20:47:57 +00:00
Hash = digest,
2022-02-26 22:57:42 +00:00
EditSecret = editSecret?.FromBase58Guid() ?? Guid.Empty,
2022-03-01 16:48:42 +00:00
Id = gid,
IsAppend = true
2022-02-10 22:22:34 +00:00
}, HttpContext.RequestAborted);
2022-06-10 20:42:36 +00:00
2022-06-08 16:17:53 +00:00
// update file size
await _metadata.Set(vf.Id, vf.Metadata!);
2022-02-10 22:22:34 +00:00
return UploadResult.Success(vf);
}
catch (Exception ex)
{
return UploadResult.Error(ex.Message);
}
2022-01-25 16:17:48 +00:00
}
2022-03-08 13:47:42 +00:00
/// <summary>
/// Return information about a specific file
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
2022-01-25 23:39:51 +00:00
[HttpGet]
[Route("{id}")]
2022-06-10 20:42:36 +00:00
public async Task<IActionResult> GetInfo([FromRoute] string id)
2022-01-25 16:17:48 +00:00
{
2022-06-10 20:42:36 +00:00
var fid = id.FromBase58Guid();
var uid = HttpContext.GetUserId();
var isOwner = uid.HasValue && await _userUploads.Uploader(fid) == uid;
return isOwner ? Json(await _fileInfo.GetPrivate(fid)) : Json(await _fileInfo.Get(fid));
2022-01-25 16:17:48 +00:00
}
2022-02-21 09:39:59 +00:00
2022-03-08 13:47:42 +00:00
/// <summary>
/// Create a paywall order to pay
/// </summary>
/// <param name="id">File id</param>
/// <returns></returns>
2022-02-21 09:39:59 +00:00
[HttpGet]
[Route("{id}/paywall")]
2022-02-21 12:54:57 +00:00
public async ValueTask<PaywallOrder?> CreateOrder([FromRoute] string id)
2022-02-21 09:39:59 +00:00
{
2022-02-21 12:54:57 +00:00
var gid = id.FromBase58Guid();
2022-02-27 13:54:25 +00:00
var file = await _fileInfo.Get(gid);
var config = await _paywall.Get(gid);
2022-02-21 12:54:57 +00:00
var provider = await _paywallFactory.CreateProvider(config!.Service);
2022-06-13 13:35:26 +00:00
return await provider.CreateOrder(file!.Paywall!);
2022-02-21 09:39:59 +00:00
}
2022-02-27 13:54:25 +00:00
2022-03-08 13:47:42 +00:00
/// <summary>
/// Return the status of an order
/// </summary>
/// <param name="id">File id</param>
/// <param name="order">Order id</param>
/// <returns></returns>
2022-02-21 12:54:57 +00:00
[HttpGet]
[Route("{id}/paywall/{order:guid}")]
2022-02-27 13:54:25 +00:00
public async ValueTask<PaywallOrder?> GetOrderStatus([FromRoute] string id, [FromRoute] Guid order)
2022-02-21 12:54:57 +00:00
{
var gid = id.FromBase58Guid();
var config = await _paywall.Get(gid);
2022-02-21 12:54:57 +00:00
var provider = await _paywallFactory.CreateProvider(config!.Service);
return await provider.GetOrderStatus(order);
}
2022-03-08 13:47:42 +00:00
/// <summary>
/// Update the paywall config
/// </summary>
/// <param name="id">File id</param>
/// <param name="req">Requested config to set on the file</param>
/// <returns></returns>
2022-02-21 09:39:59 +00:00
[HttpPost]
[Route("{id}/paywall")]
public async Task<IActionResult> SetPaywallConfig([FromRoute] string id, [FromBody] SetPaywallConfigRequest req)
{
var gid = id.FromBase58Guid();
2022-02-27 13:54:25 +00:00
var meta = await _metadata.Get<SecretVoidFileMeta>(gid);
2022-02-21 09:39:59 +00:00
if (meta == default) return NotFound();
2022-06-10 20:42:36 +00:00
if (!meta.CanEdit(req.EditSecret)) return Unauthorized();
2022-02-21 12:54:57 +00:00
2022-02-21 09:39:59 +00:00
if (req.Strike != default)
{
2022-06-13 13:35:26 +00:00
await _paywall.Add(gid, new StrikePaywallConfig()
{
Service = PaymentServices.Strike,
Handle = req.Strike.Handle,
Cost = req.Strike.Cost
});
2022-02-21 09:39:59 +00:00
return Ok();
}
2022-06-13 13:35:26 +00:00
// if none set, delete config
await _paywall.Delete(gid);
2022-02-21 14:32:13 +00:00
return Ok();
2022-02-21 09:39:59 +00:00
}
2022-03-15 10:39:36 +00:00
/// <summary>
/// Update metadata about file
/// </summary>
/// <param name="id">Id of file to edit</param>
/// <param name="fileMeta">New metadata to update</param>
/// <returns></returns>
/// <remarks>
/// You can only change `Name`, `Description` and `MimeType`
/// </remarks>
[HttpPost]
[Route("{id}/meta")]
public async Task<IActionResult> UpdateFileMeta([FromRoute] string id, [FromBody] SecretVoidFileMeta fileMeta)
{
var gid = id.FromBase58Guid();
var meta = await _metadata.Get<SecretVoidFileMeta>(gid);
if (meta == default) return NotFound();
2022-06-10 20:42:36 +00:00
if (!meta.CanEdit(fileMeta.EditSecret)) return Unauthorized();
2022-03-15 10:39:36 +00:00
await _metadata.Update(gid, fileMeta);
return Ok();
}
2022-01-25 16:17:48 +00:00
}
2022-01-28 10:32:00 +00:00
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
var factories = context.ValueProviderFactories;
factories.RemoveType<FormValueProviderFactory>();
factories.RemoveType<FormFileValueProviderFactory>();
factories.RemoveType<JQueryFormValueProviderFactory>();
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
}
2022-02-10 22:22:34 +00:00
2022-02-17 15:52:49 +00:00
public record UploadResult(bool Ok, PrivateVoidFile? File, string? ErrorMessage)
2022-02-10 22:22:34 +00:00
{
2022-02-17 15:52:49 +00:00
public static UploadResult Success(PrivateVoidFile vf)
2022-02-10 22:22:34 +00:00
=> new(true, vf, null);
public static UploadResult Error(string message)
=> new(false, null, message);
}
2022-02-21 09:39:59 +00:00
public record SetPaywallConfigRequest
{
[JsonConverter(typeof(Base58GuidConverter))]
public Guid EditSecret { get; init; }
2022-02-21 12:54:57 +00:00
2022-02-21 09:39:59 +00:00
public StrikePaywallConfig? Strike { get; init; }
}
2022-03-14 09:40:18 +00:00
}