Rework exception handling

This commit is contained in:
Zoe Roux 2023-03-13 18:38:46 +09:00
parent c0c263c4d7
commit 67112a37da
28 changed files with 379 additions and 676 deletions

View File

@ -28,19 +28,19 @@ namespace Kyoo.Abstractions.Models.Exceptions
public class DuplicatedItemException : Exception
{
/// <summary>
/// Create a new <see cref="DuplicatedItemException"/> with the default message.
/// The existing object.
/// </summary>
public DuplicatedItemException()
: base("Already exists in the database.")
{ }
public object Existing { get; }
/// <summary>
/// Create a new <see cref="DuplicatedItemException"/> with a custom message.
/// Create a new <see cref="DuplicatedItemException"/> with the default message.
/// </summary>
/// <param name="message">The message to use</param>
public DuplicatedItemException(string message)
: base(message)
{ }
/// <param name="existing">The existing object.</param>
public DuplicatedItemException(object existing = null)
: base("Already exists in the database.")
{
Existing = existing;
}
/// <summary>
/// The serialization constructor.

View File

@ -72,7 +72,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated collection (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -142,7 +142,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated episode (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return await _ValidateTracks(obj);
}

View File

@ -67,7 +67,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated genre (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -75,7 +75,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated library (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -72,33 +72,37 @@ namespace Kyoo.Core.Controllers
{
sortBy ??= DefaultSort;
switch (sortBy)
IOrderedQueryable<T> _Sort(IQueryable<T> query, Sort<T> sortBy)
{
case Sort<T>.Default:
return Sort(query, DefaultSort);
case Sort<T>.By(var key, var desc):
return desc
? query.OrderByDescending(x => EF.Property<object>(x, key))
: query.OrderBy(x => EF.Property<T>(x, key));
case Sort<T>.Conglomerate(var keys):
IOrderedQueryable<T> nQuery = Sort(query, keys[0]);
foreach ((string key, bool desc) in keys.Skip(1))
{
nQuery = desc
? nQuery.ThenByDescending(x => EF.Property<object>(x, key))
: nQuery.ThenBy(x => EF.Property<object>(x, key));
}
return nQuery;
default:
// The language should not require me to do this...
throw new SwitchExpressionException();
switch (sortBy)
{
case Sort<T>.Default:
return Sort(query, DefaultSort);
case Sort<T>.By(var key, var desc):
return desc
? query.OrderByDescending(x => EF.Property<object>(x, key))
: query.OrderBy(x => EF.Property<T>(x, key));
case Sort<T>.Conglomerate(var keys):
IOrderedQueryable<T> nQuery = _Sort(query, keys[0]);
foreach ((string key, bool desc) in keys.Skip(1))
{
nQuery = desc
? nQuery.ThenByDescending(x => EF.Property<object>(x, key))
: nQuery.ThenBy(x => EF.Property<object>(x, key));
}
return nQuery;
default:
// The language should not require me to do this...
throw new SwitchExpressionException();
}
}
return _Sort(query, sortBy).ThenBy(x => x.ID);
}
private static Func<Expression, Expression, BinaryExpression> GetComparisonExpression(
bool desc,
bool next,
bool orEqual)
private static Func<Expression, Expression, BinaryExpression> _GetComparisonExpression(
bool desc,
bool next,
bool orEqual)
{
bool greaterThan = desc ^ next;
@ -107,7 +111,6 @@ namespace Kyoo.Core.Controllers
: (greaterThan ? Expression.GreaterThan : Expression.LessThan);
}
/// <summary>
/// Create a filter (where) expression on the query to skip everything before/after the referenceID.
/// The generalized expression for this in pseudocode is:
@ -121,6 +124,10 @@ namespace Kyoo.Core.Controllers
/// (x = a AND y &lt; b) OR
/// (x = a AND y = b AND z > c) OR...
/// </summary>
/// <param name="sort">How items are sorted in the query</param>
/// <param name="reference">The reference item (the AfterID query)</param>
/// <param name="next">True if the following page should be returned, false for the previous.</param>
/// <returns>An expression ready to be added to a Where close of a sorted query to handle the AfterID</returns>
protected Expression<Func<T, bool>> KeysetPaginatate(
Sort<T> sort,
T reference,
@ -133,133 +140,52 @@ namespace Kyoo.Core.Controllers
ParameterExpression x = Expression.Parameter(typeof(T), "x");
ConstantExpression referenceC = Expression.Constant(reference, typeof(T));
if (sort is Sort<T>.By(var key, var desc))
// Don't forget that every sorts must end with a ID sort (to differenciate equalities).
Sort<T>.By id = new(x => x.ID);
IEnumerable<Sort<T>.By> sorts = (sort switch
{
Func<Expression, Expression, BinaryExpression> comparer = GetComparisonExpression(desc, next, false);
Sort<T>.By @sortBy => new[] { sortBy },
Sort<T>.Conglomerate(var list) => list,
_ => Array.Empty<Sort<T>.By>(),
}).Append(id);
BinaryExpression filter = null;
List<Sort<T>.By> previousSteps = new();
// TODO: Add an outer query >= for perf
// PERF: See https://use-the-index-luke.com/sql/partial-results/fetch-next-page#sb-equivalent-logic
foreach ((string key, bool desc) in sorts)
{
BinaryExpression compare = null;
// Create all the equality statements for previous sorts.
foreach ((string pKey, bool pDesc) in previousSteps)
{
BinaryExpression pcompare = Expression.Equal(
Expression.Property(x, pKey),
Expression.Property(referenceC, pKey)
);
compare = compare != null
? Expression.AndAlso(compare, pcompare)
: pcompare;
}
// Create the last comparison of the statement.
Func<Expression, Expression, BinaryExpression> comparer = _GetComparisonExpression(desc, next, false);
MemberExpression xkey = Expression.Property(x, key);
MemberExpression rkey = Expression.Property(referenceC, key);
BinaryExpression compare = ApiHelper.StringCompatibleExpression(comparer, xkey, rkey);
return Expression.Lambda<Func<T, bool>>(compare, x);
}
BinaryExpression lastCompare = ApiHelper.StringCompatibleExpression(comparer, xkey, rkey);
compare = compare != null
? Expression.AndAlso(compare, lastCompare)
: lastCompare;
if (sort is Sort<T>.Conglomerate(var list))
{
throw new NotImplementedException();
// BinaryExpression orExpression;
//
// foreach ((string key, bool desc) in list)
// {
// query.Where(x =>
// }
}
throw new SwitchExpressionException();
filter = filter != null
? Expression.OrElse(filter, compare)
: compare;
// Shamlessly stollen from https://github.com/mrahhal/MR.EntityFrameworkCore.KeysetPagination/blob/main/src/MR.EntityFrameworkCore.KeysetPagination/KeysetPaginationExtensions.cs#L191
// // A composite keyset pagination in sql looks something like this:
// // (x, y, ...) > (a, b, ...)
// // Where, x/y/... represent the column and a/b/... represent the reference's respective values.
// //
// // In sql standard this syntax is called "row value". Check here: https://use-the-index-luke.com/sql/partial-results/fetch-next-page#sb-row-values
// // Unfortunately, not all databases support this properly.
// // Further, if we were to use this we would somehow need EF Core to recognise it and translate it
// // perhaps by using a new DbFunction (https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbfunctions).
// // There's an ongoing issue for this here: https://github.com/dotnet/efcore/issues/26822
// //
// // In addition, row value won't work for mixed ordered columns. i.e if x > a but y < b.
// // So even if we can use it we'll still have to fallback to this logic in these cases.
// //
// // The generalized expression for this in pseudocode is:
// // (x > a) OR
// // (x = a AND y > b) OR
// // (x = a AND y = b AND z > c) OR...
// //
// // Of course, this will be a bit more complex when ASC and DESC are mixed.
// // Assume x is ASC, y is DESC, and z is ASC:
// // (x > a) OR
// // (x = a AND y < b) OR
// // (x = a AND y = b AND z > c) OR...
// //
// // An optimization is to include an additional redundant wrapping clause for the 1st column when there are
// // more than one column we're acting on, which would allow the db to use it as an access predicate on the 1st column.
// // See here: https://use-the-index-luke.com/sql/partial-results/fetch-next-page#sb-equivalent-logic
//
// var referenceValues = GetValues(columns, reference);
//
// MemberExpression firstMemberAccessExpression;
// Expression firstReferenceValueExpression;
//
// // entity =>
// ParameterExpression param = Expression.Parameter(typeof(T), "entity");
//
// BinaryExpression orExpression;
// int innerLimit = 1;
// // This loop compounds the outer OR expressions.
// for (int i = 0; i < sort.list.Length; i++)
// {
// BinaryExpression andExpression;
//
// // This loop compounds the inner AND expressions.
// // innerLimit implicitly grows from 1 to items.Count by each iteration.
// for (int j = 0; j < innerLimit; j++)
// {
// bool isInnerLastOperation = j + 1 == innerLimit;
// var column = columns[j];
// var memberAccess = column.MakeMemberAccessExpression(param);
// var referenceValue = referenceValues[j];
// Expression<Func<object>> referenceValueFunc = () => referenceValue;
// var referenceValueExpression = referenceValueFunc.Body;
//
// if (firstMemberAccessExpression == null)
// {
// // This might be used later on in an optimization.
// firstMemberAccessExpression = memberAccess;
// firstReferenceValueExpression = referenceValueExpression;
// }
//
// BinaryExpression innerExpression;
// if (!isInnerLastOperation)
// {
// innerExpression = Expression.Equal(
// memberAccess,
// EnsureMatchingType(memberAccess, referenceValueExpression));
// }
// else
// {
// var compare = GetComparisonExpressionToApply(direction, column, orEqual: false);
// innerExpression = MakeComparisonExpression(
// column,
// memberAccess, referenceValueExpression,
// compare);
// }
//
// andExpression = andExpression == null ? innerExpression : Expression.And(andExpression, innerExpression);
// }
//
// orExpression = orExpression == null ? andExpression : Expression.Or(orExpression, andExpression);
//
// innerLimit++;
// }
//
// var finalExpression = orExpression;
// if (columns.Count > 1)
// {
// // Implement the optimization that allows an access predicate on the 1st column.
// // This is done by generating the following expression:
// // (x >=|<= a) AND (previous generated expression)
// //
// // This effectively adds a redundant clause on the 1st column, but it's a clause all dbs
// // understand and can use as an access predicate (most commonly when the column is indexed).
//
// var firstColumn = columns[0];
// var compare = GetComparisonExpressionToApply(direction, firstColumn, orEqual: true);
// var accessPredicateClause = MakeComparisonExpression(
// firstColumn,
// firstMemberAccessExpression!, firstReferenceValueExpression!,
// compare);
// finalExpression = Expression.And(accessPredicateClause, finalExpression);
// }
//
// return Expression.Lambda<Func<T, bool>>(finalExpression, param);
previousSteps.Add(new(key, desc));
}
return Expression.Lambda<Func<T, bool>>(filter, x);
}
/// <summary>

View File

@ -85,7 +85,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated people (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -67,8 +67,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync("Trying to insert a duplicated provider " +
$"(slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -108,7 +108,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated season (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -101,7 +101,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated show (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -74,7 +74,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated studio (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -67,7 +67,7 @@ namespace Kyoo.Core.Controllers
{
await base.Create(obj);
_database.Entry(obj).State = EntityState.Added;
await _database.SaveChangesAsync($"Trying to insert a duplicated user (slug {obj.Slug} already exists).");
await _database.SaveChangesAsync(() => Get(obj.Slug));
return obj;
}

View File

@ -34,7 +34,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using IMetadataProvider = Kyoo.Abstractions.Controllers.IMetadataProvider;
using JsonOptions = Kyoo.Core.Api.JsonOptions;
@ -122,7 +121,10 @@ namespace Kyoo.Core
services.AddHttpContextAccessor();
services.AddTransient<IConfigureOptions<MvcNewtonsoftJsonOptions>, JsonOptions>();
services.AddMvcCore()
services.AddMvcCore(options =>
{
options.Filters.Add<ExceptionFilter>();
})
.AddNewtonsoftJson()
.AddDataAnnotations()
.AddControllersAsServices()
@ -156,16 +158,7 @@ namespace Kyoo.Core
/// <inheritdoc />
public IEnumerable<IStartupAction> ConfigureSteps => new IStartupAction[]
{
SA.New<IApplicationBuilder, IHostEnvironment>((app, env) =>
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
}, SA.Before),
SA.New<IApplicationBuilder>(app => app.UseHsts(), SA.Before),
SA.New<IApplicationBuilder>(app => app.UseResponseCompression(), SA.Routing + 1),
SA.New<IApplicationBuilder>(app => app.UseRouting(), SA.Routing),
SA.New<IApplicationBuilder>(app => app.UseEndpoints(x => x.MapControllers()), SA.Endpoint)

View File

@ -0,0 +1,80 @@
// 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 Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
namespace Kyoo.Core
{
/// <summary>
/// A middleware to handle errors globally.
/// </summary>
public class ExceptionFilter : IExceptionFilter
{
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionFilter"/> class.
/// </summary>
/// <param name="logger">The logger used to log errors.</param>
public ExceptionFilter(ILogger<ExceptionFilter> logger)
{
_logger = logger;
}
/// <inheritdoc/>
public void OnException(ExceptionContext context)
{
switch (context.Exception)
{
case ArgumentException ex:
context.Result = new BadRequestObjectResult(new RequestError(ex.Message));
break;
case ItemNotFoundException ex:
context.Result = new NotFoundObjectResult(new RequestError(ex.Message));
break;
case DuplicatedItemException ex:
context.Result = new ConflictObjectResult(ex.Existing);
break;
case Exception ex:
_logger.LogError("Unhandled error", ex);
context.Result = new ServerErrorObjectResult(new RequestError("Internal Server Error"));
break;
}
}
}
/// <inheritdoc />
public class ServerErrorObjectResult : ObjectResult
{
/// <summary>
/// Initializes a new instance of the <see cref="ServerErrorObjectResult"/> class.
/// </summary>
/// <param name="value">The object to return.</param>
public ServerErrorObjectResult(object value)
: base(value)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
}

View File

@ -16,11 +16,9 @@
// 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.Threading.Tasks;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models.Attributes;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -68,14 +66,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<object> GetConfiguration(string slug)
{
try
{
return _manager.GetValue(slug);
}
catch (ItemNotFoundException)
{
return NotFound();
}
return _manager.GetValue(slug);
}
/// <summary>
@ -95,19 +86,8 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<object>> EditConfiguration(string slug, [FromBody] object newValue)
{
try
{
await _manager.EditValue(slug, newValue);
return newValue;
}
catch (ItemNotFoundException)
{
return NotFound();
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}
await _manager.EditValue(slug, newValue);
return newValue;
}
}
}

View File

@ -20,7 +20,6 @@ using System;
using System.Collections.Generic;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models.Attributes;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
@ -90,19 +89,8 @@ namespace Kyoo.Core.Api
public IActionResult RunTask(string taskSlug,
[FromQuery] Dictionary<string, object> args)
{
try
{
_taskManager.StartTask(taskSlug, new Progress<float>(), args);
return Ok();
}
catch (ItemNotFoundException)
{
return NotFound();
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
_taskManager.StartTask(taskSlug, new Progress<float>(), args);
return Ok();
}
}
}

View File

@ -16,12 +16,10 @@
// 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.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;
@ -93,14 +91,7 @@ namespace Kyoo.Core.Api
[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));
}
return await Repository.GetCount(ApiHelper.ParseWhere<T>(where));
}
/// <summary>
@ -111,8 +102,7 @@ namespace Kyoo.Core.Api
/// </remarks>
/// <param name="sortBy">Sort information about the query (sort by, sort order).</param>
/// <param name="where">Filter the returned items.</param>
/// <param name="limit">How many items per page should be returned.</param>
/// <param name="afterID">Where the pagination should start.</param>
/// <param name="pagination">How many items per page should be returned, where should the page start...</param>
/// <returns>A list of resources that match every filters.</returns>
/// <response code="400">Invalid filters or sort information.</response>
[HttpGet]
@ -122,23 +112,15 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<T>>> GetAll(
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<T> resources = await Repository.GetAll(
ApiHelper.ParseWhere<T>(where),
Sort<T>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<T> resources = await Repository.GetAll(
ApiHelper.ParseWhere<T>(where),
Sort<T>.From(sortBy),
pagination
);
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
return Page(resources, pagination.Count);
}
/// <summary>
@ -158,19 +140,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status409Conflict, Type = typeof(ActionResult<>))]
public 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);
}
return await Repository.Create(resource);
}
/// <summary>
@ -191,19 +161,12 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<T>> Edit([FromBody] T resource)
{
try
{
if (resource.ID > 0)
return await Repository.Edit(resource, true);
T old = await Repository.Get(resource.Slug);
resource.ID = old.ID;
if (resource.ID > 0)
return await Repository.Edit(resource, true);
}
catch (ItemNotFoundException)
{
return NotFound();
}
T old = await Repository.Get(resource.Slug);
resource.ID = old.ID;
return await Repository.Edit(resource, true);
}
/// <summary>
@ -224,19 +187,12 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<T>> Patch([FromBody] T resource)
{
try
{
if (resource.ID > 0)
return await Repository.Edit(resource, false);
T old = await Repository.Get(resource.Slug);
resource.ID = old.ID;
if (resource.ID > 0)
return await Repository.Edit(resource, false);
}
catch (ItemNotFoundException)
{
return NotFound();
}
T old = await Repository.Get(resource.Slug);
resource.ID = old.ID;
return await Repository.Edit(resource, false);
}
/// <summary>
@ -254,18 +210,10 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Identifier identifier)
{
try
{
await identifier.Match(
id => Repository.Delete(id),
slug => Repository.Delete(slug)
);
}
catch (ItemNotFoundException)
{
return NotFound();
}
await identifier.Match(
id => Repository.Delete(id),
slug => Repository.Delete(slug)
);
return NoContent();
}
@ -284,15 +232,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(RequestError))]
public async Task<IActionResult> Delete([FromQuery] Dictionary<string, string> where)
{
try
{
await Repository.DeleteAll(ApiHelper.ParseWhere<T>(where));
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
await Repository.DeleteAll(ApiHelper.ParseWhere<T>(where));
return NoContent();
}
}

