305 lines
9.6 KiB
C#

// Kyoo - A portable and vast media library solution.
// Copyright (c) Kyoo.
//
// See AUTHORS.md and LICENSE file in the project root for full license information.
//
// Kyoo is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// Kyoo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Kyoo.Core.Api
{
/// <summary>
/// A base class to handle CRUD operations on a specific resource type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of resource to make CRUD apis for.</typeparam>
[ApiController]
[ResourceView]
public class CrudApi<T> : ControllerBase
where T : class, IResource
{
/// <summary>
/// The repository of the resource, used to retrieve, save and do operations on the baking store.
/// </summary>
private readonly IRepository<T> _repository;
/// <summary>
/// The base URL of Kyoo. This will be used to create links for images and <see cref="Abstractions.Models.Page{T}"/>.
/// </summary>
protected Uri BaseURL { get; }
/// <summary>
/// Create a new <see cref="CrudApi{T}"/> using the given repository and base url.
/// </summary>
/// <param name="repository">
/// The repository to use as a baking store for the type <typeparamref name="T"/>.
/// </param>
/// <param name="baseURL">
/// The base URL of Kyoo to use to create links.
/// </param>
public CrudApi(IRepository<T> repository, Uri baseURL)
{
_repository = repository;
BaseURL = baseURL;
}
/// <summary>
/// Construct and return a page from an api.
/// </summary>
/// <param name="resources">The list of resources that should be included in the current page.</param>
/// <param name="limit">
/// The max number of items that should be present per page. This should be the same as in the request,
/// it is used to calculate if this is the last page and so on.
/// </param>
/// <typeparam name="TResult">The type of items on the page.</typeparam>
/// <returns>A Page representing the response.</returns>
protected Page<TResult> Page<TResult>(ICollection<TResult> resources, int limit)
where TResult : IResource
{
return new Page<TResult>(resources,
new Uri(BaseURL, Request.Path),
Request.Query.ToDictionary(x => x.Key, x => x.Value.ToString(), StringComparer.InvariantCultureIgnoreCase),
limit);
}
/// <summary>
/// Get by ID
/// </summary>
/// <remarks>
/// Get a specific resource via it's ID.
/// </remarks>
/// <param name="id">The ID of the resource to retrieve.</param>
/// <returns>The retrieved resource.</returns>
/// <response code="404">A resource with the given ID does not exist.</response>
[HttpGet("{id:int}")]
[PartialPermission(Kind.Read)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<T>> Get(int id)
{
T ret = await _repository.GetOrDefault(id);
if (ret == null)
return NotFound();
return ret;
}
/// <summary>
/// Get by slug
/// </summary>
/// <remarks>
/// Get a specific resource via it's slug (a unique, human readable identifier).
/// </remarks>
/// <param name="slug" example="1">The slug of the resource to retrieve.</param>
/// <returns>The retrieved resource.</returns>
/// <response code="404">A resource with the given ID does not exist.</response>
[HttpGet("{slug}")]
[PartialPermission(Kind.Read)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<T>> Get(string slug)
{
T ret = await _repository.GetOrDefault(slug);
if (ret == null)
return NotFound();
return ret;
}
/// <summary>
/// Get count
/// </summary>
/// <remarks>
/// Get the number of resources that match the filters.
/// </remarks>
/// <param name="where">A list of filters to respect.</param>
/// <returns>How many resources matched that filter.</returns>
/// <response code="400">Invalid filters.</response>
[HttpGet("count")]
[PartialPermission(Kind.Read)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(RequestError))]
public async Task<ActionResult<int>> GetCount([FromQuery] Dictionary<string, string> where)
{
try
{
return await _repository.GetCount(ApiHelper.ParseWhere<T>(where));
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
}
/// <summary>
/// Get all
/// </summary>
/// <remarks>
/// Get all resources that match the given filter.
/// </remarks>
/// <param name="sortBy">Sort information about the query (sort by, sort order).</param>
/// <param name="afterID">Where the pagination should start.</param>
/// <param name="where">Filter the returned items.</param>
/// <param name="limit">How many items per page should be returned.</param>
/// <returns>A list of resources that match every filters.</returns>
/// <response code="400">Invalid filters or sort information.</response>
[HttpGet]
[PartialPermission(Kind.Read)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(RequestError))]
public async Task<ActionResult<Page<T>>> GetAll([FromQuery] string sortBy,
[FromQuery] int afterID,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20)
{
try
{
ICollection<T> resources = await _repository.GetAll(ApiHelper.ParseWhere<T>(where),
new Sort<T>(sortBy),
new Pagination(limit, afterID));
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
}
/// <summary>
/// Create new
/// </summary>
/// <remarks>
/// Create a new item and store it. You may leave the ID unspecified, it will be filed by Kyoo.
/// </remarks>
/// <param name="resource">The resource to create.</param>
/// <returns>The created resource.</returns>
/// <response code="400">The resource in the request body is invalid.</response>
/// <response code="409">This item already exists (maybe a duplicated slug).</response>
[HttpPost]
[PartialPermission(Kind.Create)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(RequestError))]
[ProducesResponseType(StatusCodes.Status409Conflict, Type = typeof(ActionResult<>))]
public virtual async Task<ActionResult<T>> Create([FromBody] T resource)
{
try
{
return await _repository.Create(resource);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
catch (DuplicatedItemException)
{
T existing = await _repository.GetOrDefault(resource.Slug);
return Conflict(existing);
}
}
/// <summary>
/// Edit
/// </summary>
/// <remarks>
/// Edit an item. If the ID is specified it will be used to identify the resource.
/// If not, the slug will be used to identify it.
/// </remarks>
/// <param name="resource">The resource to edit.</param>
/// <param name="resetOld">
/// Should old properties of the resource be discarded or should null values considered as not changed?
/// </param>
/// <returns>The created resource.</returns>
/// <response code="400">The resource in the request body is invalid.</response>
/// <response code="404">No item found with the specified ID (or slug).</response>
[HttpPut]
[PartialPermission(Kind.Write)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(RequestError))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<T>> Edit([FromBody] T resource, [FromQuery] bool resetOld = true)
{
try
{
if (resource.ID > 0)
return await _repository.Edit(resource, resetOld);
T old = await _repository.Get(resource.Slug);
resource.ID = old.ID;
return await _repository.Edit(resource, resetOld);
}
catch (ItemNotFoundException)
{
return NotFound();
}
}
[HttpDelete("{id:int}")]
[PartialPermission(Kind.Delete)]
public virtual async Task<IActionResult> Delete(int id)
{
try
{
await _repository.Delete(id);
}
catch (ItemNotFoundException)
{
return NotFound();
}
return Ok();
}
[HttpDelete("{slug}")]
[PartialPermission(Kind.Delete)]
public virtual async Task<IActionResult> Delete(string slug)
{
try
{
await _repository.Delete(slug);
}
catch (ItemNotFoundException)
{
return NotFound();
}
return Ok();
}
[HttpDelete]
[PartialPermission(Kind.Delete)]
public virtual async Task<IActionResult> Delete(Dictionary<string, string> where)
{
try
{
await _repository.DeleteAll(ApiHelper.ParseWhere<T>(where));
}
catch (ItemNotFoundException)
{
return NotFound();
}
return Ok();
}
}
}