// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using NSwag.Annotations; using Squidex.Areas.Api.Controllers.Assets.Models; using Squidex.Domain.Apps.Entities.Apps.Services; using Squidex.Domain.Apps.Entities.Assets; using Squidex.Domain.Apps.Entities.Assets.Commands; using Squidex.Domain.Apps.Entities.Assets.Repositories; using Squidex.Infrastructure; using Squidex.Infrastructure.Assets; using Squidex.Infrastructure.Commands; using Squidex.Pipeline; namespace Squidex.Areas.Api.Controllers.Assets { /// /// Uploads and retrieves assets. /// [ApiAuthorize] [ApiExceptionFilter] [AppApi] [SwaggerTag(nameof(Assets))] public sealed class AssetsController : ApiController { private readonly IAssetRepository assetRepository; private readonly IAssetStatsRepository assetStatsRepository; private readonly IAppPlansProvider appPlanProvider; private readonly AssetConfig assetsConfig; public AssetsController( ICommandBus commandBus, IAssetRepository assetRepository, IAssetStatsRepository assetStatsRepository, IAppPlansProvider appPlanProvider, IOptions assetsConfig) : base(commandBus) { this.assetsConfig = assetsConfig.Value; this.assetRepository = assetRepository; this.assetStatsRepository = assetStatsRepository; this.appPlanProvider = appPlanProvider; } /// /// Get assets. /// /// The name of the app. /// The optional asset ids. /// /// 200 => Assets returned. /// 404 => App not found. /// /// /// Get all assets for the app. /// [MustBeAppReader] [HttpGet] [Route("apps/{app}/assets/")] [ProducesResponseType(typeof(AssetsDto), 200)] [ApiCosts(1)] public async Task GetAssets(string app, [FromQuery] string ids = null) { HashSet idsList = null; if (!string.IsNullOrWhiteSpace(ids)) { idsList = new HashSet(); foreach (var id in ids.Split(',')) { if (Guid.TryParse(id, out var guid)) { idsList.Add(guid); } } } var assets = idsList?.Count > 0 ? await assetRepository.QueryAsync(App.Id, idsList) : await assetRepository.QueryAsync(App.Id, Request.QueryString.ToString()); var response = AssetsDto.FromAssets(assets); Response.Headers["Surrogate-Key"] = string.Join(" ", response.Items.Select(x => x.Id)); return Ok(response); } /// /// Get an asset by id. /// /// The name of the app. /// The id of the asset to retrieve. /// /// 200 => Asset found. /// 404 => Asset or app not found. /// [MustBeAppReader] [HttpGet] [Route("apps/{app}/assets/{id}/")] [ProducesResponseType(typeof(AssetsDto), 200)] [ApiCosts(1)] public async Task GetAsset(string app, Guid id) { var entity = await assetRepository.FindAssetAsync(id); if (entity == null) { return NotFound(); } var response = AssetDto.FromAsset(entity); Response.Headers["ETag"] = entity.Version.ToString(); Response.Headers["Surrogate-Key"] = entity.Id.ToString(); return Ok(response); } /// /// Upload a new asset. /// /// The name of the app. /// The file to upload. /// /// 201 => Asset created. /// 404 => App not found. /// 400 => Asset exceeds the maximum size. /// /// /// You can only upload one file at a time. The mime type of the file is not calculated by Squidex and is required correctly. /// [MustBeAppEditor] [HttpPost] [Route("apps/{app}/assets/")] [ProducesResponseType(typeof(AssetCreatedDto), 201)] [ProducesResponseType(typeof(ErrorDto), 400)] public async Task PostAsset(string app, [SwaggerIgnore] List file) { var assetFile = await CheckAssetFileAsync(file); var command = new CreateAsset { File = assetFile }; var context = await CommandBus.PublishAsync(command); var result = context.Result>(); var response = AssetCreatedDto.FromCommand(command, result); return StatusCode(201, response); } /// /// Replace asset content. /// /// The name of the app. /// The id of the asset. /// The file to upload. /// /// 201 => Asset updated. /// 404 => Asset or app not found. /// 400 => Asset exceeds the maximum size. /// /// /// Use multipart request to upload an asset. /// [MustBeAppEditor] [HttpPut] [Route("apps/{app}/assets/{id}/content/")] [ProducesResponseType(typeof(AssetReplacedDto), 201)] [ProducesResponseType(typeof(ErrorDto), 400)] [ApiCosts(1)] public async Task PutAssetContent(string app, Guid id, [SwaggerIgnore] List file) { var assetFile = await CheckAssetFileAsync(file); var command = new UpdateAsset { File = assetFile, AssetId = id }; var context = await CommandBus.PublishAsync(command); var result = context.Result(); var response = AssetReplacedDto.Create(command, result); return StatusCode(201, response); } /// /// Updates the asset. /// /// The name of the app. /// The id of the asset. /// The asset object that needs to updated. /// /// 204 => Asset updated. /// 400 => Asset name not valid. /// 404 => Asset or app not found. /// [MustBeAppReader] [HttpPut] [Route("apps/{app}/assets/{id}/")] [ProducesResponseType(typeof(ErrorDto), 400)] [ApiCosts(1)] public async Task PutAsset(string app, Guid id, [FromBody] AssetUpdateDto request) { await CommandBus.PublishAsync(request.ToCommand(id)); return NoContent(); } /// /// Delete an asset. /// /// The name of the app. /// The id of the asset to delete. /// /// 204 => Asset has been deleted. /// 404 => Asset or app not found. /// [MustBeAppEditor] [HttpDelete] [Route("apps/{app}/assets/{id}/")] [ApiCosts(1)] public async Task DeleteAsset(string app, Guid id) { await CommandBus.PublishAsync(new DeleteAsset { AssetId = id }); return NoContent(); } private async Task CheckAssetFileAsync(IReadOnlyList file) { if (file.Count != 1) { var error = new ValidationError($"Can only upload one file, found {file.Count} files."); throw new ValidationException("Cannot create asset.", error); } var formFile = file[0]; if (formFile.Length > assetsConfig.MaxSize) { var error = new ValidationError($"File size cannot be longer than {assetsConfig.MaxSize.ToReadableSize()}."); throw new ValidationException("Cannot create asset.", error); } var plan = appPlanProvider.GetPlanForApp(App); var currentSize = await assetStatsRepository.GetTotalSizeAsync(App.Id); if (plan.MaxAssetSize > 0 && plan.MaxAssetSize < currentSize + formFile.Length) { var error = new ValidationError("You have reached your max asset size."); throw new ValidationException("Cannot create asset.", error); } var assetFile = new AssetFile(formFile.FileName, formFile.ContentType, formFile.Length, formFile.OpenReadStream); return assetFile; } } }