View File

@ -16,7 +16,6 @@
// 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;
@ -67,8 +66,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Genre"/>.</param>
/// <param name="sortBy">A key to sort shows by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of shows to return.</param>
/// <param name="afterID">An optional show's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of shows to return and where to start.</param>
/// <returns>A page of shows.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No genre with the given ID could be found.</response>
@ -81,25 +79,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Show>>> GetShows(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Genre>(x => x.Genres)),
Sort<Show>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Genre>(x => x.Genres)),
Sort<Show>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Genre>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Genre>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
}
}

View File

@ -23,7 +23,6 @@ using System.Threading.Tasks;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models;
using Kyoo.Abstractions.Models.Attributes;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
@ -73,8 +72,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the person.</param>
/// <param name="sortBy">A key to sort roles by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of roles to return.</param>
/// <param name="afterID">An optional role's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of roles to return.</param>
/// <returns>A page of roles.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No person with the given ID or slug could be found.</response>
@ -87,30 +85,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<PeopleRole>>> GetRoles(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
Expression<Func<PeopleRole, bool>> whereQuery = ApiHelper.ParseWhere<PeopleRole>(where);
Sort<PeopleRole> sort = Sort<PeopleRole>.From(sortBy);
Pagination pagination = new(limit, afterID);
Expression<Func<PeopleRole, bool>> whereQuery = ApiHelper.ParseWhere<PeopleRole>(where);
Sort<PeopleRole> sort = Sort<PeopleRole>.From(sortBy);
ICollection<PeopleRole> resources = await identifier.Match(
id => _libraryManager.GetRolesFromPeople(id, whereQuery, sort, pagination),
slug => _libraryManager.GetRolesFromPeople(slug, whereQuery, sort, pagination)
);
ICollection<PeopleRole> resources = await identifier.Match(
id => _libraryManager.GetRolesFromPeople(id, whereQuery, sort, pagination),
slug => _libraryManager.GetRolesFromPeople(slug, whereQuery, sort, pagination)
);
return Page(resources, limit);
}
catch (ItemNotFoundException)
{
return NotFound();
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
return Page(resources, pagination.Count);
}
}
}

