From 1180b9746fe7c4a6562baff77910819a6706510b Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 15 Apr 2020 00:01:31 -0600 Subject: [PATCH 01/39] Migrates the notifications service to use ASP.NET MVC framework --- .../Api/NotificationsService.cs | 189 ------------------ .../Controllers/NotificationsController.cs | 138 +++++++++++++ .../NotificationDtos/NotificationDto.cs | 51 +++++ .../NotificationsSummaryDto.cs | 20 ++ .../ApiServiceCollectionExtensions.cs | 1 + 5 files changed, 210 insertions(+), 189 deletions(-) delete mode 100644 Emby.Notifications/Api/NotificationsService.cs create mode 100644 Jellyfin.Api/Controllers/NotificationsController.cs create mode 100644 Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs create mode 100644 Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs deleted file mode 100644 index 788750796d..0000000000 --- a/Emby.Notifications/Api/NotificationsService.cs +++ /dev/null @@ -1,189 +0,0 @@ -#pragma warning disable CS1591 -#pragma warning disable SA1402 -#pragma warning disable SA1649 - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Notifications; -using MediaBrowser.Model.Services; - -namespace Emby.Notifications.Api -{ - [Route("/Notifications/{UserId}", "GET", Summary = "Gets notifications")] - public class GetNotifications : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } = string.Empty; - - [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] - public bool? IsRead { get; set; } - - [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? StartIndex { get; set; } - - [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? Limit { get; set; } - } - - public class Notification - { - public string Id { get; set; } = string.Empty; - - public string UserId { get; set; } = string.Empty; - - public DateTime Date { get; set; } - - public bool IsRead { get; set; } - - public string Name { get; set; } = string.Empty; - - public string Description { get; set; } = string.Empty; - - public string Url { get; set; } = string.Empty; - - public NotificationLevel Level { get; set; } - } - - public class NotificationResult - { - public IReadOnlyList Notifications { get; set; } = Array.Empty(); - - public int TotalRecordCount { get; set; } - } - - public class NotificationsSummary - { - public int UnreadCount { get; set; } - - public NotificationLevel MaxUnreadNotificationLevel { get; set; } - } - - [Route("/Notifications/{UserId}/Summary", "GET", Summary = "Gets a notification summary for a user")] - public class GetNotificationsSummary : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } = string.Empty; - } - - [Route("/Notifications/Types", "GET", Summary = "Gets notification types")] - public class GetNotificationTypes : IReturn> - { - } - - [Route("/Notifications/Services", "GET", Summary = "Gets notification types")] - public class GetNotificationServices : IReturn> - { - } - - [Route("/Notifications/Admin", "POST", Summary = "Sends a notification to all admin users")] - public class AddAdminNotification : IReturnVoid - { - [ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Name { get; set; } = string.Empty; - - [ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Description { get; set; } = string.Empty; - - [ApiMember(Name = "ImageUrl", Description = "The notification's image url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string? ImageUrl { get; set; } - - [ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string? Url { get; set; } - - [ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public NotificationLevel Level { get; set; } - } - - [Route("/Notifications/{UserId}/Read", "POST", Summary = "Marks notifications as read")] - public class MarkRead : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } = string.Empty; - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } = string.Empty; - } - - [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")] - public class MarkUnread : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } = string.Empty; - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } = string.Empty; - } - - [Authenticated] - public class NotificationsService : IService - { - private readonly INotificationManager _notificationManager; - private readonly IUserManager _userManager; - - public NotificationsService(INotificationManager notificationManager, IUserManager userManager) - { - _notificationManager = notificationManager; - _userManager = userManager; - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public object Get(GetNotificationTypes request) - { - return _notificationManager.GetNotificationTypes(); - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public object Get(GetNotificationServices request) - { - return _notificationManager.GetNotificationServices().ToList(); - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public object Get(GetNotificationsSummary request) - { - return new NotificationsSummary - { - }; - } - - public Task Post(AddAdminNotification request) - { - // This endpoint really just exists as post of a real with sickbeard - var notification = new NotificationRequest - { - Date = DateTime.UtcNow, - Description = request.Description, - Level = request.Level, - Name = request.Name, - Url = request.Url, - UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray() - }; - - return _notificationManager.SendNotification(notification, CancellationToken.None); - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public void Post(MarkRead request) - { - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public void Post(MarkUnread request) - { - } - - [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")] - public object Get(GetNotifications request) - { - return new NotificationResult(); - } - } -} diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs new file mode 100644 index 0000000000..6602fca9c7 --- /dev/null +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -0,0 +1,138 @@ +#nullable enable +#pragma warning disable CA1801 +#pragma warning disable SA1313 + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Jellyfin.Api.Models.NotificationDtos; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Notifications; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Notifications; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api.Controllers +{ + /// + /// The notification controller. + /// + public class NotificationsController : BaseJellyfinApiController + { + private readonly INotificationManager _notificationManager; + private readonly IUserManager _userManager; + + /// + /// Initializes a new instance of the class. + /// + /// The notification manager. + /// The user manager. + public NotificationsController(INotificationManager notificationManager, IUserManager userManager) + { + _notificationManager = notificationManager; + _userManager = userManager; + } + + /// + /// Endpoint for getting a user's notifications. + /// + /// The UserID. + /// An optional filter by IsRead. + /// The optional index to start at. All notifications with a lower index will be dropped from the results. + /// An optional limit on the number of notifications returned. + /// A read-only list of all of the user's notifications. + [HttpGet("{UserID}")] + public IReadOnlyList GetNotifications( + [FromRoute] string UserID, + [FromQuery] bool? IsRead, + [FromQuery] int? StartIndex, + [FromQuery] int? Limit) + { + return new List(); + } + + /// + /// Endpoint for getting a user's notification summary. + /// + /// The UserID. + /// Notifications summary for the user. + [HttpGet("{UserId}/Summary")] + public NotificationsSummaryDto GetNotificationsSummary( + [FromRoute] string UserID) + { + return new NotificationsSummaryDto(); + } + + /// + /// Endpoint for getting notification types. + /// + /// All notification types. + [HttpGet("Types")] + public IEnumerable GetNotificationTypes() + { + return _notificationManager.GetNotificationTypes(); + } + + /// + /// Endpoint for getting notification services. + /// + /// All notification services. + [HttpGet("Services")] + public IEnumerable GetNotificationServices() + { + return _notificationManager.GetNotificationServices(); + } + + /// + /// Endpoint to send a notification to all admins. + /// + /// The name of the notification. + /// The description of the notification. + /// The URL of the notification. + /// The level of the notification. + [HttpPost("Admin")] + public void CreateAdminNotification( + [FromForm] string Name, + [FromForm] string Description, + [FromForm] string? URL, + [FromForm] NotificationLevel Level) + { + var notification = new NotificationRequest + { + Name = Name, + Description = Description, + Url = URL, + Level = Level, + UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), + Date = DateTime.UtcNow, + }; + + _notificationManager.SendNotification(notification, CancellationToken.None); + } + + /// + /// Endpoint to set notifications as read. + /// + /// The UserID. + /// The IDs of notifications which should be set as read. + [HttpPost("{UserID}/Read")] + public void SetRead( + [FromRoute] string UserID, + [FromForm] List IDs) + { + } + + /// + /// Endpoint to set notifications as unread. + /// + /// The UserID. + /// The IDs of notifications which should be set as unread. + [HttpPost("{UserID}/Unread")] + public void SetUnread( + [FromRoute] string UserID, + [FromForm] List IDs) + { + } + } +} diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs new file mode 100644 index 0000000000..7ecd2a49db --- /dev/null +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs @@ -0,0 +1,51 @@ +using System; +using MediaBrowser.Model.Notifications; + +namespace Jellyfin.Api.Models.NotificationDtos +{ + /// + /// The notification DTO. + /// + public class NotificationDto + { + /// + /// Gets or sets the notification ID. Defaults to an empty string. + /// + public string Id { get; set; } = string.Empty; + + /// + /// Gets or sets the notification's user ID. Defaults to an empty string. + /// + public string UserId { get; set; } = string.Empty; + + /// + /// Gets or sets the notification date. + /// + public DateTime Date { get; set; } + + /// + /// Gets or sets a value indicating whether the notification has been read. + /// + public bool IsRead { get; set; } + + /// + /// Gets or sets the notification's name. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the notification's description. + /// + public string Description { get; set; } = string.Empty; + + /// + /// Gets or sets the notification's URL. + /// + public string Url { get; set; } = string.Empty; + + /// + /// Gets or sets the notification level. + /// + public NotificationLevel Level { get; set; } + } +} diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs new file mode 100644 index 0000000000..c18ab545d3 --- /dev/null +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs @@ -0,0 +1,20 @@ +using MediaBrowser.Model.Notifications; + +namespace Jellyfin.Api.Models.NotificationDtos +{ + /// + /// The notification summary DTO. + /// + public class NotificationsSummaryDto + { + /// + /// Gets or sets the number of unread notifications. + /// + public int UnreadCount { get; set; } + + /// + /// Gets or sets the maximum unread notification level. + /// + public NotificationLevel MaxUnreadNotificationLevel { get; set; } + } +} diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index dd4f9cd238..b3164e068f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -71,6 +71,7 @@ namespace Jellyfin.Server.Extensions // Clear app parts to avoid other assemblies being picked up .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear()) .AddApplicationPart(typeof(StartupController).Assembly) + .AddApplicationPart(typeof(NotificationsController).Assembly) .AddControllersAsServices(); } From ad1c880751dda93f1226e3846bb6a344ac58d0b6 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 15 Apr 2020 00:34:50 -0600 Subject: [PATCH 02/39] Lowercase parameters --- .../Controllers/NotificationsController.cs | 63 +++++++++---------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 6602fca9c7..31747584e1 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -1,6 +1,5 @@ #nullable enable #pragma warning disable CA1801 -#pragma warning disable SA1313 using System; using System.Collections.Generic; @@ -37,17 +36,17 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint for getting a user's notifications. /// - /// The UserID. - /// An optional filter by IsRead. - /// The optional index to start at. All notifications with a lower index will be dropped from the results. - /// An optional limit on the number of notifications returned. + /// The UserID. + /// An optional filter by IsRead. + /// The optional index to start at. All notifications with a lower index will be dropped from the results. + /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] public IReadOnlyList GetNotifications( - [FromRoute] string UserID, - [FromQuery] bool? IsRead, - [FromQuery] int? StartIndex, - [FromQuery] int? Limit) + [FromRoute] string userID, + [FromQuery] bool? isRead, + [FromQuery] int? startIndex, + [FromQuery] int? limit) { return new List(); } @@ -55,11 +54,11 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint for getting a user's notification summary. /// - /// The UserID. + /// The userID. /// Notifications summary for the user. - [HttpGet("{UserId}/Summary")] + [HttpGet("{UserID}/Summary")] public NotificationsSummaryDto GetNotificationsSummary( - [FromRoute] string UserID) + [FromRoute] string userID) { return new NotificationsSummaryDto(); } @@ -87,23 +86,23 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint to send a notification to all admins. /// - /// The name of the notification. - /// The description of the notification. - /// The URL of the notification. - /// The level of the notification. + /// The name of the notification. + /// The description of the notification. + /// The URL of the notification. + /// The level of the notification. [HttpPost("Admin")] public void CreateAdminNotification( - [FromForm] string Name, - [FromForm] string Description, - [FromForm] string? URL, - [FromForm] NotificationLevel Level) + [FromForm] string name, + [FromForm] string description, + [FromForm] string? url, + [FromForm] NotificationLevel level) { var notification = new NotificationRequest { - Name = Name, - Description = Description, - Url = URL, - Level = Level, + Name = name, + Description = description, + Url = url, + Level = level, UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), Date = DateTime.UtcNow, }; @@ -114,24 +113,24 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint to set notifications as read. /// - /// The UserID. - /// The IDs of notifications which should be set as read. + /// The userID. + /// The IDs of notifications which should be set as read. [HttpPost("{UserID}/Read")] public void SetRead( - [FromRoute] string UserID, - [FromForm] List IDs) + [FromRoute] string userID, + [FromForm] List ids) { } /// /// Endpoint to set notifications as unread. /// - /// The UserID. - /// The IDs of notifications which should be set as unread. + /// The userID. + /// The IDs of notifications which should be set as unread. [HttpPost("{UserID}/Unread")] public void SetUnread( - [FromRoute] string UserID, - [FromForm] List IDs) + [FromRoute] string userID, + [FromForm] List ids) { } } From 558b50a094adc82728a52b13862e19bc04783679 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 15 Apr 2020 09:29:29 -0600 Subject: [PATCH 03/39] Remove unnecessary assembly, update casing, enable nullable reference types on notification DTOs. --- .../Controllers/NotificationsController.cs | 20 +++++++++---------- .../NotificationDtos/NotificationDto.cs | 16 ++++++++------- .../NotificationsSummaryDto.cs | 4 +++- .../ApiServiceCollectionExtensions.cs | 1 - 4 files changed, 22 insertions(+), 19 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 31747584e1..c8a5be89b3 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -36,14 +36,14 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint for getting a user's notifications. /// - /// The UserID. + /// The user's ID. /// An optional filter by IsRead. /// The optional index to start at. All notifications with a lower index will be dropped from the results. /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] public IReadOnlyList GetNotifications( - [FromRoute] string userID, + [FromRoute] string userId, [FromQuery] bool? isRead, [FromQuery] int? startIndex, [FromQuery] int? limit) @@ -54,11 +54,11 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint for getting a user's notification summary. /// - /// The userID. + /// The user's ID. /// Notifications summary for the user. [HttpGet("{UserID}/Summary")] public NotificationsSummaryDto GetNotificationsSummary( - [FromRoute] string userID) + [FromRoute] string userId) { return new NotificationsSummaryDto(); } @@ -95,14 +95,14 @@ namespace Jellyfin.Api.Controllers [FromForm] string name, [FromForm] string description, [FromForm] string? url, - [FromForm] NotificationLevel level) + [FromForm] NotificationLevel? level) { var notification = new NotificationRequest { Name = name, Description = description, Url = url, - Level = level, + Level = level ?? NotificationLevel.Normal, UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), Date = DateTime.UtcNow, }; @@ -113,11 +113,11 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint to set notifications as read. /// - /// The userID. + /// The userID. /// The IDs of notifications which should be set as read. [HttpPost("{UserID}/Read")] public void SetRead( - [FromRoute] string userID, + [FromRoute] string userId, [FromForm] List ids) { } @@ -125,11 +125,11 @@ namespace Jellyfin.Api.Controllers /// /// Endpoint to set notifications as unread. /// - /// The userID. + /// The userID. /// The IDs of notifications which should be set as unread. [HttpPost("{UserID}/Unread")] public void SetUnread( - [FromRoute] string userID, + [FromRoute] string userId, [FromForm] List ids) { } diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs index 7ecd2a49db..c849ecd75d 100644 --- a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs @@ -1,3 +1,5 @@ +#nullable enable + using System; using MediaBrowser.Model.Notifications; @@ -24,28 +26,28 @@ namespace Jellyfin.Api.Models.NotificationDtos public DateTime Date { get; set; } /// - /// Gets or sets a value indicating whether the notification has been read. + /// Gets or sets a value indicating whether the notification has been read. Defaults to false. /// - public bool IsRead { get; set; } + public bool IsRead { get; set; } = false; /// - /// Gets or sets the notification's name. + /// Gets or sets the notification's name. Defaults to an empty string. /// public string Name { get; set; } = string.Empty; /// - /// Gets or sets the notification's description. + /// Gets or sets the notification's description. Defaults to an empty string. /// public string Description { get; set; } = string.Empty; /// - /// Gets or sets the notification's URL. + /// Gets or sets the notification's URL. Defaults to null. /// - public string Url { get; set; } = string.Empty; + public string? Url { get; set; } /// /// Gets or sets the notification level. /// - public NotificationLevel Level { get; set; } + public NotificationLevel? Level { get; set; } } } diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs index c18ab545d3..b3746ee2da 100644 --- a/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationsSummaryDto.cs @@ -1,3 +1,5 @@ +#nullable enable + using MediaBrowser.Model.Notifications; namespace Jellyfin.Api.Models.NotificationDtos @@ -15,6 +17,6 @@ namespace Jellyfin.Api.Models.NotificationDtos /// /// Gets or sets the maximum unread notification level. /// - public NotificationLevel MaxUnreadNotificationLevel { get; set; } + public NotificationLevel? MaxUnreadNotificationLevel { get; set; } } } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index b3164e068f..dd4f9cd238 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -71,7 +71,6 @@ namespace Jellyfin.Server.Extensions // Clear app parts to avoid other assemblies being picked up .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear()) .AddApplicationPart(typeof(StartupController).Assembly) - .AddApplicationPart(typeof(NotificationsController).Assembly) .AddControllersAsServices(); } From 8a7e4cd639be24eb58385dc7b36b466c3d6aed92 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 10:51:51 -0600 Subject: [PATCH 04/39] add redoc --- Jellyfin.Api/Jellyfin.Api.csproj | 3 ++- .../ApiApplicationBuilderExtensions.cs | 16 ++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 8f23ef9d03..cbb1d3007f 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -10,7 +10,8 @@ - + + diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index db06eb4552..2ab9b0ba5e 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -14,14 +14,18 @@ namespace Jellyfin.Server.Extensions /// The updated application builder. public static IApplicationBuilder UseJellyfinApiSwagger(this IApplicationBuilder applicationBuilder) { - applicationBuilder.UseSwagger(); - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. - return applicationBuilder.UseSwaggerUI(c => - { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jellyfin API V1"); - }); + const string specEndpoint = "/swagger/v1/swagger.json"; + return applicationBuilder.UseSwagger() + .UseSwaggerUI(c => + { + c.SwaggerEndpoint(specEndpoint, "Jellyfin API V1"); + }) + .UseReDoc(c => + { + c.SpecUrl(specEndpoint); + }); } } } From e72a543570b59df61f48cb9a4049ab3dc9675250 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 11:24:03 -0600 Subject: [PATCH 05/39] Add Redoc, move docs to api-docs/ --- Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 2ab9b0ba5e..766243f201 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -21,10 +21,12 @@ namespace Jellyfin.Server.Extensions .UseSwaggerUI(c => { c.SwaggerEndpoint(specEndpoint, "Jellyfin API V1"); + c.RoutePrefix = "api-docs/swagger"; }) .UseReDoc(c => { c.SpecUrl(specEndpoint); + c.RoutePrefix = "api-docs/redoc"; }); } } From 5da88fac4d0681126bdee635d59237d8d7fcebeb Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 11:24:32 -0600 Subject: [PATCH 06/39] Enable string enum converter --- .../ApiServiceCollectionExtensions.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 71ef9a69a2..a4f078b5b3 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -1,3 +1,8 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json.Serialization; using Jellyfin.Api; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy; @@ -75,6 +80,9 @@ namespace Jellyfin.Server.Extensions { // Setting the naming policy to null leaves the property names as-is when serializing objects to JSON. options.JsonSerializerOptions.PropertyNamingPolicy = null; + + // Accept string enums + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }) .AddControllersAsServices(); } @@ -89,6 +97,17 @@ namespace Jellyfin.Server.Extensions return serviceCollection.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" }); + + // Add all xml doc files to swagger generator. + var xmlFiles = Directory.GetFiles( + AppContext.BaseDirectory, + "*.xml", + SearchOption.TopDirectoryOnly); + + foreach (var xmlFile in xmlFiles) + { + c.IncludeXmlComments(xmlFile); + } }); } } From 72745f47225a5b1071660acc4dcde618d938eaa0 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 11:28:56 -0600 Subject: [PATCH 07/39] fix formatting --- Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 766243f201..43c49307d4 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -17,7 +17,8 @@ namespace Jellyfin.Server.Extensions // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. const string specEndpoint = "/swagger/v1/swagger.json"; - return applicationBuilder.UseSwagger() + return applicationBuilder + .UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint(specEndpoint, "Jellyfin API V1"); From 7c8188194b5bf9b74413f25d471a212f1677f7ed Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Sun, 19 Apr 2020 13:19:15 -0600 Subject: [PATCH 08/39] Address PR comments, and revert changes that changed the API schema --- .../Controllers/NotificationsController.cs | 20 +++++++++--------- .../NotificationDtos/NotificationDto.cs | 6 +++--- .../NotificationDtos/NotificationResultDto.cs | 21 +++++++++++++++++++ 3 files changed, 34 insertions(+), 13 deletions(-) create mode 100644 Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index c8a5be89b3..d9a5c5e316 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -42,13 +42,13 @@ namespace Jellyfin.Api.Controllers /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] - public IReadOnlyList GetNotifications( + public NotificationResultDto GetNotifications( [FromRoute] string userId, [FromQuery] bool? isRead, [FromQuery] int? startIndex, [FromQuery] int? limit) { - return new List(); + return new NotificationResultDto(); } /// @@ -92,10 +92,10 @@ namespace Jellyfin.Api.Controllers /// The level of the notification. [HttpPost("Admin")] public void CreateAdminNotification( - [FromForm] string name, - [FromForm] string description, - [FromForm] string? url, - [FromForm] NotificationLevel? level) + [FromQuery] string name, + [FromQuery] string description, + [FromQuery] string? url, + [FromQuery] NotificationLevel? level) { var notification = new NotificationRequest { @@ -114,11 +114,11 @@ namespace Jellyfin.Api.Controllers /// Endpoint to set notifications as read. /// /// The userID. - /// The IDs of notifications which should be set as read. + /// A comma-separated list of the IDs of notifications which should be set as read. [HttpPost("{UserID}/Read")] public void SetRead( [FromRoute] string userId, - [FromForm] List ids) + [FromQuery] string ids) { } @@ -126,11 +126,11 @@ namespace Jellyfin.Api.Controllers /// Endpoint to set notifications as unread. /// /// The userID. - /// The IDs of notifications which should be set as unread. + /// A comma-separated list of the IDs of notifications which should be set as unread. [HttpPost("{UserID}/Unread")] public void SetUnread( [FromRoute] string userId, - [FromForm] List ids) + [FromQuery] string ids) { } } diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs index c849ecd75d..502b22623b 100644 --- a/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationDto.cs @@ -41,13 +41,13 @@ namespace Jellyfin.Api.Models.NotificationDtos public string Description { get; set; } = string.Empty; /// - /// Gets or sets the notification's URL. Defaults to null. + /// Gets or sets the notification's URL. Defaults to an empty string. /// - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the notification level. /// - public NotificationLevel? Level { get; set; } + public NotificationLevel Level { get; set; } } } diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs new file mode 100644 index 0000000000..64e92bd83a --- /dev/null +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Api.Models.NotificationDtos +{ + /// + /// A list of notifications with the total record count for pagination. + /// + public class NotificationResultDto + { + /// + /// Gets or sets the current page of notifications. + /// + public IReadOnlyList Notifications { get; set; } = Array.Empty(); + + /// + /// Gets or sets the total number of notifications. + /// + public int TotalRecordCount { get; set; } + } +} From ad67081840ec61085673634795d0b6363f649dbf Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 18:04:36 -0600 Subject: [PATCH 09/39] add camelCase formatter --- .../CamelCaseJsonProfileFormatter.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs diff --git a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs new file mode 100644 index 0000000000..433a3197d3 --- /dev/null +++ b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Formatters; +using Microsoft.Net.Http.Headers; + +namespace Jellyfin.Server.Formatters +{ + /// + /// Camel Case Json Profile Formatter. + /// + public class CamelCaseJsonProfileFormatter : SystemTextJsonOutputFormatter + { + /// + /// Initializes a new instance of the class. + /// + public CamelCaseJsonProfileFormatter() : base(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) + { + SupportedMediaTypes.Clear(); + SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=\"CamelCase\"")); + } + } +} From c89dc8921ffb0ce11031e9cfb096b525d94e21b3 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 19 Apr 2020 18:10:59 -0600 Subject: [PATCH 10/39] Fix PascalCase --- .../ApiServiceCollectionExtensions.cs | 3 +++ .../PascalCaseJsonProfileFormatter.cs | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 71ef9a69a2..00688074f0 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy; using Jellyfin.Api.Auth.RequiresElevationPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; +using Jellyfin.Server.Formatters; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; @@ -66,6 +67,8 @@ namespace Jellyfin.Server.Extensions return serviceCollection.AddMvc(opts => { opts.UseGeneralRoutePrefix(baseUrl); + opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter()); + opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter()); }) // Clear app parts to avoid other assemblies being picked up diff --git a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs new file mode 100644 index 0000000000..2ed006a336 --- /dev/null +++ b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs @@ -0,0 +1,23 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Formatters; +using Microsoft.Net.Http.Headers; + +namespace Jellyfin.Server.Formatters +{ + /// + /// Pascal Case Json Profile Formatter. + /// + public class PascalCaseJsonProfileFormatter : SystemTextJsonOutputFormatter + { + /// + /// Initializes a new instance of the class. + /// + public PascalCaseJsonProfileFormatter() : base(new JsonSerializerOptions { PropertyNamingPolicy = null }) + { + SupportedMediaTypes.Clear(); + // Add application/json for default formatter + SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json")); + SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=\"PascalCase\"")); + } + } +} From 16cae23bbee14a7398d39014973b1a476e1ca57c Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Sun, 19 Apr 2020 21:06:28 -0600 Subject: [PATCH 11/39] Add response type annotations, return IActionResult to handle errors --- .../Controllers/NotificationsController.cs | 79 ++++++++++++++----- 1 file changed, 59 insertions(+), 20 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index d9a5c5e316..76b025fa16 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Notifications; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Api.Controllers @@ -42,13 +43,14 @@ namespace Jellyfin.Api.Controllers /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] - public NotificationResultDto GetNotifications( + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public IActionResult GetNotifications( [FromRoute] string userId, [FromQuery] bool? isRead, [FromQuery] int? startIndex, [FromQuery] int? limit) { - return new NotificationResultDto(); + return Ok(new NotificationResultDto()); } /// @@ -57,10 +59,11 @@ namespace Jellyfin.Api.Controllers /// The user's ID. /// Notifications summary for the user. [HttpGet("{UserID}/Summary")] - public NotificationsSummaryDto GetNotificationsSummary( + [ProducesResponseType(typeof(NotificationsSummaryDto), StatusCodes.Status200OK)] + public IActionResult GetNotificationsSummary( [FromRoute] string userId) { - return new NotificationsSummaryDto(); + return Ok(new NotificationsSummaryDto()); } /// @@ -68,9 +71,18 @@ namespace Jellyfin.Api.Controllers /// /// All notification types. [HttpGet("Types")] - public IEnumerable GetNotificationTypes() + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] + public IActionResult GetNotificationTypes() { - return _notificationManager.GetNotificationTypes(); + try + { + return Ok(_notificationManager.GetNotificationTypes()); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } } /// @@ -78,9 +90,18 @@ namespace Jellyfin.Api.Controllers /// /// All notification services. [HttpGet("Services")] - public IEnumerable GetNotificationServices() + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] + public IActionResult GetNotificationServices() { - return _notificationManager.GetNotificationServices(); + try + { + return Ok(_notificationManager.GetNotificationServices()); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } } /// @@ -90,24 +111,36 @@ namespace Jellyfin.Api.Controllers /// The description of the notification. /// The URL of the notification. /// The level of the notification. + /// Status. [HttpPost("Admin")] - public void CreateAdminNotification( + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] + public IActionResult CreateAdminNotification( [FromQuery] string name, [FromQuery] string description, [FromQuery] string? url, [FromQuery] NotificationLevel? level) { - var notification = new NotificationRequest + try { - Name = name, - Description = description, - Url = url, - Level = level ?? NotificationLevel.Normal, - UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), - Date = DateTime.UtcNow, - }; + var notification = new NotificationRequest + { + Name = name, + Description = description, + Url = url, + Level = level ?? NotificationLevel.Normal, + UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), + Date = DateTime.UtcNow, + }; - _notificationManager.SendNotification(notification, CancellationToken.None); + _notificationManager.SendNotification(notification, CancellationToken.None); + + return Ok(); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } } /// @@ -115,11 +148,14 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as read. + /// Status. [HttpPost("{UserID}/Read")] - public void SetRead( + [ProducesResponseType(StatusCodes.Status200OK)] + public IActionResult SetRead( [FromRoute] string userId, [FromQuery] string ids) { + return Ok(); } /// @@ -127,11 +163,14 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as unread. + /// Status. [HttpPost("{UserID}/Unread")] - public void SetUnread( + [ProducesResponseType(StatusCodes.Status200OK)] + public IActionResult SetUnread( [FromRoute] string userId, [FromQuery] string ids) { + return Ok(); } } } From 688240151bae0f333cd329572b3774954d13ebae Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Mon, 20 Apr 2020 00:00:00 -0600 Subject: [PATCH 12/39] Enable nullable reference types on new class, remove unnecessary documenation and return types --- Jellyfin.Api/Controllers/NotificationsController.cs | 11 ++--------- .../Models/NotificationDtos/NotificationResultDto.cs | 2 ++ 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 76b025fa16..c0c2be626b 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -72,7 +72,6 @@ namespace Jellyfin.Api.Controllers /// All notification types. [HttpGet("Types")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] public IActionResult GetNotificationTypes() { try @@ -91,7 +90,6 @@ namespace Jellyfin.Api.Controllers /// All notification services. [HttpGet("Services")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] public IActionResult GetNotificationServices() { try @@ -114,7 +112,6 @@ namespace Jellyfin.Api.Controllers /// Status. [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] public IActionResult CreateAdminNotification( [FromQuery] string name, [FromQuery] string description, @@ -148,14 +145,12 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as read. - /// Status. [HttpPost("{UserID}/Read")] [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult SetRead( + public void SetRead( [FromRoute] string userId, [FromQuery] string ids) { - return Ok(); } /// @@ -163,14 +158,12 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as unread. - /// Status. [HttpPost("{UserID}/Unread")] [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult SetUnread( + public void SetUnread( [FromRoute] string userId, [FromQuery] string ids) { - return Ok(); } } } diff --git a/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs index 64e92bd83a..e34e176cb9 100644 --- a/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs +++ b/Jellyfin.Api/Models/NotificationDtos/NotificationResultDto.cs @@ -1,3 +1,5 @@ +#nullable enable + using System; using System.Collections.Generic; From fff2a40ffc4e5010b26143185c68d221225c1a22 Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 20 Apr 2020 07:24:13 -0600 Subject: [PATCH 13/39] Remove StringEnumConverter --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a4f078b5b3..92bacb4400 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -80,9 +80,6 @@ namespace Jellyfin.Server.Extensions { // Setting the naming policy to null leaves the property names as-is when serializing objects to JSON. options.JsonSerializerOptions.PropertyNamingPolicy = null; - - // Accept string enums - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }) .AddControllersAsServices(); } From 67efcbee05fe7917aaff11fd27235fb952938434 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Mon, 20 Apr 2020 20:16:58 -0600 Subject: [PATCH 14/39] Remove error handlers, to be implemented at a global level in a separate PR --- .../Controllers/NotificationsController.cs | 47 +++++-------------- 1 file changed, 12 insertions(+), 35 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index c0c2be626b..2a41f6020e 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -74,14 +74,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] public IActionResult GetNotificationTypes() { - try - { - return Ok(_notificationManager.GetNotificationTypes()); - } - catch (Exception e) - { - return StatusCode(StatusCodes.Status500InternalServerError, e.Message); - } + return Ok(_notificationManager.GetNotificationTypes()); } /// @@ -92,14 +85,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] public IActionResult GetNotificationServices() { - try - { - return Ok(_notificationManager.GetNotificationServices()); - } - catch (Exception e) - { - return StatusCode(StatusCodes.Status500InternalServerError, e.Message); - } + return Ok(_notificationManager.GetNotificationServices()); } /// @@ -112,32 +98,23 @@ namespace Jellyfin.Api.Controllers /// Status. [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult CreateAdminNotification( + public void CreateAdminNotification( [FromQuery] string name, [FromQuery] string description, [FromQuery] string? url, [FromQuery] NotificationLevel? level) { - try + var notification = new NotificationRequest { - var notification = new NotificationRequest - { - Name = name, - Description = description, - Url = url, - Level = level ?? NotificationLevel.Normal, - UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), - Date = DateTime.UtcNow, - }; + Name = name, + Description = description, + Url = url, + Level = level ?? NotificationLevel.Normal, + UserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray(), + Date = DateTime.UtcNow, + }; - _notificationManager.SendNotification(notification, CancellationToken.None); - - return Ok(); - } - catch (Exception e) - { - return StatusCode(StatusCodes.Status500InternalServerError, e.Message); - } + _notificationManager.SendNotification(notification, CancellationToken.None); } /// From 6c8e1d37bd49339d298c46c24cddf8e858b334c8 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Mon, 20 Apr 2020 23:53:09 -0600 Subject: [PATCH 15/39] Remove more unnecessary IActionResult --- .../Controllers/NotificationsController.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 2a41f6020e..932b91d55c 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -43,14 +43,14 @@ namespace Jellyfin.Api.Controllers /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] - [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - public IActionResult GetNotifications( + [ProducesResponseType(typeof(NotificationResultDto), StatusCodes.Status200OK)] + public NotificationResultDto GetNotifications( [FromRoute] string userId, [FromQuery] bool? isRead, [FromQuery] int? startIndex, [FromQuery] int? limit) { - return Ok(new NotificationResultDto()); + return new NotificationResultDto(); } /// @@ -60,10 +60,10 @@ namespace Jellyfin.Api.Controllers /// Notifications summary for the user. [HttpGet("{UserID}/Summary")] [ProducesResponseType(typeof(NotificationsSummaryDto), StatusCodes.Status200OK)] - public IActionResult GetNotificationsSummary( + public NotificationsSummaryDto GetNotificationsSummary( [FromRoute] string userId) { - return Ok(new NotificationsSummaryDto()); + return new NotificationsSummaryDto(); } /// @@ -71,10 +71,10 @@ namespace Jellyfin.Api.Controllers /// /// All notification types. [HttpGet("Types")] - [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - public IActionResult GetNotificationTypes() + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public IEnumerable GetNotificationTypes() { - return Ok(_notificationManager.GetNotificationTypes()); + return _notificationManager.GetNotificationTypes(); } /// @@ -83,9 +83,9 @@ namespace Jellyfin.Api.Controllers /// All notification services. [HttpGet("Services")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - public IActionResult GetNotificationServices() + public IEnumerable GetNotificationServices() { - return Ok(_notificationManager.GetNotificationServices()); + return _notificationManager.GetNotificationServices(); } /// From dae69657108f90de54166a670c47a6dff2dae139 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Tue, 21 Apr 2020 00:24:35 -0600 Subject: [PATCH 16/39] Remove documentation of void return type --- Jellyfin.Api/Controllers/NotificationsController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 932b91d55c..c1d9e32515 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -95,7 +95,6 @@ namespace Jellyfin.Api.Controllers /// The description of the notification. /// The URL of the notification. /// The level of the notification. - /// Status. [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] public void CreateAdminNotification( From 1175ce3f97fdebc6fdb489ce65deaac59c7b7f87 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 07:36:22 -0600 Subject: [PATCH 17/39] Add Exception Middleware --- .../Models/ExceptionDtos/ExceptionDto.cs | 14 +++++ .../ApiApplicationBuilderExtensions.cs | 11 ++++ .../Middleware/ExceptionMiddleware.cs | 60 +++++++++++++++++++ Jellyfin.Server/Startup.cs | 2 + 4 files changed, 87 insertions(+) create mode 100644 Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs create mode 100644 Jellyfin.Server/Middleware/ExceptionMiddleware.cs diff --git a/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs b/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs new file mode 100644 index 0000000000..d2b48d4ae5 --- /dev/null +++ b/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs @@ -0,0 +1,14 @@ +namespace Jellyfin.Api.Models.ExceptionDtos +{ + /// + /// Exception Dto. + /// Used for graceful handling of API exceptions. + /// + public class ExceptionDto + { + /// + /// Gets or sets exception message. + /// + public string Message { get; set; } + } +} diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index db06eb4552..6c105ab65b 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -1,3 +1,4 @@ +using Jellyfin.Server.Middleware; using Microsoft.AspNetCore.Builder; namespace Jellyfin.Server.Extensions @@ -23,5 +24,15 @@ namespace Jellyfin.Server.Extensions c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jellyfin API V1"); }); } + + /// + /// Adds exception middleware to the application pipeline. + /// + /// The application builder. + /// The updated application builder. + public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder applicationBuilder) + { + return applicationBuilder.UseMiddleware(); + } } } diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs new file mode 100644 index 0000000000..39aace95d2 --- /dev/null +++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs @@ -0,0 +1,60 @@ +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Jellyfin.Api.Models.ExceptionDtos; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Middleware +{ + /// + /// Exception Middleware. + /// + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Next request delegate. + /// Instance of the interface. + public ExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) + { + _next = next ?? throw new ArgumentNullException(nameof(next)); + _logger = loggerFactory.CreateLogger() ?? + throw new ArgumentNullException(nameof(loggerFactory)); + } + + /// + /// Invoke request. + /// + /// Request context. + /// Task. + public async Task Invoke(HttpContext context) + { + try + { + await _next(context).ConfigureAwait(false); + } + catch (Exception ex) + { + if (context.Response.HasStarted) + { + _logger.LogWarning("The response has already started, the exception middleware will not be executed."); + throw; + } + + var exceptionBody = new ExceptionDto { Message = ex.Message }; + var exceptionJson = JsonSerializer.Serialize(exceptionBody); + + context.Response.Clear(); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + // TODO switch between PascalCase and camelCase + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(exceptionJson).ConfigureAwait(false); + } + } + } +} diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 4d7d56e9d4..7a632f6c44 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -58,6 +58,8 @@ namespace Jellyfin.Server app.UseDeveloperExceptionPage(); } + app.UseExceptionMiddleware(); + app.UseWebSockets(); app.UseResponseCompression(); From fe632146dcba69edeec56b850736227ff5f4c5b3 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 08:17:13 -0600 Subject: [PATCH 18/39] Move Json Options to static class for easier access. --- .../CamelCaseJsonProfileFormatter.cs | 4 +- .../PascalCaseJsonProfileFormatter.cs | 4 +- Jellyfin.Server/Models/JsonOptions.cs | 41 +++++++++++++++++++ 3 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 Jellyfin.Server/Models/JsonOptions.cs diff --git a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs index 433a3197d3..e6ad6dfb13 100644 --- a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs +++ b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using Jellyfin.Server.Models; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; @@ -12,7 +12,7 @@ namespace Jellyfin.Server.Formatters /// /// Initializes a new instance of the class. /// - public CamelCaseJsonProfileFormatter() : base(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) + public CamelCaseJsonProfileFormatter() : base(JsonOptions.CamelCase) { SupportedMediaTypes.Clear(); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=\"CamelCase\"")); diff --git a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs index 2ed006a336..675f4c79ee 100644 --- a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs +++ b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using Jellyfin.Server.Models; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; @@ -12,7 +12,7 @@ namespace Jellyfin.Server.Formatters /// /// Initializes a new instance of the class. /// - public PascalCaseJsonProfileFormatter() : base(new JsonSerializerOptions { PropertyNamingPolicy = null }) + public PascalCaseJsonProfileFormatter() : base(JsonOptions.PascalCase) { SupportedMediaTypes.Clear(); // Add application/json for default formatter diff --git a/Jellyfin.Server/Models/JsonOptions.cs b/Jellyfin.Server/Models/JsonOptions.cs new file mode 100644 index 0000000000..fa503bc9a4 --- /dev/null +++ b/Jellyfin.Server/Models/JsonOptions.cs @@ -0,0 +1,41 @@ +using System.Text.Json; + +namespace Jellyfin.Server.Models +{ + /// + /// Json Options. + /// + public static class JsonOptions + { + /// + /// Base Json Serializer Options. + /// + private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + /// + /// Gets CamelCase json options. + /// + public static JsonSerializerOptions CamelCase + { + get + { + var options = _jsonOptions; + options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + return options; + } + } + + /// + /// Gets PascalCase json options. + /// + public static JsonSerializerOptions PascalCase + { + get + { + var options = _jsonOptions; + options.PropertyNamingPolicy = null; + return options; + } + } + } +} From 14361c68cf71bc810d282901a764d2f8d5858eea Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 08:38:31 -0600 Subject: [PATCH 19/39] Add ProducesResponseType to base controller --- Jellyfin.Api/BaseJellyfinApiController.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Jellyfin.Api/BaseJellyfinApiController.cs b/Jellyfin.Api/BaseJellyfinApiController.cs index 1f4508e6cb..f691759866 100644 --- a/Jellyfin.Api/BaseJellyfinApiController.cs +++ b/Jellyfin.Api/BaseJellyfinApiController.cs @@ -1,3 +1,5 @@ +using Jellyfin.Api.Models.ExceptionDtos; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Api @@ -7,6 +9,7 @@ namespace Jellyfin.Api /// [ApiController] [Route("[controller]")] + [ProducesResponseType(typeof(ExceptionDto), StatusCodes.Status500InternalServerError)] public class BaseJellyfinApiController : ControllerBase { } From 3ef8448a518e673feae0c70c2682d60e4632c0cd Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 09:09:05 -0600 Subject: [PATCH 20/39] Return to previous exception handle implementation --- Jellyfin.Api/BaseJellyfinApiController.cs | 3 - .../Models/ExceptionDtos/ExceptionDto.cs | 14 --- .../Middleware/ExceptionMiddleware.cs | 86 ++++++++++++++++--- 3 files changed, 73 insertions(+), 30 deletions(-) delete mode 100644 Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs diff --git a/Jellyfin.Api/BaseJellyfinApiController.cs b/Jellyfin.Api/BaseJellyfinApiController.cs index f691759866..1f4508e6cb 100644 --- a/Jellyfin.Api/BaseJellyfinApiController.cs +++ b/Jellyfin.Api/BaseJellyfinApiController.cs @@ -1,5 +1,3 @@ -using Jellyfin.Api.Models.ExceptionDtos; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Api @@ -9,7 +7,6 @@ namespace Jellyfin.Api /// [ApiController] [Route("[controller]")] - [ProducesResponseType(typeof(ExceptionDto), StatusCodes.Status500InternalServerError)] public class BaseJellyfinApiController : ControllerBase { } diff --git a/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs b/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs deleted file mode 100644 index d2b48d4ae5..0000000000 --- a/Jellyfin.Api/Models/ExceptionDtos/ExceptionDto.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Jellyfin.Api.Models.ExceptionDtos -{ - /// - /// Exception Dto. - /// Used for graceful handling of API exceptions. - /// - public class ExceptionDto - { - /// - /// Gets or sets exception message. - /// - public string Message { get; set; } - } -} diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs index 39aace95d2..0d9dac89f0 100644 --- a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs +++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs @@ -1,7 +1,9 @@ using System; -using System.Text.Json; +using System.IO; using System.Threading.Tasks; -using Jellyfin.Api.Models.ExceptionDtos; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -14,17 +16,22 @@ namespace Jellyfin.Server.Middleware { private readonly RequestDelegate _next; private readonly ILogger _logger; + private readonly IServerConfigurationManager _configuration; /// /// Initializes a new instance of the class. /// /// Next request delegate. /// Instance of the interface. - public ExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) + /// Instance of the interface. + public ExceptionMiddleware( + RequestDelegate next, + ILoggerFactory loggerFactory, + IServerConfigurationManager serverConfigurationManager) { - _next = next ?? throw new ArgumentNullException(nameof(next)); - _logger = loggerFactory.CreateLogger() ?? - throw new ArgumentNullException(nameof(loggerFactory)); + _next = next; + _logger = loggerFactory.CreateLogger(); + _configuration = serverConfigurationManager; } /// @@ -46,15 +53,68 @@ namespace Jellyfin.Server.Middleware throw; } - var exceptionBody = new ExceptionDto { Message = ex.Message }; - var exceptionJson = JsonSerializer.Serialize(exceptionBody); + ex = GetActualException(ex); + _logger.LogError(ex, "Error processing request: {0}", ex.Message); + context.Response.StatusCode = GetStatusCode(ex); + context.Response.ContentType = "text/plain"; - context.Response.Clear(); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - // TODO switch between PascalCase and camelCase - context.Response.ContentType = "application/json"; - await context.Response.WriteAsync(exceptionJson).ConfigureAwait(false); + var errorContent = NormalizeExceptionMessage(ex.Message); + await context.Response.WriteAsync(errorContent).ConfigureAwait(false); } } + + private static Exception GetActualException(Exception ex) + { + if (ex is AggregateException agg) + { + var inner = agg.InnerException; + if (inner != null) + { + return GetActualException(inner); + } + + var inners = agg.InnerExceptions; + if (inners.Count > 0) + { + return GetActualException(inners[0]); + } + } + + return ex; + } + + private static int GetStatusCode(Exception ex) + { + switch (ex) + { + case ArgumentException _: return StatusCodes.Status400BadRequest; + case SecurityException _: return StatusCodes.Status401Unauthorized; + case DirectoryNotFoundException _: + case FileNotFoundException _: + case ResourceNotFoundException _: return StatusCodes.Status404NotFound; + case MethodNotAllowedException _: return StatusCodes.Status405MethodNotAllowed; + default: return StatusCodes.Status500InternalServerError; + } + } + + private string NormalizeExceptionMessage(string msg) + { + if (msg == null) + { + return string.Empty; + } + + // Strip any information we don't want to reveal + msg = msg.Replace( + _configuration.ApplicationPaths.ProgramSystemPath, + string.Empty, + StringComparison.OrdinalIgnoreCase); + msg = msg.Replace( + _configuration.ApplicationPaths.ProgramDataPath, + string.Empty, + StringComparison.OrdinalIgnoreCase); + + return msg; + } } } From 69d9bfb233bd2716e3803b38c55275de58bb8d46 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Tue, 21 Apr 2020 12:10:34 -0600 Subject: [PATCH 21/39] Make documentation of parameters clearer Co-Authored-By: Vasily --- Jellyfin.Api/Controllers/NotificationsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index c1d9e32515..6145246ed3 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -38,7 +38,7 @@ namespace Jellyfin.Api.Controllers /// Endpoint for getting a user's notifications. /// /// The user's ID. - /// An optional filter by IsRead. + /// An optional filter by notification read state. /// The optional index to start at. All notifications with a lower index will be dropped from the results. /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. From 3ab61dbdc252670abf28797d3183614b1cd05ece Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 15:49:04 -0600 Subject: [PATCH 22/39] bump swashbuckle --- Jellyfin.Api/Jellyfin.Api.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index cbb1d3007f..77bb52c6a5 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -10,8 +10,8 @@ - - + + From 2542a27bd5f79ccfbc2547ddd877ddb0423ae296 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 16:15:31 -0600 Subject: [PATCH 23/39] Fix documentation endpoint for use with baseUrl --- .../ApiApplicationBuilderExtensions.cs | 28 ++++++++++++++----- Jellyfin.Server/Startup.cs | 2 +- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 43c49307d4..df3bab931b 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -1,3 +1,4 @@ +using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Builder; namespace Jellyfin.Server.Extensions @@ -11,23 +12,36 @@ namespace Jellyfin.Server.Extensions /// Adds swagger and swagger UI to the application pipeline. /// /// The application builder. + /// The server configuration. /// The updated application builder. - public static IApplicationBuilder UseJellyfinApiSwagger(this IApplicationBuilder applicationBuilder) + public static IApplicationBuilder UseJellyfinApiSwagger( + this IApplicationBuilder applicationBuilder, + IServerConfigurationManager serverConfigurationManager) { // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. - const string specEndpoint = "/swagger/v1/swagger.json"; + + var baseUrl = serverConfigurationManager.Configuration.BaseUrl.Trim('/'); + if (!string.IsNullOrEmpty(baseUrl)) + { + baseUrl += '/'; + } + return applicationBuilder - .UseSwagger() + .UseSwagger(c => + { + c.RouteTemplate = $"/{baseUrl}api-docs/{{documentName}}/openapi.json"; + }) .UseSwaggerUI(c => { - c.SwaggerEndpoint(specEndpoint, "Jellyfin API V1"); - c.RoutePrefix = "api-docs/swagger"; + c.SwaggerEndpoint($"/{baseUrl}api-docs/v1/openapi.json", "Jellyfin API v1"); + c.RoutePrefix = $"{baseUrl}api-docs/v1/swagger"; }) .UseReDoc(c => { - c.SpecUrl(specEndpoint); - c.RoutePrefix = "api-docs/redoc"; + c.DocumentTitle = "Jellyfin API v1"; + c.SpecUrl($"/{baseUrl}api-docs/v1/openapi.json"); + c.RoutePrefix = $"{baseUrl}api-docs/v1/redoc"; }); } } diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 4d7d56e9d4..ee08d2580a 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -66,7 +66,7 @@ namespace Jellyfin.Server app.Use(serverApplicationHost.ExecuteWebsocketHandlerAsync); // TODO use when old API is removed: app.UseAuthentication(); - app.UseJellyfinApiSwagger(); + app.UseJellyfinApiSwagger(_serverConfigurationManager); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => From 041d674eb6e4a675b68406ed5c2d7018d61e870a Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 21 Apr 2020 16:19:26 -0600 Subject: [PATCH 24/39] Fix swagger ui Document Title --- Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index df3bab931b..d094242259 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -34,6 +34,7 @@ namespace Jellyfin.Server.Extensions }) .UseSwaggerUI(c => { + c.DocumentTitle = "Jellyfin API v1"; c.SwaggerEndpoint($"/{baseUrl}api-docs/v1/openapi.json", "Jellyfin API v1"); c.RoutePrefix = $"{baseUrl}api-docs/v1/swagger"; }) From 2a49b19a7c02f16cd4bb1d847c1ff76c5df316fb Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 22 Apr 2020 00:21:37 -0600 Subject: [PATCH 25/39] Update documentation of startIndex Co-Authored-By: Vasily --- Jellyfin.Api/Controllers/NotificationsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 6145246ed3..bb9f5a7b3c 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -39,7 +39,7 @@ namespace Jellyfin.Api.Controllers /// /// The user's ID. /// An optional filter by notification read state. - /// The optional index to start at. All notifications with a lower index will be dropped from the results. + /// The optional index to start at. All notifications with a lower index will be omitted from the results. /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] From 7693cc0db006ef4eb3a90d161b14ac4551bb96a7 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 22 Apr 2020 10:00:10 -0600 Subject: [PATCH 26/39] Use ActionResult return type for all endpoints --- .../Controllers/NotificationsController.cs | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index bb9f5a7b3c..0bf3aa1b47 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -43,8 +43,8 @@ namespace Jellyfin.Api.Controllers /// An optional limit on the number of notifications returned. /// A read-only list of all of the user's notifications. [HttpGet("{UserID}")] - [ProducesResponseType(typeof(NotificationResultDto), StatusCodes.Status200OK)] - public NotificationResultDto GetNotifications( + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult GetNotifications( [FromRoute] string userId, [FromQuery] bool? isRead, [FromQuery] int? startIndex, @@ -59,8 +59,8 @@ namespace Jellyfin.Api.Controllers /// The user's ID. /// Notifications summary for the user. [HttpGet("{UserID}/Summary")] - [ProducesResponseType(typeof(NotificationsSummaryDto), StatusCodes.Status200OK)] - public NotificationsSummaryDto GetNotificationsSummary( + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult GetNotificationsSummary( [FromRoute] string userId) { return new NotificationsSummaryDto(); @@ -71,8 +71,8 @@ namespace Jellyfin.Api.Controllers /// /// All notification types. [HttpGet("Types")] - [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - public IEnumerable GetNotificationTypes() + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult> GetNotificationTypes() { return _notificationManager.GetNotificationTypes(); } @@ -82,10 +82,10 @@ namespace Jellyfin.Api.Controllers /// /// All notification services. [HttpGet("Services")] - [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - public IEnumerable GetNotificationServices() + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult> GetNotificationServices() { - return _notificationManager.GetNotificationServices(); + return _notificationManager.GetNotificationServices().ToList(); } /// @@ -97,7 +97,7 @@ namespace Jellyfin.Api.Controllers /// The level of the notification. [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] - public void CreateAdminNotification( + public ActionResult CreateAdminNotification( [FromQuery] string name, [FromQuery] string description, [FromQuery] string? url, @@ -114,6 +114,8 @@ namespace Jellyfin.Api.Controllers }; _notificationManager.SendNotification(notification, CancellationToken.None); + + return Ok(); } /// @@ -123,10 +125,11 @@ namespace Jellyfin.Api.Controllers /// A comma-separated list of the IDs of notifications which should be set as read. [HttpPost("{UserID}/Read")] [ProducesResponseType(StatusCodes.Status200OK)] - public void SetRead( + public ActionResult SetRead( [FromRoute] string userId, [FromQuery] string ids) { + return Ok(); } /// @@ -136,10 +139,11 @@ namespace Jellyfin.Api.Controllers /// A comma-separated list of the IDs of notifications which should be set as unread. [HttpPost("{UserID}/Unread")] [ProducesResponseType(StatusCodes.Status200OK)] - public void SetUnread( + public ActionResult SetUnread( [FromRoute] string userId, [FromQuery] string ids) { + return Ok(); } } } From c6eebca335d09d6a6c627205e126448ab5441f37 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 23 Apr 2020 07:29:28 -0600 Subject: [PATCH 27/39] Apply suggestions and add URL to log message --- .../Middleware/ExceptionMiddleware.cs | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs index 0d9dac89f0..ecc76594e4 100644 --- a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs +++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Net.Mime; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; @@ -22,15 +23,15 @@ namespace Jellyfin.Server.Middleware /// Initializes a new instance of the class. /// /// Next request delegate. - /// Instance of the interface. + /// Instance of the interface. /// Instance of the interface. public ExceptionMiddleware( RequestDelegate next, - ILoggerFactory loggerFactory, + ILogger logger, IServerConfigurationManager serverConfigurationManager) { _next = next; - _logger = loggerFactory.CreateLogger(); + _logger = logger; _configuration = serverConfigurationManager; } @@ -54,9 +55,14 @@ namespace Jellyfin.Server.Middleware } ex = GetActualException(ex); - _logger.LogError(ex, "Error processing request: {0}", ex.Message); + _logger.LogError( + ex, + "Error processing request: {ExceptionMessage}. URL {Method} {Url}. ", + ex.Message, + context.Request.Method, + context.Request.Path); context.Response.StatusCode = GetStatusCode(ex); - context.Response.ContentType = "text/plain"; + context.Response.ContentType = MediaTypeNames.Text.Plain; var errorContent = NormalizeExceptionMessage(ex.Message); await context.Response.WriteAsync(errorContent).ConfigureAwait(false); @@ -105,16 +111,14 @@ namespace Jellyfin.Server.Middleware } // Strip any information we don't want to reveal - msg = msg.Replace( - _configuration.ApplicationPaths.ProgramSystemPath, - string.Empty, - StringComparison.OrdinalIgnoreCase); - msg = msg.Replace( - _configuration.ApplicationPaths.ProgramDataPath, - string.Empty, - StringComparison.OrdinalIgnoreCase); - - return msg; + return msg.Replace( + _configuration.ApplicationPaths.ProgramSystemPath, + string.Empty, + StringComparison.OrdinalIgnoreCase) + .Replace( + _configuration.ApplicationPaths.ProgramDataPath, + string.Empty, + StringComparison.OrdinalIgnoreCase); } } } From 3c34d956088430da08bdd812c05d6a87c3bf9d25 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 23 Apr 2020 21:23:29 -0600 Subject: [PATCH 28/39] Address comments --- .../Middleware/ExceptionMiddleware.cs | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs index ecc76594e4..6ebe015030 100644 --- a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs +++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs @@ -1,8 +1,10 @@ using System; using System.IO; using System.Net.Mime; +using System.Net.Sockets; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; @@ -55,15 +57,35 @@ namespace Jellyfin.Server.Middleware } ex = GetActualException(ex); - _logger.LogError( - ex, - "Error processing request: {ExceptionMessage}. URL {Method} {Url}. ", - ex.Message, - context.Request.Method, - context.Request.Path); + + bool ignoreStackTrace = + ex is SocketException + || ex is IOException + || ex is OperationCanceledException + || ex is SecurityException + || ex is AuthenticationException + || ex is FileNotFoundException; + + if (ignoreStackTrace) + { + _logger.LogError( + "Error processing request: {ExceptionMessage}. URL {Method} {Url}.", + ex.Message.TrimEnd('.'), + context.Request.Method, + context.Request.Path); + } + else + { + _logger.LogError( + ex, + "Error processing request. URL {Method} {Url}.", + ex.Message.TrimEnd('.'), + context.Request.Method, + context.Request.Path); + } + context.Response.StatusCode = GetStatusCode(ex); context.Response.ContentType = MediaTypeNames.Text.Plain; - var errorContent = NormalizeExceptionMessage(ex.Message); await context.Response.WriteAsync(errorContent).ConfigureAwait(false); } From be50fae38a27878cb520e20ed7956a72d7b05a84 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 23 Apr 2020 21:24:40 -0600 Subject: [PATCH 29/39] Address comments --- .../Extensions/ApiApplicationBuilderExtensions.cs | 10 ---------- Jellyfin.Server/Startup.cs | 3 ++- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 6c105ab65b..0bd654c7dc 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -24,15 +24,5 @@ namespace Jellyfin.Server.Extensions c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jellyfin API V1"); }); } - - /// - /// Adds exception middleware to the application pipeline. - /// - /// The application builder. - /// The updated application builder. - public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder applicationBuilder) - { - return applicationBuilder.UseMiddleware(); - } } } diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 7a632f6c44..b17357fc3d 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -1,4 +1,5 @@ using Jellyfin.Server.Extensions; +using Jellyfin.Server.Middleware; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Builder; @@ -58,7 +59,7 @@ namespace Jellyfin.Server app.UseDeveloperExceptionPage(); } - app.UseExceptionMiddleware(); + app.UseMiddleware(); app.UseWebSockets(); From b8508a57d8320085c01a7e2d4656b233169584f2 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 23 Apr 2020 21:38:40 -0600 Subject: [PATCH 30/39] oop --- Jellyfin.Server/Middleware/ExceptionMiddleware.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs index 6ebe015030..0d79bbfaff 100644 --- a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs +++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs @@ -79,7 +79,6 @@ namespace Jellyfin.Server.Middleware _logger.LogError( ex, "Error processing request. URL {Method} {Url}.", - ex.Message.TrimEnd('.'), context.Request.Method, context.Request.Path); } From 0765ef8bda4d23e33fde7a1bfe49b5a365c6d28e Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 23 Apr 2020 21:41:10 -0600 Subject: [PATCH 31/39] Apply suggestions, fix warning --- Jellyfin.Server/Models/JsonOptions.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Server/Models/JsonOptions.cs b/Jellyfin.Server/Models/JsonOptions.cs index fa503bc9a4..2f0df3d2c7 100644 --- a/Jellyfin.Server/Models/JsonOptions.cs +++ b/Jellyfin.Server/Models/JsonOptions.cs @@ -7,11 +7,6 @@ namespace Jellyfin.Server.Models /// public static class JsonOptions { - /// - /// Base Json Serializer Options. - /// - private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); - /// /// Gets CamelCase json options. /// @@ -19,7 +14,7 @@ namespace Jellyfin.Server.Models { get { - var options = _jsonOptions; + var options = DefaultJsonOptions; options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; return options; } @@ -32,10 +27,15 @@ namespace Jellyfin.Server.Models { get { - var options = _jsonOptions; + var options = DefaultJsonOptions; options.PropertyNamingPolicy = null; return options; } } + + /// + /// Gets base Json Serializer Options. + /// + private static JsonSerializerOptions DefaultJsonOptions => new JsonSerializerOptions(); } } From 85853f9ce3d77469b84e3334d7080cd025474ee8 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Fri, 24 Apr 2020 17:11:11 -0600 Subject: [PATCH 32/39] Add back in return type documentation --- Jellyfin.Api/Controllers/NotificationsController.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 0bf3aa1b47..8da2a6c536 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -95,6 +95,7 @@ namespace Jellyfin.Api.Controllers /// The description of the notification. /// The URL of the notification. /// The level of the notification. + /// Status. [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult CreateAdminNotification( @@ -123,6 +124,7 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as read. + /// Status. [HttpPost("{UserID}/Read")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult SetRead( @@ -137,6 +139,7 @@ namespace Jellyfin.Api.Controllers /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as unread. + /// Status. [HttpPost("{UserID}/Unread")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult SetUnread( From 890e659cd390fc45c68b42c1a20f24a33e8c1570 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 25 Apr 2020 15:12:18 -0600 Subject: [PATCH 33/39] Fix autolaunch & redirect of swagger. --- Emby.Server.Implementations/Browser/BrowserLauncher.cs | 4 +++- Jellyfin.Server/Program.cs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs index 96096e142a..384cb049fa 100644 --- a/Emby.Server.Implementations/Browser/BrowserLauncher.cs +++ b/Emby.Server.Implementations/Browser/BrowserLauncher.cs @@ -1,5 +1,7 @@ using System; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Browser @@ -24,7 +26,7 @@ namespace Emby.Server.Implementations.Browser /// The app host. public static void OpenSwaggerPage(IServerApplicationHost appHost) { - TryOpenUrl(appHost, "/swagger/index.html"); + TryOpenUrl(appHost, "/api-docs/v1/swagger"); } /// diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index e55b0d4ed9..23ddcf159b 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -529,7 +529,7 @@ namespace Jellyfin.Server var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration; if (startupConfig != null && !startupConfig.HostWebClient()) { - inMemoryDefaultConfig[HttpListenerHost.DefaultRedirectKey] = "swagger/index.html"; + inMemoryDefaultConfig[HttpListenerHost.DefaultRedirectKey] = "api-docs/v1/swagger"; } return config From 068368df6352cfad4e69df599c364b3f05b367ba Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 26 Apr 2020 23:28:32 -0600 Subject: [PATCH 34/39] Order actions by route, then http method --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 92bacb4400..00a73ade6f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -105,6 +105,10 @@ namespace Jellyfin.Server.Extensions { c.IncludeXmlComments(xmlFile); } + + // Order actions by route path, then by http method. + c.OrderActionsBy(description => + $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}"); }); } } From c61a200c9de2714b3d6353f3a4ae52b8962d369a Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Tue, 28 Apr 2020 09:30:59 -0600 Subject: [PATCH 35/39] Revise documentation based on discussion in #2872 --- .../Controllers/NotificationsController.cs | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 8da2a6c536..8feea9ab61 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -35,13 +35,14 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint for getting a user's notifications. + /// Gets a user's notifications. /// /// The user's ID. /// An optional filter by notification read state. /// The optional index to start at. All notifications with a lower index will be omitted from the results. /// An optional limit on the number of notifications returned. - /// A read-only list of all of the user's notifications. + /// Notifications returned. + /// An containing a list of notifications. [HttpGet("{UserID}")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetNotifications( @@ -54,10 +55,11 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint for getting a user's notification summary. + /// Gets a user's notification summary. /// /// The user's ID. - /// Notifications summary for the user. + /// Summary of user's notifications returned. + /// An containing a summary of the users notifications. [HttpGet("{UserID}/Summary")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetNotificationsSummary( @@ -67,9 +69,10 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint for getting notification types. + /// Gets notification types. /// - /// All notification types. + /// All notification types returned. + /// An containing a list of all notification types. [HttpGet("Types")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetNotificationTypes() @@ -78,9 +81,10 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint for getting notification services. + /// Gets notification services. /// - /// All notification services. + /// All notification services returned. + /// An containing a list of all notification services. [HttpGet("Services")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetNotificationServices() @@ -89,13 +93,14 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint to send a notification to all admins. + /// Sends a notification to all admins. /// /// The name of the notification. /// The description of the notification. /// The URL of the notification. /// The level of the notification. - /// Status. + /// Notification sent. + /// An . [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult CreateAdminNotification( @@ -120,11 +125,12 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint to set notifications as read. + /// Sets notifications as read. /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as read. - /// Status. + /// Notifications set as read. + /// An . [HttpPost("{UserID}/Read")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult SetRead( @@ -135,11 +141,12 @@ namespace Jellyfin.Api.Controllers } /// - /// Endpoint to set notifications as unread. + /// Sets notifications as unread. /// /// The userID. /// A comma-separated list of the IDs of notifications which should be set as unread. - /// Status. + /// Notifications set as unread. + /// An . [HttpPost("{UserID}/Unread")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult SetUnread( From 806ae1bc07e715c6109a3e8ec96c6d3dd6a802ef Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 29 Apr 2020 08:04:05 -0600 Subject: [PATCH 36/39] Remove versioned API --- .../Browser/BrowserLauncher.cs | 2 +- .../ApiApplicationBuilderExtensions.cs | 16 ++++++++-------- .../Extensions/ApiServiceCollectionExtensions.cs | 2 +- Jellyfin.Server/Program.cs | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs index 384cb049fa..e706401fd1 100644 --- a/Emby.Server.Implementations/Browser/BrowserLauncher.cs +++ b/Emby.Server.Implementations/Browser/BrowserLauncher.cs @@ -26,7 +26,7 @@ namespace Emby.Server.Implementations.Browser /// The app host. public static void OpenSwaggerPage(IServerApplicationHost appHost) { - TryOpenUrl(appHost, "/api-docs/v1/swagger"); + TryOpenUrl(appHost, "/api-docs/swagger"); } /// diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 33fd77d9c7..745567703f 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -1,5 +1,4 @@ using MediaBrowser.Controller.Configuration; -using Jellyfin.Server.Middleware; using Microsoft.AspNetCore.Builder; namespace Jellyfin.Server.Extensions @@ -31,19 +30,20 @@ namespace Jellyfin.Server.Extensions return applicationBuilder .UseSwagger(c => { - c.RouteTemplate = $"/{baseUrl}api-docs/{{documentName}}/openapi.json"; + // Custom path requires {documentName}, SwaggerDoc documentName is 'api-docs' + c.RouteTemplate = $"/{baseUrl}{{documentName}}/openapi.json"; }) .UseSwaggerUI(c => { - c.DocumentTitle = "Jellyfin API v1"; - c.SwaggerEndpoint($"/{baseUrl}api-docs/v1/openapi.json", "Jellyfin API v1"); - c.RoutePrefix = $"{baseUrl}api-docs/v1/swagger"; + c.DocumentTitle = "Jellyfin API"; + c.SwaggerEndpoint($"/{baseUrl}api-docs/openapi.json", "Jellyfin API"); + c.RoutePrefix = $"{baseUrl}api-docs/swagger"; }) .UseReDoc(c => { - c.DocumentTitle = "Jellyfin API v1"; - c.SpecUrl($"/{baseUrl}api-docs/v1/openapi.json"); - c.RoutePrefix = $"{baseUrl}api-docs/v1/redoc"; + c.DocumentTitle = "Jellyfin API"; + c.SpecUrl($"/{baseUrl}api-docs/openapi.json"); + c.RoutePrefix = $"{baseUrl}api-docs/redoc"; }); } } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a24785d57e..a354f45aad 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -96,7 +96,7 @@ namespace Jellyfin.Server.Extensions { return serviceCollection.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" }); + c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API" }); // Add all xml doc files to swagger generator. var xmlFiles = Directory.GetFiles( diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 23ddcf159b..7135800802 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -529,7 +529,7 @@ namespace Jellyfin.Server var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration; if (startupConfig != null && !startupConfig.HostWebClient()) { - inMemoryDefaultConfig[HttpListenerHost.DefaultRedirectKey] = "api-docs/v1/swagger"; + inMemoryDefaultConfig[HttpListenerHost.DefaultRedirectKey] = "api-docs/swagger"; } return config From 82231b4393bb367f7fca50fed21f00e469b9f960 Mon Sep 17 00:00:00 2001 From: ZadenRB Date: Wed, 29 Apr 2020 15:53:29 -0600 Subject: [PATCH 37/39] Update to return IEnumerable directly where possible --- Jellyfin.Api/Controllers/NotificationsController.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 8feea9ab61..3cbb3a3a3f 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -75,7 +75,7 @@ namespace Jellyfin.Api.Controllers /// An containing a list of all notification types. [HttpGet("Types")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> GetNotificationTypes() + public IEnumerable GetNotificationTypes() { return _notificationManager.GetNotificationTypes(); } @@ -87,9 +87,9 @@ namespace Jellyfin.Api.Controllers /// An containing a list of all notification services. [HttpGet("Services")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> GetNotificationServices() + public IEnumerable GetNotificationServices() { - return _notificationManager.GetNotificationServices().ToList(); + return _notificationManager.GetNotificationServices(); } /// From d7d8118b42c8abc8a4f12c4f2b0fb97cc6384ba7 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 3 May 2020 14:02:15 -0600 Subject: [PATCH 38/39] Fix xml docs --- Jellyfin.Api/Controllers/NotificationsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 3cbb3a3a3f..8d82ca10f1 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -83,7 +83,7 @@ namespace Jellyfin.Api.Controllers /// /// Gets notification services. /// - /// All notification services returned. + /// All notification services returned. /// An containing a list of all notification services. [HttpGet("Services")] [ProducesResponseType(StatusCodes.Status200OK)] From 2b1b9a64b6b7a3bac4d96642cda7a0c55d5cae74 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 8 May 2020 08:40:37 -0600 Subject: [PATCH 39/39] Add OperationId to SwaggerGen --- .../Extensions/ApiServiceCollectionExtensions.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a354f45aad..344ef6a5ff 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Text.Json.Serialization; using Jellyfin.Api; using Jellyfin.Api.Auth; @@ -14,6 +15,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; namespace Jellyfin.Server.Extensions { @@ -112,6 +114,10 @@ namespace Jellyfin.Server.Extensions // Order actions by route path, then by http method. c.OrderActionsBy(description => $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}"); + + // Use method name as operationId + c.CustomOperationIds(description => + description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null); }); } }