View File

@ -67,8 +67,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Studio"/>.</param>
/// <param name="sortBy">A key to sort shows by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of shows to return.</param>
/// <param name="afterID">An optional show's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of shows to return.</param>
/// <returns>A page of shows.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No studio with the given ID or slug could be found.</response>
@ -81,25 +80,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Show>>> GetShows(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Show>(x => x.StudioID, x => x.Studio.Slug)),
Sort<Show>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Show>(x => x.StudioID, x => x.Studio.Slug)),
Sort<Show>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Studio>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Studio>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
}
}

View File

@ -16,7 +16,6 @@
// 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;
@ -71,8 +70,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Collection"/>.</param>
/// <param name="sortBy">A key to sort shows by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of shows to return.</param>
/// <param name="afterID">An optional show's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of shows to return.</param>
/// <returns>A page of shows.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No collection with the given ID could be found.</response>
@ -85,25 +83,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Show>>> GetShows(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Collection>(x => x.Collections)),
Sort<Show>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Collection>(x => x.Collections)),
Sort<Show>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Collection>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Collection>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -115,8 +105,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Collection"/>.</param>
/// <param name="sortBy">A key to sort libraries by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of libraries to return.</param>
/// <param name="afterID">An optional library's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of libraries to return.</param>
/// <returns>A page of libraries.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No collection with the given ID or slug could be found.</response>
@ -129,25 +118,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Library>>> GetLibraries(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Library> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Library, Collection>(x => x.Collections)),
Sort<Library>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Library> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Library, Collection>(x => x.Collections)),
Sort<Library>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Collection>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Collection>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
}
}

View File

@ -16,7 +16,6 @@
// 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;
@ -92,10 +91,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Show>> GetShow(Identifier identifier)
{
Show ret = await _libraryManager.GetOrDefault(identifier.IsContainedIn<Show, Episode>(x => x.Episodes));
if (ret == null)
return NotFound();
return ret;
return await _libraryManager.Get(identifier.IsContainedIn<Show, Episode>(x => x.Episodes));
}
/// <summary>
@ -138,8 +134,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Episode"/>.</param>
/// <param name="sortBy">A key to sort tracks by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of tracks to return.</param>
/// <param name="afterID">An optional track's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of tracks to return.</param>
/// <returns>A page of tracks.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No episode with the given ID or slug could be found.</response>
@ -153,24 +148,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Track>>> GetEpisode(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Track> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Track>(x => x.EpisodeID, x => x.Episode.Slug)),
Sort<Track>.From(sortBy),
new Pagination(limit, afterID));
ICollection<Track> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Track>(x => x.EpisodeID, x => x.Episode.Slug)),
Sort<Track>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Episode>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Episode>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
}
}

View File

@ -24,7 +24,6 @@ using System.Threading.Tasks;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models;
using Kyoo.Abstractions.Models.Attributes;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
@ -70,8 +69,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Library"/>.</param>
/// <param name="sortBy">A key to sort shows by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of shows to return.</param>
/// <param name="afterID">An optional show's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of shows to return.</param>
/// <returns>A page of shows.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No library with the given ID or slug could be found.</response>
@ -84,25 +82,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Show>>> GetShows(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 50,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Library>(x => x.Libraries)),
Sort<Show>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Show> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Show, Library>(x => x.Libraries)),
Sort<Show>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Library>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Library>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -114,8 +104,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Library"/>.</param>
/// <param name="sortBy">A key to sort collections by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of collections to return.</param>
/// <param name="afterID">An optional collection's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of collections to return.</param>
/// <returns>A page of collections.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No library with the given ID or slug could be found.</response>
@ -128,25 +117,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Collection>>> GetCollections(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 50,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Collection> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Collection, Library>(x => x.Libraries)),
Sort<Collection>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Collection> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Collection, Library>(x => x.Libraries)),
Sort<Collection>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Library>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Library>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -161,8 +142,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Library"/>.</param>
/// <param name="sortBy">A key to sort items by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of items to return.</param>
/// <param name="afterID">An optional item's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of items to return.</param>
/// <returns>A page of items.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No library with the given ID or slug could be found.</response>
@ -175,30 +155,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<LibraryItem>>> GetItems(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 50,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
Expression<Func<LibraryItem, bool>> whereQuery = ApiHelper.ParseWhere<LibraryItem>(where);
Sort<LibraryItem> sort = Sort<LibraryItem>.From(sortBy);
Pagination pagination = new(limit, afterID);
Expression<Func<LibraryItem, bool>> whereQuery = ApiHelper.ParseWhere<LibraryItem>(where);
Sort<LibraryItem> sort = Sort<LibraryItem>.From(sortBy);
ICollection<LibraryItem> resources = await identifier.Match(
id => _libraryManager.GetItemsFromLibrary(id, whereQuery, sort, pagination),
slug => _libraryManager.GetItemsFromLibrary(slug, whereQuery, sort, pagination)
);
ICollection<LibraryItem> resources = await identifier.Match(
id => _libraryManager.GetItemsFromLibrary(id, whereQuery, sort, pagination),
slug => _libraryManager.GetItemsFromLibrary(slug, whereQuery, sort, pagination)
);
return Page(resources, limit);
}
catch (ItemNotFoundException)
{
return NotFound();
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
return Page(resources, pagination.Count);
}
}
}

View File

@ -69,8 +69,7 @@ namespace Kyoo.Core.Api
/// </remarks>
/// <param name="sortBy">A key to sort items by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of items to return.</param>
/// <param name="afterID">An optional item's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of items to return.</param>
/// <returns>A page of items.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No library with the given ID or slug could be found.</response>
@ -82,23 +81,15 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<LibraryItem>>> GetAll(
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 50,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<LibraryItem> resources = await _libraryItems.GetAll(
ApiHelper.ParseWhere<LibraryItem>(where),
Sort<LibraryItem>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<LibraryItem> resources = await _libraryItems.GetAll(
ApiHelper.ParseWhere<LibraryItem>(where),
Sort<LibraryItem>.From(sortBy),
pagination
);
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
return Page(resources, pagination.Count);
}
}
}

View File

@ -16,7 +16,6 @@
// 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;
@ -71,8 +70,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Season"/>.</param>
/// <param name="sortBy">A key to sort episodes by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of episodes to return.</param>
/// <param name="afterID">An optional episode's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of episodes to return.</param>
/// <returns>A page of episodes.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No season with the given ID or slug could be found.</response>
@ -85,24 +83,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Episode>>> GetEpisode(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Episode> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Episode>(x => x.SeasonID, x => x.Season.Slug)),
Sort<Episode>.From(sortBy),
new Pagination(limit, afterID));
ICollection<Episode> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Episode>(x => x.SeasonID, x => x.Season.Slug)),
Sort<Episode>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Season>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Season>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>

View File

@ -24,7 +24,6 @@ using System.Threading.Tasks;
using Kyoo.Abstractions.Controllers;
using Kyoo.Abstractions.Models;
using Kyoo.Abstractions.Models.Attributes;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Abstractions.Models.Permissions;
using Kyoo.Abstractions.Models.Utils;
using Microsoft.AspNetCore.Http;
@ -75,8 +74,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort seasons by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of seasons to return.</param>
/// <param name="afterID">An optional season's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of seasons to return.</param>
/// <returns>A page of seasons.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -89,25 +87,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Season>>> GetSeasons(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 20,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Season> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Season>(x => x.ShowID, x => x.Show.Slug)),
Sort<Season>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Season> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Season>(x => x.ShowID, x => x.Show.Slug)),
Sort<Season>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -119,8 +109,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort episodes by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of episodes to return.</param>
/// <param name="afterID">An optional episode's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of episodes to return.</param>
/// <returns>A page of episodes.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -133,25 +122,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Episode>>> GetEpisodes(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 50,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Episode> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Episode>(x => x.ShowID, x => x.Show.Slug)),
Sort<Episode>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Episode> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.Matcher<Episode>(x => x.ShowID, x => x.Show.Slug)),
Sort<Episode>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -163,8 +144,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort staff members by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of people to return.</param>
/// <param name="afterID">An optional person's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of people to return.</param>
/// <returns>A page of people.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -177,29 +157,16 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<PeopleRole>>> GetPeople(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
Expression<Func<PeopleRole, bool>> whereQuery = ApiHelper.ParseWhere<PeopleRole>(where);
Sort<PeopleRole> sort = Sort<PeopleRole>.From(sortBy);
Pagination pagination = new(limit, afterID);
Expression<Func<PeopleRole, bool>> whereQuery = ApiHelper.ParseWhere<PeopleRole>(where);
Sort<PeopleRole> sort = Sort<PeopleRole>.From(sortBy);
ICollection<PeopleRole> resources = await identifier.Match(
id => _libraryManager.GetPeopleFromShow(id, whereQuery, sort, pagination),
slug => _libraryManager.GetPeopleFromShow(slug, whereQuery, sort, pagination)
);
return Page(resources, limit);
}
catch (ItemNotFoundException)
{
return NotFound();
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
ICollection<PeopleRole> resources = await identifier.Match(
id => _libraryManager.GetPeopleFromShow(id, whereQuery, sort, pagination),
slug => _libraryManager.GetPeopleFromShow(slug, whereQuery, sort, pagination)
);
return Page(resources, pagination.Count);
}
/// <summary>
@ -211,8 +178,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort genres by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of genres to return.</param>
/// <param name="afterID">An optional genre's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of genres to return.</param>
/// <returns>A page of genres.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -225,25 +191,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Genre>>> GetGenres(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Genre> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Genre, Show>(x => x.Shows)),
Sort<Genre>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Genre> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Genre, Show>(x => x.Shows)),
Sort<Genre>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -261,10 +219,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Studio>> GetStudio(Identifier identifier)
{
Studio studio = await _libraryManager.GetOrDefault(identifier.IsContainedIn<Studio, Show>(x => x.Shows));
if (studio == null)
return NotFound();
return studio;
return await _libraryManager.Get(identifier.IsContainedIn<Studio, Show>(x => x.Shows));
}
/// <summary>
@ -277,8 +232,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort libraries by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of libraries to return.</param>
/// <param name="afterID">An optional library's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of libraries to return.</param>
/// <returns>A page of libraries.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -291,25 +245,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Library>>> GetLibraries(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Library> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Library, Show>(x => x.Shows)),
Sort<Library>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Library> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Library, Show>(x => x.Shows)),
Sort<Library>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
/// <summary>
@ -321,8 +267,7 @@ namespace Kyoo.Core.Api
/// <param name="identifier">The ID or slug of the <see cref="Show"/>.</param>
/// <param name="sortBy">A key to sort collections by.</param>
/// <param name="where">An optional list of filters.</param>
/// <param name="limit">The number of collections to return.</param>
/// <param name="afterID">An optional collection's ID to start the query from this specific item.</param>
/// <param name="pagination">The number of collections to return.</param>
/// <returns>A page of collections.</returns>
/// <response code="400">The filters or the sort parameters are invalid.</response>
/// <response code="404">No show with the given ID or slug could be found.</response>
@ -335,25 +280,17 @@ namespace Kyoo.Core.Api
public async Task<ActionResult<Page<Collection>>> GetCollections(Identifier identifier,
[FromQuery] string sortBy,
[FromQuery] Dictionary<string, string> where,
[FromQuery] int limit = 30,
[FromQuery] int? afterID = null)
[FromQuery] Pagination pagination)
{
try
{
ICollection<Collection> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Collection, Show>(x => x.Shows)),
Sort<Collection>.From(sortBy),
new Pagination(limit, afterID)
);
ICollection<Collection> resources = await _libraryManager.GetAll(
ApiHelper.ParseWhere(where, identifier.IsContainedIn<Collection, Show>(x => x.Shows)),
Sort<Collection>.From(sortBy),
pagination
);
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, limit);
}
catch (ArgumentException ex)
{
return BadRequest(new RequestError(ex.Message));
}
if (!resources.Any() && await _libraryManager.GetOrDefault(identifier.IsSame<Show>()) == null)
return NotFound();
return Page(resources, pagination.Count);
}
}
}

View File

@ -72,10 +72,7 @@ namespace Kyoo.Core.Api
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Episode>> GetEpisode(Identifier identifier)
{
Episode ret = await _libraryManager.GetOrDefault(identifier.IsContainedIn<Episode, Track>(x => x.Tracks));
if (ret == null)
return NotFound();
return ret;
return await _libraryManager.Get(identifier.IsContainedIn<Episode, Track>(x => x.Tracks));
}
}
}

View File

@ -421,28 +421,6 @@ namespace Kyoo.Database
}
}
/// <summary>
/// Save changes that are applied to this context.
/// </summary>
/// <param name="duplicateMessage">The message that will have the <see cref="DuplicatedItemException"/>
/// (if a duplicate is found).</param>
/// <exception cref="DuplicatedItemException">A duplicated item has been found.</exception>
/// <returns>The number of state entries written to the database.</returns>
public int SaveChanges(string duplicateMessage)
{
try
{
return base.SaveChanges();
}
catch (DbUpdateException ex)
{
DiscardChanges();
if (IsDuplicateException(ex))
throw new DuplicatedItemException(duplicateMessage);
throw;
}
}
/// <summary>
/// Save changes that are applied to this context.
/// </summary>
@ -491,12 +469,13 @@ namespace Kyoo.Database
/// <summary>
/// Save changes that are applied to this context.
/// </summary>
/// <param name="duplicateMessage">The message that will have the <see cref="DuplicatedItemException"/>
/// (if a duplicate is found).</param>
/// <param name="getExisting">How to retrieve the conflicting item.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for the task to complete</param>
/// <exception cref="DuplicatedItemException">A duplicated item has been found.</exception>
/// <typeparam name="T">The type of the potential duplicate (this is unused).</typeparam>
/// <returns>The number of state entries written to the database.</returns>
public async Task<int> SaveChangesAsync(string duplicateMessage,
public async Task<int> SaveChangesAsync<T>(
Func<Task<T>> getExisting,
CancellationToken cancellationToken = default)
{
try
@ -507,7 +486,7 @@ namespace Kyoo.Database
{
DiscardChanges();
if (IsDuplicateException(ex))
throw new DuplicatedItemException(duplicateMessage);
throw new DuplicatedItemException(await getExisting());
throw;
}
}