Merge remote-tracking branch 'upstream/api-migration' into api-scheduled-tasks

This commit is contained in:
crobibero 2020-06-04 15:16:04 -06:00
commit a787efc660
57 changed files with 1433 additions and 1037 deletions

14
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-dotnettools.csharp",
"editorconfig.editorconfig"
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": [
]
}

View File

@ -1,5 +1,4 @@
ARG DOTNET_VERSION=3.1
ARG FFMPEG_VERSION=latest
FROM node:alpine as web-builder
ARG JELLYFIN_WEB_VERSION=master
@ -17,7 +16,6 @@ ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"
FROM jellyfin/ffmpeg:${FFMPEG_VERSION} as ffmpeg
FROM debian:buster-slim
# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
@ -27,32 +25,26 @@ ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
COPY --from=builder /jellyfin /jellyfin
COPY --from=web-builder /dist /jellyfin/jellyfin-web
# Install dependencies:
# libfontconfig1: needed for Skia
# libgomp1: needed for ffmpeg
# libva-drm2: needed for ffmpeg
# mesa-va-drivers: needed for VAAPI
# mesa-va-drivers: needed for AMD VAAPI
RUN apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg wget apt-transport-https \
&& wget -O - https://repo.jellyfin.org/jellyfin_team.gpg.key | apt-key add - \
&& echo "deb [arch=$( dpkg --print-architecture )] https://repo.jellyfin.org/$( awk -F'=' '/^ID=/{ print $NF }' /etc/os-release ) $( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release ) main" | tee /etc/apt/sources.list.d/jellyfin.list \
&& apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y \
libfontconfig1 \
libgomp1 \
libva-drm2 \
mesa-va-drivers \
jellyfin-ffmpeg \
openssl \
ca-certificates \
vainfo \
i965-va-driver \
locales \
&& apt-get clean autoclean -y\
&& apt-get autoremove -y\
&& apt-get remove gnupg wget apt-transport-https -y \
&& apt-get clean autoclean -y \
&& apt-get autoremove -y \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /cache /config /media \
&& chmod 777 /cache /config /media \
&& ln -s /opt/ffmpeg/bin/ffmpeg /usr/local/bin \
&& ln -s /opt/ffmpeg/bin/ffprobe /usr/local/bin \
&& sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
@ -65,4 +57,4 @@ VOLUME /cache /config /media
ENTRYPOINT ["./jellyfin/jellyfin", \
"--datadir", "/config", \
"--cachedir", "/cache", \
"--ffmpeg", "/usr/local/bin/ffmpeg"]
"--ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"]

View File

@ -1018,19 +1018,58 @@ namespace Emby.Dlna.Didl
}
}
item = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Primary));
if (item != null)
// For audio tracks without art use album art if available.
if (item is Audio audioItem)
{
if (item.HasImage(ImageType.Primary))
{
return GetImageInfo(item, ImageType.Primary);
}
var album = audioItem.AlbumEntity;
return album != null && album.HasImage(ImageType.Primary)
? GetImageInfo(album, ImageType.Primary)
: null;
}
// Don't look beyond album/playlist level. Metadata service may assign an image from a different album/show to the parent folder.
if (item is MusicAlbum || item is Playlist)
{
return null;
}
// For other item types check parents, but be aware that image retrieved from a parent may be not suitable for this media item.
var parentWithImage = GetFirstParentWithImageBelowUserRoot(item);
if (parentWithImage != null)
{
return GetImageInfo(parentWithImage, ImageType.Primary);
}
return null;
}
private BaseItem GetFirstParentWithImageBelowUserRoot(BaseItem item)
{
if (item == null)
{
return null;
}
if (item.HasImage(ImageType.Primary))
{
return item;
}
var parent = item.GetParent();
if (parent is UserRootFolder)
{
return null;
}
// terminate in case we went past user root folder (unlikely?)
if (parent is Folder folder && folder.IsRoot)
{
return null;
}
return GetFirstParentWithImageBelowUserRoot(parent);
}
private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
{
var imageInfo = item.GetImageInfo(type, 0);

View File

@ -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<NotificationResult>
{
[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<Notification> Notifications { get; set; } = Array.Empty<Notification>();
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<NotificationsSummary>
{
[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<List<NotificationTypeInfo>>
{
}
[Route("/Notifications/Services", "GET", Summary = "Gets notification types")]
public class GetNotificationServices : IReturn<List<NameIdPair>>
{
}
[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();
}
}
}

View File

@ -422,7 +422,7 @@ namespace Emby.Server.Implementations.Activity
});
}
private void OnPluginUpdated(object sender, GenericEventArgs<(IPlugin, PackageVersionInfo)> e)
private void OnPluginUpdated(object sender, GenericEventArgs<(IPlugin, VersionInfo)> e)
{
CreateLogEntry(new ActivityLogEntry
{
@ -434,8 +434,8 @@ namespace Emby.Server.Implementations.Activity
ShortOverview = string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("VersionNumber"),
e.Argument.Item2.versionStr),
Overview = e.Argument.Item2.description
e.Argument.Item2.version),
Overview = e.Argument.Item2.changelog
});
}
@ -451,7 +451,7 @@ namespace Emby.Server.Implementations.Activity
});
}
private void OnPluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
private void OnPluginInstalled(object sender, GenericEventArgs<VersionInfo> e)
{
CreateLogEntry(new ActivityLogEntry
{
@ -463,7 +463,7 @@ namespace Emby.Server.Implementations.Activity
ShortOverview = string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("VersionNumber"),
e.Argument.versionStr)
e.Argument.version)
});
}

View File

@ -211,19 +211,6 @@ namespace Emby.Server.Implementations
public IFileSystem FileSystemManager { get; set; }
/// <inheritdoc />
public PackageVersionClass SystemUpdateLevel
{
get
{
#if BETA
return PackageVersionClass.Beta;
#else
return PackageVersionClass.Release;
#endif
}
}
/// <summary>
/// Gets or sets the service provider.
/// </summary>
@ -1390,7 +1377,6 @@ namespace Emby.Server.Implementations
SupportsLibraryMonitor = true,
EncoderLocation = MediaEncoder.EncoderLocation,
SystemArchitecture = RuntimeInformation.OSArchitecture,
SystemUpdateLevel = SystemUpdateLevel,
PackageName = StartupOptions.PackageName
};
}

View File

@ -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
/// <param name="appHost">The app host.</param>
public static void OpenSwaggerPage(IServerApplicationHost appHost)
{
TryOpenUrl(appHost, "/swagger/index.html");
TryOpenUrl(appHost, "/api-docs/swagger");
}
/// <summary>

View File

@ -18,7 +18,7 @@ namespace Emby.Server.Implementations
{
{ HostWebClientKey, bool.TrueString },
{ HttpListenerHost.DefaultRedirectKey, "web/index.html" },
{ InstallationManager.PluginManifestUrlKey, "https://repo.jellyfin.org/releases/plugin/manifest.json" },
{ InstallationManager.PluginManifestUrlKey, "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" },
{ FfmpegProbeSizeKey, "1G" },
{ FfmpegAnalyzeDurationKey, "200M" },
{ PlaylistsAllowDuplicatesKey, bool.TrueString }

View File

@ -39,7 +39,7 @@ namespace Emby.Server.Implementations.Library
// for imdbid we also accept pattern matching
if (string.Equals(attrib, "imdbid", StringComparison.OrdinalIgnoreCase))
{
var m = Regex.Match(str, "tt\\d{7}", RegexOptions.IgnoreCase);
var m = Regex.Match(str, "tt([0-9]{7,8})", RegexOptions.IgnoreCase);
return m.Success ? m.Value : null;
}

View File

@ -3,7 +3,7 @@
"AppDeviceValues": "App: {0}, Gerät: {1}",
"Application": "Anwendung",
"Artists": "Interpreten",
"AuthenticationSucceededWithUserName": "{0} hat sich erfolgreich authentifziert",
"AuthenticationSucceededWithUserName": "{0} hat sich erfolgreich authentifiziert",
"Books": "Bücher",
"CameraImageUploadedFrom": "Ein neues Foto wurde von {0} hochgeladen",
"Channels": "Kanäle",
@ -99,11 +99,11 @@
"TaskRefreshChannels": "Erneuere Kanäle",
"TaskCleanTranscodeDescription": "Löscht Transkodierdateien welche älter als ein Tag sind.",
"TaskCleanTranscode": "Lösche Transkodier Pfad",
"TaskUpdatePluginsDescription": "Läd Updates für Plugins herunter, welche dazu eingestellt sind automatisch zu updaten und installiert sie.",
"TaskUpdatePluginsDescription": "Lädt Updates für Plugins herunter, welche dazu eingestellt sind automatisch zu updaten und installiert sie.",
"TaskUpdatePlugins": "Update Plugins",
"TaskRefreshPeopleDescription": "Erneuert Metadaten für Schausteller und Regisseure in deinen Bibliotheken.",
"TaskRefreshPeople": "Erneuere Schausteller",
"TaskCleanLogsDescription": "Lösche Log Datein die älter als {0} Tage sind.",
"TaskCleanLogsDescription": "Lösche Log Dateien die älter als {0} Tage sind.",
"TaskCleanLogs": "Lösche Log Pfad",
"TaskRefreshLibraryDescription": "Scanne alle Bibliotheken für hinzugefügte Datein und erneuere Metadaten.",
"TaskRefreshLibrary": "Scanne alle Bibliotheken",

View File

@ -23,7 +23,7 @@
"HeaderFavoriteEpisodes": "قسمت‌های مورد علاقه",
"HeaderFavoriteShows": "سریال‌های مورد علاقه",
"HeaderFavoriteSongs": "آهنگ‌های مورد علاقه",
"HeaderLiveTV": "تلویزیون زنده",
"HeaderLiveTV": "پخش زنده",
"HeaderNextUp": "قسمت بعدی",
"HeaderRecordingGroups": "گروه‌های ضبط",
"HomeVideos": "ویدیوهای خانگی",

View File

@ -11,7 +11,7 @@
"Collections": "Collections",
"DeviceOfflineWithName": "{0} s'est déconnecté",
"DeviceOnlineWithName": "{0} est connecté",
"FailedLoginAttemptWithUserName": "Échec de connexion de {0}",
"FailedLoginAttemptWithUserName": "Échec de connexion depuis {0}",
"Favorites": "Favoris",
"Folders": "Dossiers",
"Genres": "Genres",
@ -69,7 +69,7 @@
"PluginUpdatedWithName": "{0} a été mis à jour",
"ProviderValue": "Fournisseur : {0}",
"ScheduledTaskFailedWithName": "{0} a échoué",
"ScheduledTaskStartedWithName": "{0} a commencé",
"ScheduledTaskStartedWithName": "{0} a démarré",
"ServerNameNeedsToBeRestarted": "{0} doit être redémarré",
"Shows": "Émissions",
"Songs": "Chansons",
@ -95,21 +95,21 @@
"VersionNumber": "Version {0}",
"TasksChannelsCategory": "Chaines en ligne",
"TaskDownloadMissingSubtitlesDescription": "Cherche les sous-titres manquant sur internet en se basant sur la configuration des métadonnées.",
"TaskDownloadMissingSubtitles": "Télécharge les sous-titres manquant",
"TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquant",
"TaskRefreshChannelsDescription": "Rafraîchit les informations des chaines en ligne.",
"TaskRefreshChannels": "Rafraîchit les chaines",
"TaskRefreshChannels": "Rafraîchir les chaines",
"TaskCleanTranscodeDescription": "Supprime les fichiers transcodés de plus d'un jour.",
"TaskCleanTranscode": "Nettoie les dossier des transcodages",
"TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des plugins configurés pour être mis à jour automatiquement.",
"TaskUpdatePlugins": "Mettre à jour les plugins",
"TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et directeurs dans votre bibliothèque.",
"TaskRefreshPeople": "Rafraîchit les acteurs",
"TaskCleanTranscode": "Nettoyer les dossier des transcodages",
"TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurés pour être mises à jour automatiquement.",
"TaskUpdatePlugins": "Mettre à jour les extensions",
"TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre bibliothèque.",
"TaskRefreshPeople": "Rafraîchir les acteurs",
"TaskCleanLogsDescription": "Supprime les journaux de plus de {0} jours.",
"TaskCleanLogs": "Nettoie le répertoire des journaux",
"TaskCleanLogs": "Nettoyer le répertoire des journaux",
"TaskRefreshLibraryDescription": "Scanne toute les bibliothèques pour trouver les nouveaux fichiers et rafraîchit les métadonnées.",
"TaskRefreshLibrary": "Scanne toute les Bibliothèques",
"TaskRefreshLibrary": "Scanner toute les Bibliothèques",
"TaskRefreshChapterImagesDescription": "Crée des images de miniature pour les vidéos ayant des chapitres.",
"TaskRefreshChapterImages": "Extrait les images de chapitre",
"TaskRefreshChapterImages": "Extraire les images de chapitre",
"TaskCleanCacheDescription": "Supprime les fichiers de cache dont le système n'a plus besoin.",
"TaskCleanCache": "Vider le répertoire cache",
"TasksApplicationCategory": "Application",

View File

@ -26,7 +26,7 @@
"HeaderLiveTV": "TV em Direto",
"HeaderNextUp": "A Seguir",
"HeaderRecordingGroups": "Grupos de Gravação",
"HomeVideos": "Home videos",
"HomeVideos": "Videos caseiros",
"Inherit": "Herdar",
"ItemAddedWithName": "{0} foi adicionado à biblioteca",
"ItemRemovedWithName": "{0} foi removido da biblioteca",
@ -92,5 +92,27 @@
"UserStoppedPlayingItemWithValues": "{0} terminou a reprodução de {1} em {2}",
"ValueHasBeenAddedToLibrary": "{0} foi adicionado à sua biblioteca multimédia",
"ValueSpecialEpisodeName": "Especial - {0}",
"VersionNumber": "Versão {0}"
"VersionNumber": "Versão {0}",
"TaskDownloadMissingSubtitlesDescription": "Procurar na internet por legendas em falta baseado na configuração de metadados.",
"TaskDownloadMissingSubtitles": "Fazer download de legendas em falta",
"TaskRefreshChannelsDescription": "Atualizar informação sobre canais da Internet.",
"TaskRefreshChannels": "Atualizar Canais",
"TaskCleanTranscodeDescription": "Apagar ficheiros de transcode com mais de um dia.",
"TaskCleanTranscode": "Limpar a Diretoria de Transcode",
"TaskUpdatePluginsDescription": "Faz o download e instala updates para os plugins que estão configurados para atualizar automaticamente.",
"TaskUpdatePlugins": "Atualizar Plugins",
"TaskRefreshPeopleDescription": "Atualizar metadados para atores e diretores na biblioteca.",
"TaskRefreshPeople": "Atualizar Pessoas",
"TaskCleanLogsDescription": "Apagar ficheiros de log que têm mais de {0} dias.",
"TaskCleanLogs": "Limpar a Diretoria de Logs",
"TaskRefreshLibraryDescription": "Scannear a biblioteca de música para novos ficheiros e atualizar os metadados.",
"TaskRefreshLibrary": "Scannear Biblioteca de Música",
"TaskRefreshChapterImagesDescription": "Criar thumbnails para os vídeos que têm capítulos.",
"TaskRefreshChapterImages": "Extrair Imagens dos Capítulos",
"TaskCleanCacheDescription": "Apagar ficheiros em cache que já não são necessários.",
"TaskCleanCache": "Limpar Cache",
"TasksChannelsCategory": "Canais da Internet",
"TasksApplicationCategory": "Aplicação",
"TasksLibraryCategory": "Biblioteca",
"TasksMaintenanceCategory": "Manutenção"
}

View File

@ -91,5 +91,18 @@
"VersionNumber": "版本 {0}",
"HeaderRecordingGroups": "錄製組",
"Inherit": "繼承",
"SubtitleDownloadFailureFromForItem": "無法為 {1} 從 {0} 下載字幕"
"SubtitleDownloadFailureFromForItem": "無法為 {1} 從 {0} 下載字幕",
"TaskDownloadMissingSubtitlesDescription": "在網路上透過描述資料搜尋遺失的字幕。",
"TaskDownloadMissingSubtitles": "下載遺失的字幕",
"TaskRefreshChannels": "重新整理頻道",
"TaskUpdatePlugins": "更新插件",
"TaskRefreshPeople": "重新整理人員",
"TaskCleanLogsDescription": "刪除超過{0}天的紀錄檔案。",
"TaskCleanLogs": "清空紀錄資料夾",
"TaskRefreshLibraryDescription": "掃描媒體庫內新的檔案並重新整理描述資料。",
"TaskRefreshLibrary": "掃描媒體庫",
"TaskRefreshChapterImages": "擷取章節圖片",
"TaskCleanCacheDescription": "刪除系統長時間不需要的快取。",
"TaskCleanCache": "清除快取資料夾",
"TasksLibraryCategory": "媒體庫"
}

View File

@ -26,7 +26,7 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Updates
{
/// <summary>
/// Manages all install, uninstall and update operations (both plugins and system).
/// Manages all install, uninstall, and update operations for the system and individual plugins.
/// </summary>
public class InstallationManager : IInstallationManager
{
@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Updates
public const string PluginManifestUrlKey = "InstallationManager:PluginManifestUrl";
/// <summary>
/// The _logger.
/// The logger.
/// </summary>
private readonly ILogger _logger;
private readonly IApplicationPaths _appPaths;
@ -112,10 +112,10 @@ namespace Emby.Server.Implementations.Updates
public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
/// <inheritdoc />
public event EventHandler<GenericEventArgs<(IPlugin, PackageVersionInfo)>> PluginUpdated;
public event EventHandler<GenericEventArgs<(IPlugin, VersionInfo)>> PluginUpdated;
/// <inheritdoc />
public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
public event EventHandler<GenericEventArgs<VersionInfo>> PluginInstalled;
/// <inheritdoc />
public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
@ -183,61 +183,56 @@ namespace Emby.Server.Implementations.Updates
}
/// <inheritdoc />
public IEnumerable<PackageVersionInfo> GetCompatibleVersions(
IEnumerable<PackageVersionInfo> availableVersions,
Version minVersion = null,
PackageVersionClass classification = PackageVersionClass.Release)
public IEnumerable<VersionInfo> GetCompatibleVersions(
IEnumerable<VersionInfo> availableVersions,
Version minVersion = null)
{
var appVer = _applicationHost.ApplicationVersion;
availableVersions = availableVersions
.Where(x => x.classification == classification
&& Version.Parse(x.requiredVersionStr) <= appVer);
.Where(x => Version.Parse(x.targetAbi) <= appVer);
if (minVersion != null)
{
availableVersions = availableVersions.Where(x => x.Version >= minVersion);
availableVersions = availableVersions.Where(x => x.version >= minVersion);
}
return availableVersions.OrderByDescending(x => x.Version);
return availableVersions.OrderByDescending(x => x.version);
}
/// <inheritdoc />
public IEnumerable<PackageVersionInfo> GetCompatibleVersions(
public IEnumerable<VersionInfo> GetCompatibleVersions(
IEnumerable<PackageInfo> availablePackages,
string name = null,
Guid guid = default,
Version minVersion = null,
PackageVersionClass classification = PackageVersionClass.Release)
Version minVersion = null)
{
var package = FilterPackages(availablePackages, name, guid).FirstOrDefault();
// Package not found.
// Package not found in repository
if (package == null)
{
return Enumerable.Empty<PackageVersionInfo>();
return Enumerable.Empty<VersionInfo>();
}
return GetCompatibleVersions(
package.versions,
minVersion,
classification);
minVersion);
}
/// <inheritdoc />
public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
public async Task<IEnumerable<VersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
{
var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
return GetAvailablePluginUpdates(catalog);
}
private IEnumerable<PackageVersionInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
private IEnumerable<VersionInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
{
foreach (var plugin in _applicationHost.Plugins)
{
var compatibleversions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, plugin.Version, _applicationHost.SystemUpdateLevel);
var version = compatibleversions.FirstOrDefault(y => y.Version > plugin.Version);
if (version != null
&& !CompletedInstallations.Any(x => string.Equals(x.AssemblyGuid, version.guid, StringComparison.OrdinalIgnoreCase)))
var compatibleversions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, plugin.Version);
var version = compatibleversions.FirstOrDefault(y => y.version > plugin.Version);
if (version != null && !CompletedInstallations.Any(x => string.Equals(x.Guid, version.guid, StringComparison.OrdinalIgnoreCase)))
{
yield return version;
}
@ -245,7 +240,7 @@ namespace Emby.Server.Implementations.Updates
}
/// <inheritdoc />
public async Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken)
public async Task InstallPackage(VersionInfo package, CancellationToken cancellationToken)
{
if (package == null)
{
@ -254,11 +249,9 @@ namespace Emby.Server.Implementations.Updates
var installationInfo = new InstallationInfo
{
Id = Guid.NewGuid(),
Guid = package.guid,
Name = package.name,
AssemblyGuid = package.guid,
UpdateClass = package.classification,
Version = package.versionStr
Version = package.version.ToString()
};
var innerCancellationTokenSource = new CancellationTokenSource();
@ -276,7 +269,7 @@ namespace Emby.Server.Implementations.Updates
var installationEventArgs = new InstallationEventArgs
{
InstallationInfo = installationInfo,
PackageVersionInfo = package
VersionInfo = package
};
PackageInstalling?.Invoke(this, installationEventArgs);
@ -301,7 +294,7 @@ namespace Emby.Server.Implementations.Updates
_currentInstallations.Remove(tuple);
}
_logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
_logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.version);
PackageInstallationCancelled?.Invoke(this, installationEventArgs);
@ -337,7 +330,7 @@ namespace Emby.Server.Implementations.Updates
/// <param name="package">The package.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns><see cref="Task" />.</returns>
private async Task InstallPackageInternal(PackageVersionInfo package, CancellationToken cancellationToken)
private async Task InstallPackageInternal(VersionInfo package, CancellationToken cancellationToken)
{
// Set last update time if we were installed before
IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
@ -349,26 +342,26 @@ namespace Emby.Server.Implementations.Updates
// Do plugin-specific processing
if (plugin == null)
{
_logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
_logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.version);
PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo>(package));
PluginInstalled?.Invoke(this, new GenericEventArgs<VersionInfo>(package));
}
else
{
_logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
_logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.version);
PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, PackageVersionInfo)>((plugin, package)));
PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, VersionInfo)>((plugin, package)));
}
_applicationHost.NotifyPendingRestart();
}
private async Task PerformPackageInstallation(PackageVersionInfo package, CancellationToken cancellationToken)
private async Task PerformPackageInstallation(VersionInfo package, CancellationToken cancellationToken)
{
var extension = Path.GetExtension(package.targetFilename);
var extension = Path.GetExtension(package.filename);
if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
{
_logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
_logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.filename);
return;
}
@ -415,7 +408,7 @@ namespace Emby.Server.Implementations.Updates
}
/// <summary>
/// Uninstalls a plugin
/// Uninstalls a plugin.
/// </summary>
/// <param name="plugin">The plugin.</param>
public void UninstallPlugin(IPlugin plugin)
@ -473,7 +466,7 @@ namespace Emby.Server.Implementations.Updates
{
lock (_currentInstallationsLock)
{
var install = _currentInstallations.Find(x => x.info.Id == id);
var install = _currentInstallations.Find(x => x.info.Guid == id.ToString());
if (install == default((InstallationInfo, CancellationTokenSource)))
{
return false;

View File

@ -0,0 +1,125 @@
#nullable enable
using System.Text.Json;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Models.ConfigurationDtos;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// Configuration Controller.
/// </summary>
[Route("System")]
[Authorize]
public class ConfigurationController : BaseJellyfinApiController
{
private readonly IServerConfigurationManager _configurationManager;
private readonly IMediaEncoder _mediaEncoder;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationController"/> class.
/// </summary>
/// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
public ConfigurationController(
IServerConfigurationManager configurationManager,
IMediaEncoder mediaEncoder)
{
_configurationManager = configurationManager;
_mediaEncoder = mediaEncoder;
}
/// <summary>
/// Gets application configuration.
/// </summary>
/// <response code="200">Application configuration returned.</response>
/// <returns>Application configuration.</returns>
[HttpGet("Configuration")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<ServerConfiguration> GetConfiguration()
{
return _configurationManager.Configuration;
}
/// <summary>
/// Updates application configuration.
/// </summary>
/// <param name="configuration">Configuration.</param>
/// <response code="200">Configuration updated.</response>
/// <returns>Update status.</returns>
[HttpPost("Configuration")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult UpdateConfiguration([FromBody, BindRequired] ServerConfiguration configuration)
{
_configurationManager.ReplaceConfiguration(configuration);
return Ok();
}
/// <summary>
/// Gets a named configuration.
/// </summary>
/// <param name="key">Configuration key.</param>
/// <response code="200">Configuration returned.</response>
/// <returns>Configuration.</returns>
[HttpGet("Configuration/{Key}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<object> GetNamedConfiguration([FromRoute] string key)
{
return _configurationManager.GetConfiguration(key);
}
/// <summary>
/// Updates named configuration.
/// </summary>
/// <param name="key">Configuration key.</param>
/// <response code="200">Named configuration updated.</response>
/// <returns>Update status.</returns>
[HttpPost("Configuration/{Key}")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult> UpdateNamedConfiguration([FromRoute] string key)
{
var configurationType = _configurationManager.GetConfigurationType(key);
var configuration = await JsonSerializer.DeserializeAsync(Request.Body, configurationType);
_configurationManager.SaveConfiguration(key, configuration);
return Ok();
}
/// <summary>
/// Gets a default MetadataOptions object.
/// </summary>
/// <response code="200">Metadata options returned.</response>
/// <returns>Default MetadataOptions.</returns>
[HttpGet("Configuration/MetadataOptions/Default")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<MetadataOptions> GetDefaultMetadataOptions()
{
return new MetadataOptions();
}
/// <summary>
/// Updates the path to the media encoder.
/// </summary>
/// <param name="mediaEncoderPath">Media encoder path form body.</param>
/// <response code="200">Media encoder path updated.</response>
/// <returns>Status.</returns>
[HttpPost("MediaEncoder/Path")]
[Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult UpdateMediaEncoderPath([FromForm, BindRequired] MediaEncoderPathDto mediaEncoderPath)
{
_mediaEncoder.UpdateEncoderPath(mediaEncoderPath.Path, mediaEncoderPath.PathType);
return Ok();
}
}
}

View File

@ -0,0 +1,156 @@
#nullable enable
using System;
using Jellyfin.Api.Constants;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// Devices Controller.
/// </summary>
[Authorize]
public class DevicesController : BaseJellyfinApiController
{
private readonly IDeviceManager _deviceManager;
private readonly IAuthenticationRepository _authenticationRepository;
private readonly ISessionManager _sessionManager;
/// <summary>
/// Initializes a new instance of the <see cref="DevicesController"/> class.
/// </summary>
/// <param name="deviceManager">Instance of <see cref="IDeviceManager"/> interface.</param>
/// <param name="authenticationRepository">Instance of <see cref="IAuthenticationRepository"/> interface.</param>
/// <param name="sessionManager">Instance of <see cref="ISessionManager"/> interface.</param>
public DevicesController(
IDeviceManager deviceManager,
IAuthenticationRepository authenticationRepository,
ISessionManager sessionManager)
{
_deviceManager = deviceManager;
_authenticationRepository = authenticationRepository;
_sessionManager = sessionManager;
}
/// <summary>
/// Get Devices.
/// </summary>
/// <param name="supportsSync">Gets or sets a value indicating whether [supports synchronize].</param>
/// <param name="userId">Gets or sets the user identifier.</param>
/// <response code="200">Devices retrieved.</response>
/// <returns>An <see cref="OkResult"/> containing the list of devices.</returns>
[HttpGet]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<QueryResult<DeviceInfo>> GetDevices([FromQuery] bool? supportsSync, [FromQuery] Guid? userId)
{
var deviceQuery = new DeviceQuery { SupportsSync = supportsSync, UserId = userId ?? Guid.Empty };
return _deviceManager.GetDevices(deviceQuery);
}
/// <summary>
/// Get info for a device.
/// </summary>
/// <param name="id">Device Id.</param>
/// <response code="200">Device info retrieved.</response>
/// <response code="404">Device not found.</response>
/// <returns>An <see cref="OkResult"/> containing the device info on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
[HttpGet("Info")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<DeviceInfo> GetDeviceInfo([FromQuery, BindRequired] string id)
{
var deviceInfo = _deviceManager.GetDevice(id);
if (deviceInfo == null)
{
return NotFound();
}
return deviceInfo;
}
/// <summary>
/// Get options for a device.
/// </summary>
/// <param name="id">Device Id.</param>
/// <response code="200">Device options retrieved.</response>
/// <response code="404">Device not found.</response>
/// <returns>An <see cref="OkResult"/> containing the device info on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
[HttpGet("Options")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<DeviceOptions> GetDeviceOptions([FromQuery, BindRequired] string id)
{
var deviceInfo = _deviceManager.GetDeviceOptions(id);
if (deviceInfo == null)
{
return NotFound();
}
return deviceInfo;
}
/// <summary>
/// Update device options.
/// </summary>
/// <param name="id">Device Id.</param>
/// <param name="deviceOptions">Device Options.</param>
/// <response code="200">Device options updated.</response>
/// <response code="404">Device not found.</response>
/// <returns>An <see cref="OkResult"/> on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
[HttpPost("Options")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult UpdateDeviceOptions(
[FromQuery, BindRequired] string id,
[FromBody, BindRequired] DeviceOptions deviceOptions)
{
var existingDeviceOptions = _deviceManager.GetDeviceOptions(id);
if (existingDeviceOptions == null)
{
return NotFound();
}
_deviceManager.UpdateDeviceOptions(id, deviceOptions);
return Ok();
}
/// <summary>
/// Deletes a device.
/// </summary>
/// <param name="id">Device Id.</param>
/// <response code="200">Device deleted.</response>
/// <response code="404">Device not found.</response>
/// <returns>An <see cref="OkResult"/> on success, or a <see cref="NotFoundResult"/> if the device could not be found.</returns>
[HttpDelete]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult DeleteDevice([FromQuery, BindRequired] string id)
{
var existingDevice = _deviceManager.GetDevice(id);
if (existingDevice == null)
{
return NotFound();
}
var sessions = _authenticationRepository.Get(new AuthenticationInfoQuery { DeviceId = id }).Items;
foreach (var session in sessions)
{
_sessionManager.Logout(session);
}
return Ok();
}
}
}

View File

@ -0,0 +1,159 @@
#nullable enable
#pragma warning disable CA1801
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.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// The notification controller.
/// </summary>
public class NotificationsController : BaseJellyfinApiController
{
private readonly INotificationManager _notificationManager;
private readonly IUserManager _userManager;
/// <summary>
/// Initializes a new instance of the <see cref="NotificationsController" /> class.
/// </summary>
/// <param name="notificationManager">The notification manager.</param>
/// <param name="userManager">The user manager.</param>
public NotificationsController(INotificationManager notificationManager, IUserManager userManager)
{
_notificationManager = notificationManager;
_userManager = userManager;
}
/// <summary>
/// Gets a user's notifications.
/// </summary>
/// <param name="userId">The user's ID.</param>
/// <param name="isRead">An optional filter by notification read state.</param>
/// <param name="startIndex">The optional index to start at. All notifications with a lower index will be omitted from the results.</param>
/// <param name="limit">An optional limit on the number of notifications returned.</param>
/// <response code="200">Notifications returned.</response>
/// <returns>An <see cref="OkResult"/> containing a list of notifications.</returns>
[HttpGet("{UserID}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<NotificationResultDto> GetNotifications(
[FromRoute] string userId,
[FromQuery] bool? isRead,
[FromQuery] int? startIndex,
[FromQuery] int? limit)
{
return new NotificationResultDto();
}
/// <summary>
/// Gets a user's notification summary.
/// </summary>
/// <param name="userId">The user's ID.</param>
/// <response code="200">Summary of user's notifications returned.</response>
/// <returns>An <cref see="OkResult"/> containing a summary of the users notifications.</returns>
[HttpGet("{UserID}/Summary")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<NotificationsSummaryDto> GetNotificationsSummary(
[FromRoute] string userId)
{
return new NotificationsSummaryDto();
}
/// <summary>
/// Gets notification types.
/// </summary>
/// <response code="200">All notification types returned.</response>
/// <returns>An <cref see="OkResult"/> containing a list of all notification types.</returns>
[HttpGet("Types")]
[ProducesResponseType(StatusCodes.Status200OK)]
public IEnumerable<NotificationTypeInfo> GetNotificationTypes()
{
return _notificationManager.GetNotificationTypes();
}
/// <summary>
/// Gets notification services.
/// </summary>
/// <response code="200">All notification services returned.</response>
/// <returns>An <cref see="OkResult"/> containing a list of all notification services.</returns>
[HttpGet("Services")]
[ProducesResponseType(StatusCodes.Status200OK)]
public IEnumerable<NameIdPair> GetNotificationServices()
{
return _notificationManager.GetNotificationServices();
}
/// <summary>
/// Sends a notification to all admins.
/// </summary>
/// <param name="name">The name of the notification.</param>
/// <param name="description">The description of the notification.</param>
/// <param name="url">The URL of the notification.</param>
/// <param name="level">The level of the notification.</param>
/// <response code="200">Notification sent.</response>
/// <returns>An <cref see="OkResult"/>.</returns>
[HttpPost("Admin")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult CreateAdminNotification(
[FromQuery] string name,
[FromQuery] string description,
[FromQuery] string? url,
[FromQuery] NotificationLevel? level)
{
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);
return Ok();
}
/// <summary>
/// Sets notifications as read.
/// </summary>
/// <param name="userId">The userID.</param>
/// <param name="ids">A comma-separated list of the IDs of notifications which should be set as read.</param>
/// <response code="200">Notifications set as read.</response>
/// <returns>An <cref see="OkResult"/>.</returns>
[HttpPost("{UserID}/Read")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult SetRead(
[FromRoute] string userId,
[FromQuery] string ids)
{
return Ok();
}
/// <summary>
/// Sets notifications as unread.
/// </summary>
/// <param name="userId">The userID.</param>
/// <param name="ids">A comma-separated list of the IDs of notifications which should be set as unread.</param>
/// <response code="200">Notifications set as unread.</response>
/// <returns>An <cref see="OkResult"/>.</returns>
[HttpPost("{UserID}/Unread")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult SetUnread(
[FromRoute] string userId,
[FromQuery] string ids)
{
return Ok();
}
}
}

View File

@ -5,6 +5,7 @@ using Jellyfin.Api.Models.StartupDtos;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers
@ -30,22 +31,28 @@ namespace Jellyfin.Api.Controllers
}
/// <summary>
/// Api endpoint for completing the startup wizard.
/// Completes the startup wizard.
/// </summary>
/// <response code="200">Startup wizard completed.</response>
/// <returns>An <see cref="OkResult"/> indicating success.</returns>
[HttpPost("Complete")]
public void CompleteWizard()
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult CompleteWizard()
{
_config.Configuration.IsStartupWizardCompleted = true;
_config.SetOptimalValues();
_config.SaveConfiguration();
return Ok();
}
/// <summary>
/// Endpoint for getting the initial startup wizard configuration.
/// Gets the initial startup wizard configuration.
/// </summary>
/// <returns>The initial startup wizard configuration.</returns>
/// <response code="200">Initial startup wizard configuration retrieved.</response>
/// <returns>An <see cref="OkResult"/> containing the initial startup wizard configuration.</returns>
[HttpGet("Configuration")]
public StartupConfigurationDto GetStartupConfiguration()
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<StartupConfigurationDto> GetStartupConfiguration()
{
var result = new StartupConfigurationDto
{
@ -58,13 +65,16 @@ namespace Jellyfin.Api.Controllers
}
/// <summary>
/// Endpoint for updating the initial startup wizard configuration.
/// Sets the initial startup wizard configuration.
/// </summary>
/// <param name="uiCulture">The UI language culture.</param>
/// <param name="metadataCountryCode">The metadata country code.</param>
/// <param name="preferredMetadataLanguage">The preferred language for metadata.</param>
/// <response code="200">Configuration saved.</response>
/// <returns>An <see cref="OkResult"/> indicating success.</returns>
[HttpPost("Configuration")]
public void UpdateInitialConfiguration(
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult UpdateInitialConfiguration(
[FromForm] string uiCulture,
[FromForm] string metadataCountryCode,
[FromForm] string preferredMetadataLanguage)
@ -73,43 +83,51 @@ namespace Jellyfin.Api.Controllers
_config.Configuration.MetadataCountryCode = metadataCountryCode;
_config.Configuration.PreferredMetadataLanguage = preferredMetadataLanguage;
_config.SaveConfiguration();
return Ok();
}
/// <summary>
/// Endpoint for (dis)allowing remote access and UPnP.
/// Sets remote access and UPnP.
/// </summary>
/// <param name="enableRemoteAccess">Enable remote access.</param>
/// <param name="enableAutomaticPortMapping">Enable UPnP.</param>
/// <response code="200">Configuration saved.</response>
/// <returns>An <see cref="OkResult"/> indicating success.</returns>
[HttpPost("RemoteAccess")]
public void SetRemoteAccess([FromForm] bool enableRemoteAccess, [FromForm] bool enableAutomaticPortMapping)
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult SetRemoteAccess([FromForm] bool enableRemoteAccess, [FromForm] bool enableAutomaticPortMapping)
{
_config.Configuration.EnableRemoteAccess = enableRemoteAccess;
_config.Configuration.EnableUPnP = enableAutomaticPortMapping;
_config.SaveConfiguration();
return Ok();
}
/// <summary>
/// Endpoint for returning the first user.
/// Gets the first user.
/// </summary>
/// <response code="200">Initial user retrieved.</response>
/// <returns>The first user.</returns>
[HttpGet("User")]
public StartupUserDto GetFirstUser()
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<StartupUserDto> GetFirstUser()
{
var user = _userManager.Users.First();
return new StartupUserDto
{
Name = user.Name,
Password = user.Password
};
return new StartupUserDto { Name = user.Name, Password = user.Password };
}
/// <summary>
/// Endpoint for updating the user name and password.
/// Sets the user name and password.
/// </summary>
/// <param name="startupUserDto">The DTO containing username and password.</param>
/// <returns>The async task.</returns>
/// <response code="200">Updated user name and password.</response>
/// <returns>
/// A <see cref="Task" /> that represents the asynchronous update operation.
/// The task result contains an <see cref="OkResult"/> indicating success.
/// </returns>
[HttpPost("User")]
public async Task UpdateUser([FromForm] StartupUserDto startupUserDto)
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult> UpdateUser([FromForm] StartupUserDto startupUserDto)
{
var user = _userManager.Users.First();
@ -121,6 +139,8 @@ namespace Jellyfin.Api.Controllers
{
await _userManager.ChangePassword(user, startupUserDto.Password).ConfigureAwait(false);
}
return Ok();
}
}
}

View File

@ -10,7 +10,8 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.3.3" />
<PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="5.3.3" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,18 @@
namespace Jellyfin.Api.Models.ConfigurationDtos
{
/// <summary>
/// Media Encoder Path Dto.
/// </summary>
public class MediaEncoderPathDto
{
/// <summary>
/// Gets or sets media encoder path.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets or sets media encoder path type.
/// </summary>
public string PathType { get; set; }
}
}

View File

@ -0,0 +1,53 @@
#nullable enable
using System;
using MediaBrowser.Model.Notifications;
namespace Jellyfin.Api.Models.NotificationDtos
{
/// <summary>
/// The notification DTO.
/// </summary>
public class NotificationDto
{
/// <summary>
/// Gets or sets the notification ID. Defaults to an empty string.
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the notification's user ID. Defaults to an empty string.
/// </summary>
public string UserId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the notification date.
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the notification has been read. Defaults to false.
/// </summary>
public bool IsRead { get; set; } = false;
/// <summary>
/// Gets or sets the notification's name. Defaults to an empty string.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the notification's description. Defaults to an empty string.
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the notification's URL. Defaults to an empty string.
/// </summary>
public string Url { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the notification level.
/// </summary>
public NotificationLevel Level { get; set; }
}
}

View File

@ -0,0 +1,23 @@
#nullable enable
using System;
using System.Collections.Generic;
namespace Jellyfin.Api.Models.NotificationDtos
{
/// <summary>
/// A list of notifications with the total record count for pagination.
/// </summary>
public class NotificationResultDto
{
/// <summary>
/// Gets or sets the current page of notifications.
/// </summary>
public IReadOnlyList<NotificationDto> Notifications { get; set; } = Array.Empty<NotificationDto>();
/// <summary>
/// Gets or sets the total number of notifications.
/// </summary>
public int TotalRecordCount { get; set; }
}
}

View File

@ -0,0 +1,22 @@
#nullable enable
using MediaBrowser.Model.Notifications;
namespace Jellyfin.Api.Models.NotificationDtos
{
/// <summary>
/// The notification summary DTO.
/// </summary>
public class NotificationsSummaryDto
{
/// <summary>
/// Gets or sets the number of unread notifications.
/// </summary>
public int UnreadCount { get; set; }
/// <summary>
/// Gets or sets the maximum unread notification level.
/// </summary>
public NotificationLevel? MaxUnreadNotificationLevel { get; set; }
}
}

View File

@ -1,3 +1,4 @@
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Builder;
namespace Jellyfin.Server.Extensions
@ -11,17 +12,39 @@ namespace Jellyfin.Server.Extensions
/// Adds swagger and swagger UI to the application pipeline.
/// </summary>
/// <param name="applicationBuilder">The application builder.</param>
/// <param name="serverConfigurationManager">The server configuration.</param>
/// <returns>The updated application builder.</returns>
public static IApplicationBuilder UseJellyfinApiSwagger(this IApplicationBuilder applicationBuilder)
public static IApplicationBuilder UseJellyfinApiSwagger(
this IApplicationBuilder applicationBuilder,
IServerConfigurationManager serverConfigurationManager)
{
applicationBuilder.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
return applicationBuilder.UseSwaggerUI(c =>
var baseUrl = serverConfigurationManager.Configuration.BaseUrl.Trim('/');
if (!string.IsNullOrEmpty(baseUrl))
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jellyfin API V1");
});
baseUrl += '/';
}
return applicationBuilder
.UseSwagger(c =>
{
// Custom path requires {documentName}, SwaggerDoc documentName is 'api-docs'
c.RouteTemplate = $"/{baseUrl}{{documentName}}/openapi.json";
})
.UseSwaggerUI(c =>
{
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";
c.SpecUrl($"/{baseUrl}api-docs/openapi.json");
c.RoutePrefix = $"{baseUrl}api-docs/redoc";
});
}
}
}

View File

@ -1,13 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Jellyfin.Api;
using Jellyfin.Api.Auth;
using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
using Jellyfin.Api.Auth.RequiresElevationPolicy;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Controllers;
using Jellyfin.Server.Formatters;
using MediaBrowser.Common.Json;
using MediaBrowser.Model.Entities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Jellyfin.Server.Extensions
{
@ -66,6 +75,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
@ -73,8 +84,20 @@ namespace Jellyfin.Server.Extensions
.AddApplicationPart(typeof(StartupController).Assembly)
.AddJsonOptions(options =>
{
// Setting the naming policy to null leaves the property names as-is when serializing objects to JSON.
options.JsonSerializerOptions.PropertyNamingPolicy = null;
// Update all properties that are set in JsonDefaults
var jsonOptions = JsonDefaults.PascalCase;
// From JsonDefaults
options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
options.JsonSerializerOptions.Converters.Clear();
foreach (var converter in jsonOptions.Converters)
{
options.JsonSerializerOptions.Converters.Add(converter);
}
// From JsonDefaults.PascalCase
options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
})
.AddControllersAsServices();
}
@ -88,8 +111,50 @@ 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", 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);
}
// 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);
// TODO - remove when all types are supported in System.Text.Json
c.AddSwaggerTypeMappings();
});
}
private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
{
/*
* TODO remove when System.Text.Json supports non-string keys.
* Used in Jellyfin.Api.Controller.GetChannels.
*/
options.MapType<Dictionary<ImageType, string>>(() =>
new OpenApiSchema
{
Type = "object",
Properties = typeof(ImageType).GetEnumNames().ToDictionary(
name => name,
name => new OpenApiSchema
{
Type = "string",
Format = "string"
})
});
}
}
}

View File

@ -0,0 +1,21 @@
using MediaBrowser.Common.Json;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
namespace Jellyfin.Server.Formatters
{
/// <summary>
/// Camel Case Json Profile Formatter.
/// </summary>
public class CamelCaseJsonProfileFormatter : SystemTextJsonOutputFormatter
{
/// <summary>
/// Initializes a new instance of the <see cref="CamelCaseJsonProfileFormatter"/> class.
/// </summary>
public CamelCaseJsonProfileFormatter() : base(JsonDefaults.CamelCase)
{
SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=\"CamelCase\""));
}
}
}

View File

@ -0,0 +1,23 @@
using MediaBrowser.Common.Json;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
namespace Jellyfin.Server.Formatters
{
/// <summary>
/// Pascal Case Json Profile Formatter.
/// </summary>
public class PascalCaseJsonProfileFormatter : SystemTextJsonOutputFormatter
{
/// <summary>
/// Initializes a new instance of the <see cref="PascalCaseJsonProfileFormatter"/> class.
/// </summary>
public PascalCaseJsonProfileFormatter() : base(JsonDefaults.PascalCase)
{
SupportedMediaTypes.Clear();
// Add application/json for default formatter
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=\"PascalCase\""));
}
}
}

View File

@ -0,0 +1,155 @@
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.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Server.Middleware
{
/// <summary>
/// Exception Middleware.
/// </summary>
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
private readonly IServerConfigurationManager _configuration;
private readonly IWebHostEnvironment _hostEnvironment;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
/// </summary>
/// <param name="next">Next request delegate.</param>
/// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="hostEnvironment">Instance of the <see cref="IWebHostEnvironment"/> interface.</param>
public ExceptionMiddleware(
RequestDelegate next,
ILogger<ExceptionMiddleware> logger,
IServerConfigurationManager serverConfigurationManager,
IWebHostEnvironment hostEnvironment)
{
_next = next;
_logger = logger;
_configuration = serverConfigurationManager;
_hostEnvironment = hostEnvironment;
}
/// <summary>
/// Invoke request.
/// </summary>
/// <param name="context">Request context.</param>
/// <returns>Task.</returns>
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;
}
ex = GetActualException(ex);
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}.",
context.Request.Method,
context.Request.Path);
}
context.Response.StatusCode = GetStatusCode(ex);
context.Response.ContentType = MediaTypeNames.Text.Plain;
// Don't send exception unless the server is in a Development environment
var errorContent = _hostEnvironment.IsDevelopment()
? NormalizeExceptionMessage(ex.Message)
: "Error processing request.";
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
return msg.Replace(
_configuration.ApplicationPaths.ProgramSystemPath,
string.Empty,
StringComparison.OrdinalIgnoreCase)
.Replace(
_configuration.ApplicationPaths.ProgramDataPath,
string.Empty,
StringComparison.OrdinalIgnoreCase);
}
}
}

View File

@ -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/swagger";
}
return config

View File

@ -1,4 +1,5 @@
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Middleware;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Builder;
@ -58,6 +59,8 @@ namespace Jellyfin.Server
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<ExceptionMiddleware>();
app.UseWebSockets();
app.UseResponseCompression();
@ -66,7 +69,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 =>

View File

@ -1,146 +0,0 @@
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api
{
/// <summary>
/// Class GetConfiguration
/// </summary>
[Route("/System/Configuration", "GET", Summary = "Gets application configuration")]
[Authenticated]
public class GetConfiguration : IReturn<ServerConfiguration>
{
}
[Route("/System/Configuration/{Key}", "GET", Summary = "Gets a named configuration")]
[Authenticated(AllowBeforeStartupWizard = true)]
public class GetNamedConfiguration
{
[ApiMember(Name = "Key", Description = "Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Key { get; set; }
}
/// <summary>
/// Class UpdateConfiguration
/// </summary>
[Route("/System/Configuration", "POST", Summary = "Updates application configuration")]
[Authenticated(Roles = "Admin")]
public class UpdateConfiguration : ServerConfiguration, IReturnVoid
{
}
[Route("/System/Configuration/{Key}", "POST", Summary = "Updates named configuration")]
[Authenticated(Roles = "Admin")]
public class UpdateNamedConfiguration : IReturnVoid, IRequiresRequestStream
{
[ApiMember(Name = "Key", Description = "Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Key { get; set; }
public Stream RequestStream { get; set; }
}
[Route("/System/Configuration/MetadataOptions/Default", "GET", Summary = "Gets a default MetadataOptions object")]
[Authenticated(Roles = "Admin")]
public class GetDefaultMetadataOptions : IReturn<MetadataOptions>
{
}
[Route("/System/MediaEncoder/Path", "POST", Summary = "Updates the path to the media encoder")]
[Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
public class UpdateMediaEncoderPath : IReturnVoid
{
[ApiMember(Name = "Path", Description = "Path", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public string Path { get; set; }
[ApiMember(Name = "PathType", Description = "PathType", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public string PathType { get; set; }
}
public class ConfigurationService : BaseApiService
{
/// <summary>
/// The _json serializer
/// </summary>
private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// The _configuration manager
/// </summary>
private readonly IServerConfigurationManager _configurationManager;
private readonly IMediaEncoder _mediaEncoder;
public ConfigurationService(
ILogger<ConfigurationService> logger,
IServerConfigurationManager serverConfigurationManager,
IHttpResultFactory httpResultFactory,
IJsonSerializer jsonSerializer,
IServerConfigurationManager configurationManager,
IMediaEncoder mediaEncoder)
: base(logger, serverConfigurationManager, httpResultFactory)
{
_jsonSerializer = jsonSerializer;
_configurationManager = configurationManager;
_mediaEncoder = mediaEncoder;
}
public void Post(UpdateMediaEncoderPath request)
{
_mediaEncoder.UpdateEncoderPath(request.Path, request.PathType);
}
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get(GetConfiguration request)
{
return ToOptimizedResult(_configurationManager.Configuration);
}
public object Get(GetNamedConfiguration request)
{
var result = _configurationManager.GetConfiguration(request.Key);
return ToOptimizedResult(result);
}
/// <summary>
/// Posts the specified configuraiton.
/// </summary>
/// <param name="request">The request.</param>
public void Post(UpdateConfiguration request)
{
// Silly, but we need to serialize and deserialize or the XmlSerializer will write the xml with an element name of UpdateConfiguration
var json = _jsonSerializer.SerializeToString(request);
var config = _jsonSerializer.DeserializeFromString<ServerConfiguration>(json);
_configurationManager.ReplaceConfiguration(config);
}
public async Task Post(UpdateNamedConfiguration request)
{
var key = GetPathValue(2).ToString();
var configurationType = _configurationManager.GetConfigurationType(key);
var configuration = await _jsonSerializer.DeserializeFromStreamAsync(request.RequestStream, configurationType).ConfigureAwait(false);
_configurationManager.SaveConfiguration(key, configuration);
}
public object Get(GetDefaultMetadataOptions request)
{
return ToOptimizedResult(new MetadataOptions());
}
}
}

View File

@ -1,168 +0,0 @@
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Devices
{
[Route("/Devices", "GET", Summary = "Gets all devices")]
[Authenticated(Roles = "Admin")]
public class GetDevices : DeviceQuery, IReturn<QueryResult<DeviceInfo>>
{
}
[Route("/Devices/Info", "GET", Summary = "Gets info for a device")]
[Authenticated(Roles = "Admin")]
public class GetDeviceInfo : IReturn<DeviceInfo>
{
[ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string Id { get; set; }
}
[Route("/Devices/Options", "GET", Summary = "Gets options for a device")]
[Authenticated(Roles = "Admin")]
public class GetDeviceOptions : IReturn<DeviceOptions>
{
[ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string Id { get; set; }
}
[Route("/Devices", "DELETE", Summary = "Deletes a device")]
public class DeleteDevice
{
[ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
public string Id { get; set; }
}
[Route("/Devices/CameraUploads", "GET", Summary = "Gets camera upload history for a device")]
[Authenticated]
public class GetCameraUploads : IReturn<ContentUploadHistory>
{
[ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string DeviceId { get; set; }
}
[Route("/Devices/CameraUploads", "POST", Summary = "Uploads content")]
[Authenticated]
public class PostCameraUpload : IRequiresRequestStream, IReturnVoid
{
[ApiMember(Name = "DeviceId", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string DeviceId { get; set; }
[ApiMember(Name = "Album", Description = "Album", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Album { get; set; }
[ApiMember(Name = "Name", Description = "Name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Name { get; set; }
[ApiMember(Name = "Id", Description = "Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Id { get; set; }
public Stream RequestStream { get; set; }
}
[Route("/Devices/Options", "POST", Summary = "Updates device options")]
[Authenticated(Roles = "Admin")]
public class PostDeviceOptions : DeviceOptions, IReturnVoid
{
[ApiMember(Name = "Id", Description = "Device Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
public string Id { get; set; }
}
public class DeviceService : BaseApiService
{
private readonly IDeviceManager _deviceManager;
private readonly IAuthenticationRepository _authRepo;
private readonly ISessionManager _sessionManager;
public DeviceService(
ILogger<DeviceService> logger,
IServerConfigurationManager serverConfigurationManager,
IHttpResultFactory httpResultFactory,
IDeviceManager deviceManager,
IAuthenticationRepository authRepo,
ISessionManager sessionManager)
: base(logger, serverConfigurationManager, httpResultFactory)
{
_deviceManager = deviceManager;
_authRepo = authRepo;
_sessionManager = sessionManager;
}
public void Post(PostDeviceOptions request)
{
_deviceManager.UpdateDeviceOptions(request.Id, request);
}
public object Get(GetDevices request)
{
return ToOptimizedResult(_deviceManager.GetDevices(request));
}
public object Get(GetDeviceInfo request)
{
return _deviceManager.GetDevice(request.Id);
}
public object Get(GetDeviceOptions request)
{
return _deviceManager.GetDeviceOptions(request.Id);
}
public object Get(GetCameraUploads request)
{
return ToOptimizedResult(_deviceManager.GetCameraUploadHistory(request.DeviceId));
}
public void Delete(DeleteDevice request)
{
var sessions = _authRepo.Get(new AuthenticationInfoQuery
{
DeviceId = request.Id
}).Items;
foreach (var session in sessions)
{
_sessionManager.Logout(session);
}
}
public Task Post(PostCameraUpload request)
{
var deviceId = Request.QueryString["DeviceId"];
var album = Request.QueryString["Album"];
var id = Request.QueryString["Id"];
var name = Request.QueryString["Name"];
var req = Request.Response.HttpContext.Request;
if (req.HasFormContentType)
{
var file = req.Form.Files.Count == 0 ? null : req.Form.Files[0];
return _deviceManager.AcceptCameraUpload(deviceId, file.OpenReadStream(), new LocalFileInfo
{
MimeType = file.ContentType,
Album = album,
Name = name,
Id = id
});
}
return _deviceManager.AcceptCameraUpload(deviceId, request.RequestStream, new LocalFileInfo
{
MimeType = Request.ContentType,
Album = album,
Name = name,
Id = id
});
}
}
}

View File

@ -42,23 +42,6 @@ namespace MediaBrowser.Api
[Authenticated]
public class GetPackages : IReturn<PackageInfo[]>
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
[ApiMember(Name = "PackageType", Description = "Optional package type filter (System/UserInstalled)", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string PackageType { get; set; }
[ApiMember(Name = "TargetSystems", Description = "Optional. Filter by target system type. Allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string TargetSystems { get; set; }
[ApiMember(Name = "IsPremium", Description = "Optional. Filter by premium status", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? IsPremium { get; set; }
[ApiMember(Name = "IsAdult", Description = "Optional. Filter by package that contain adult content.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? IsAdult { get; set; }
public bool? IsAppStoreEnabled { get; set; }
}
/// <summary>
@ -88,13 +71,6 @@ namespace MediaBrowser.Api
/// <value>The version.</value>
[ApiMember(Name = "Version", Description = "Optional version. Defaults to latest version.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Version { get; set; }
/// <summary>
/// Gets or sets the update class.
/// </summary>
/// <value>The update class.</value>
[ApiMember(Name = "UpdateClass", Description = "Optional update class (Dev, Beta, Release). Defaults to Release.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public PackageVersionClass UpdateClass { get; set; }
}
/// <summary>
@ -154,23 +130,6 @@ namespace MediaBrowser.Api
{
IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false);
if (!string.IsNullOrEmpty(request.TargetSystems))
{
var apps = request.TargetSystems.Split(',').Select(i => (PackageTargetSystem)Enum.Parse(typeof(PackageTargetSystem), i, true));
packages = packages.Where(p => apps.Contains(p.targetSystem));
}
if (request.IsAdult.HasValue)
{
packages = packages.Where(p => p.adult == request.IsAdult.Value);
}
if (request.IsAppStoreEnabled.HasValue)
{
packages = packages.Where(p => p.enableInAppStore == request.IsAppStoreEnabled.Value);
}
return ToOptimizedResult(packages.ToArray());
}
@ -186,8 +145,7 @@ namespace MediaBrowser.Api
packages,
request.Name,
string.IsNullOrEmpty(request.AssemblyGuid) ? Guid.Empty : Guid.Parse(request.AssemblyGuid),
string.IsNullOrEmpty(request.Version) ? null : Version.Parse(request.Version),
request.UpdateClass).FirstOrDefault();
string.IsNullOrEmpty(request.Version) ? null : Version.Parse(request.Version)).FirstOrDefault();
if (package == null)
{

View File

@ -134,7 +134,7 @@ namespace MediaBrowser.Api.Playback
var data = $"{state.MediaPath}-{state.UserAgent}-{state.Request.DeviceId}-{state.Request.PlaySessionId}";
var filename = data.GetMD5().ToString("N", CultureInfo.InvariantCulture);
var ext = outputFileExtension.ToLowerInvariant();
var ext = outputFileExtension?.ToLowerInvariant();
var folder = ServerConfigurationManager.GetTranscodePath();
return EnableOutputInSubFolder

View File

@ -242,11 +242,11 @@ namespace MediaBrowser.Api.UserLibrary
return folder.GetItems(GetItemsQuery(request, dtoOptions, user));
}
var itemsArray = folder.GetChildren(user, true).ToArray();
var itemsArray = folder.GetChildren(user, true);
return new QueryResult<BaseItem>
{
Items = itemsArray,
TotalRecordCount = itemsArray.Length,
TotalRecordCount = itemsArray.Count,
StartIndex = 0
};
}

View File

@ -48,12 +48,6 @@ namespace MediaBrowser.Common
/// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
bool CanSelfRestart { get; }
/// <summary>
/// Gets the version class of the system.
/// </summary>
/// <value><see cref="PackageVersionClass.Release" /> or <see cref="PackageVersionClass.Beta" />.</value>
PackageVersionClass SystemUpdateLevel { get; }
/// <summary>
/// Gets the application version.
/// </summary>

View File

@ -0,0 +1,78 @@
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// Converter for Dictionaries without string key.
/// TODO This can be removed when System.Text.Json supports Dictionaries with non-string keys.
/// </summary>
/// <typeparam name="TKey">Type of key.</typeparam>
/// <typeparam name="TValue">Type of value.</typeparam>
internal sealed class JsonNonStringKeyDictionaryConverter<TKey, TValue> : JsonConverter<IDictionary<TKey, TValue>>
{
/// <summary>
/// Read JSON.
/// </summary>
/// <param name="reader">The Utf8JsonReader.</param>
/// <param name="typeToConvert">The type to convert.</param>
/// <param name="options">The json serializer options.</param>
/// <returns>Typed dictionary.</returns>
/// <exception cref="NotSupportedException"></exception>
public override IDictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var convertedType = typeof(Dictionary<,>).MakeGenericType(typeof(string), typeToConvert.GenericTypeArguments[1]);
var value = JsonSerializer.Deserialize(ref reader, convertedType, options);
var instance = (Dictionary<TKey, TValue>)Activator.CreateInstance(
typeToConvert,
BindingFlags.Instance | BindingFlags.Public,
null,
null,
CultureInfo.CurrentCulture);
var enumerator = (IEnumerator)convertedType.GetMethod("GetEnumerator")!.Invoke(value, null);
var parse = typeof(TKey).GetMethod(
"Parse",
0,
BindingFlags.Public | BindingFlags.Static,
null,
CallingConventions.Any,
new[] { typeof(string) },
null);
if (parse == null)
{
throw new NotSupportedException($"{typeof(TKey)} as TKey in IDictionary<TKey, TValue> is not supported.");
}
while (enumerator.MoveNext())
{
var element = (KeyValuePair<string?, TValue>)enumerator.Current;
instance.Add((TKey)parse.Invoke(null, new[] { (object?) element.Key }), element.Value);
}
return instance;
}
/// <summary>
/// Write dictionary as Json.
/// </summary>
/// <param name="writer">The Utf8JsonWriter.</param>
/// <param name="value">The dictionary value.</param>
/// <param name="options">The Json serializer options.</param>
public override void Write(Utf8JsonWriter writer, IDictionary<TKey, TValue> value, JsonSerializerOptions options)
{
var convertedDictionary = new Dictionary<string?, TValue>(value.Count);
foreach (var (k, v) in value)
{
convertedDictionary[k?.ToString()] = v;
}
JsonSerializer.Serialize(writer, convertedDictionary, options);
}
}
}

View File

@ -0,0 +1,60 @@
#nullable enable
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// https://github.com/dotnet/runtime/issues/30524#issuecomment-524619972.
/// TODO This can be removed when System.Text.Json supports Dictionaries with non-string keys.
/// </summary>
internal sealed class JsonNonStringKeyDictionaryConverterFactory : JsonConverterFactory
{
/// <summary>
/// Only convert objects that implement IDictionary and do not have string keys.
/// </summary>
/// <param name="typeToConvert">Type convert.</param>
/// <returns>Conversion ability.</returns>
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
{
return false;
}
// Let built in converter handle string keys
if (typeToConvert.GenericTypeArguments[0] == typeof(string))
{
return false;
}
// Only support objects that implement IDictionary
return typeToConvert.GetInterface(nameof(IDictionary)) != null;
}
/// <summary>
/// Create converter for generic dictionary type.
/// </summary>
/// <param name="typeToConvert">Type to convert.</param>
/// <param name="options">Json serializer options.</param>
/// <returns>JsonConverter for given type.</returns>
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var converterType = typeof(JsonNonStringKeyDictionaryConverter<,>)
.MakeGenericType(typeToConvert.GenericTypeArguments[0], typeToConvert.GenericTypeArguments[1]);
var converter = (JsonConverter)Activator.CreateInstance(
converterType,
BindingFlags.Instance | BindingFlags.Public,
null,
null,
CultureInfo.CurrentCulture);
return converter;
}
}
}

View File

@ -12,10 +12,16 @@ namespace MediaBrowser.Common.Json
/// <summary>
/// Gets the default <see cref="JsonSerializerOptions" /> options.
/// </summary>
/// <remarks>
/// When changing these options, update
/// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
/// -> AddJellyfinApi
/// -> AddJsonOptions
/// </remarks>
/// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
public static JsonSerializerOptions GetOptions()
{
var options = new JsonSerializerOptions()
var options = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Disallow,
WriteIndented = false
@ -23,9 +29,35 @@ namespace MediaBrowser.Common.Json
options.Converters.Add(new JsonGuidConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new JsonInt64Converter());
options.Converters.Add(new JsonNonStringKeyDictionaryConverterFactory());
return options;
}
/// <summary>
/// Gets CamelCase json options.
/// </summary>
public static JsonSerializerOptions CamelCase
{
get
{
var options = GetOptions();
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
return options;
}
}
/// <summary>
/// Gets PascalCase json options.
/// </summary>
public static JsonSerializerOptions PascalCase
{
get
{
var options = GetOptions();
options.PropertyNamingPolicy = null;
return options;
}
}
}
}

View File

@ -67,7 +67,7 @@ namespace MediaBrowser.Common.Plugins
}
/// <summary>
/// Called when just before the plugin is uninstalled from the server.
/// Called just before the plugin is uninstalled from the server.
/// </summary>
public virtual void OnUninstalling()
{
@ -101,7 +101,7 @@ namespace MediaBrowser.Common.Plugins
private readonly object _configurationSyncLock = new object();
/// <summary>
/// The save lock.
/// The configuration save lock.
/// </summary>
private readonly object _configurationSaveLock = new object();
@ -148,7 +148,7 @@ namespace MediaBrowser.Common.Plugins
protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath);
/// <summary>
/// Gets or sets the plugin's configuration.
/// Gets or sets the plugin configuration.
/// </summary>
/// <value>The configuration.</value>
public TConfigurationType Configuration
@ -186,7 +186,7 @@ namespace MediaBrowser.Common.Plugins
public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName);
/// <summary>
/// Gets the plugin's configuration.
/// Gets the plugin configuration.
/// </summary>
/// <value>The configuration.</value>
BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration;

View File

@ -28,12 +28,12 @@ namespace MediaBrowser.Common.Updates
/// <summary>
/// Occurs when a plugin is updated.
/// </summary>
event EventHandler<GenericEventArgs<(IPlugin, PackageVersionInfo)>> PluginUpdated;
event EventHandler<GenericEventArgs<(IPlugin, VersionInfo)>> PluginUpdated;
/// <summary>
/// Occurs when a plugin is installed.
/// </summary>
event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
event EventHandler<GenericEventArgs<VersionInfo>> PluginInstalled;
/// <summary>
/// Gets the completed installations.
@ -64,12 +64,10 @@ namespace MediaBrowser.Common.Updates
/// </summary>
/// <param name="availableVersions">The available version of the plugin.</param>
/// <param name="minVersion">The minimum required version of the plugin.</param>
/// <param name="classification">The classification of updates.</param>
/// <returns>All compatible versions ordered from newest to oldest.</returns>
IEnumerable<PackageVersionInfo> GetCompatibleVersions(
IEnumerable<PackageVersionInfo> availableVersions,
Version minVersion = null,
PackageVersionClass classification = PackageVersionClass.Release);
IEnumerable<VersionInfo> GetCompatibleVersions(
IEnumerable<VersionInfo> availableVersions,
Version minVersion = null);
/// <summary>
/// Returns all compatible versions ordered from newest to oldest.
@ -78,21 +76,19 @@ namespace MediaBrowser.Common.Updates
/// <param name="name">The name.</param>
/// <param name="guid">The guid of the plugin.</param>
/// <param name="minVersion">The minimum required version of the plugin.</param>
/// <param name="classification">The classification.</param>
/// <returns>All compatible versions ordered from newest to oldest.</returns>
IEnumerable<PackageVersionInfo> GetCompatibleVersions(
IEnumerable<VersionInfo> GetCompatibleVersions(
IEnumerable<PackageInfo> availablePackages,
string name = null,
Guid guid = default,
Version minVersion = null,
PackageVersionClass classification = PackageVersionClass.Release);
Version minVersion = null);
/// <summary>
/// Returns the available plugin updates.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The available plugin updates.</returns>
Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default);
Task<IEnumerable<VersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default);
/// <summary>
/// Installs the package.
@ -100,7 +96,7 @@ namespace MediaBrowser.Common.Updates
/// <param name="package">The package.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns><see cref="Task" />.</returns>
Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken = default);
Task InstallPackage(VersionInfo package, CancellationToken cancellationToken = default);
/// <summary>
/// Uninstalls a plugin.

View File

@ -8,6 +8,6 @@ namespace MediaBrowser.Common.Updates
{
public InstallationInfo InstallationInfo { get; set; }
public PackageVersionInfo PackageVersionInfo { get; set; }
public VersionInfo VersionInfo { get; set; }
}
}

View File

@ -549,7 +549,6 @@ namespace MediaBrowser.Controller.Entities
[JsonIgnore]
public DateTime DateModified { get; set; }
[JsonIgnore]
public DateTime DateLastSaved { get; set; }
[JsonIgnore]
@ -2741,7 +2740,7 @@ namespace MediaBrowser.Controller.Entities
{
var list = GetEtagValues(user);
return string.Join("|", list.ToArray()).GetMD5().ToString("N", CultureInfo.InvariantCulture);
return string.Join("|", list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
protected virtual List<string> GetEtagValues(User user)
@ -2784,8 +2783,7 @@ namespace MediaBrowser.Controller.Entities
return true;
}
var view = this as IHasCollectionType;
if (view != null)
if (this is IHasCollectionType view)
{
if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
{

View File

@ -864,7 +864,7 @@ namespace MediaBrowser.Controller.Entities
return SortItemsByRequest(query, result);
}
return result.ToArray();
return result;
}
return GetItemsInternal(query).Items;

View File

@ -478,7 +478,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
_logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument);
_logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments}", inputArgument);
}
}
@ -969,7 +969,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
public int? ExitCode { get; private set; }
void OnProcessExited(object sender, EventArgs e)
private void OnProcessExited(object sender, EventArgs e)
{
var process = (Process)sender;

View File

@ -8,17 +8,17 @@ namespace MediaBrowser.Model.Services
{
/// <summary>
/// Order in which Request Filters are executed.
/// &lt;0 Executed before global request filters
/// &gt;0 Executed after global request filters
/// &lt;0 Executed before global request filters.
/// &gt;0 Executed after global request filters.
/// </summary>
int Priority { get; }
/// <summary>
/// The request filter is executed before the service.
/// </summary>
/// <param name="req">The http request wrapper</param>
/// <param name="res">The http response wrapper</param>
/// <param name="requestDto">The request DTO</param>
/// <param name="req">The http request wrapper.</param>
/// <param name="res">The http response wrapper.</param>
/// <param name="requestDto">The request DTO.</param>
void RequestFilter(IRequest req, HttpResponse res, object requestDto);
}
}

View File

@ -26,8 +26,6 @@ namespace MediaBrowser.Model.System
/// </summary>
public class SystemInfo : PublicSystemInfo
{
public PackageVersionClass SystemUpdateLevel { get; set; }
/// <summary>
/// Gets or sets the display name of the operating system.
/// </summary>

View File

@ -1,29 +0,0 @@
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Class CheckForUpdateResult.
/// </summary>
public class CheckForUpdateResult
{
/// <summary>
/// Gets or sets a value indicating whether this instance is update available.
/// </summary>
/// <value><c>true</c> if this instance is update available; otherwise, <c>false</c>.</value>
public bool IsUpdateAvailable { get; set; }
/// <summary>
/// Gets or sets the available version.
/// </summary>
/// <value>The available version.</value>
public string AvailableVersion
{
get => Package != null ? Package.versionStr : "0.0.0.1";
set { } // need this for the serializer
}
/// <summary>
/// Get or sets package information for an available update
/// </summary>
public PackageVersionInfo Package { get; set; }
}
}

View File

@ -8,10 +8,10 @@ namespace MediaBrowser.Model.Updates
public class InstallationInfo
{
/// <summary>
/// Gets or sets the id.
/// Gets or sets the guid.
/// </summary>
/// <value>The id.</value>
public Guid Id { get; set; }
/// <value>The guid.</value>
public string Guid { get; set; }
/// <summary>
/// Gets or sets the name.
@ -19,22 +19,10 @@ namespace MediaBrowser.Model.Updates
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the assembly guid.
/// </summary>
/// <value>The guid of the assembly.</value>
public string AssemblyGuid { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the update class.
/// </summary>
/// <value>The update class.</value>
public PackageVersionClass UpdateClass { get; set; }
}
}

View File

@ -8,12 +8,6 @@ namespace MediaBrowser.Model.Updates
/// </summary>
public class PackageInfo
{
/// <summary>
/// The internal id of this package.
/// </summary>
/// <value>The id.</value>
public string id { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
@ -21,59 +15,17 @@ namespace MediaBrowser.Model.Updates
public string name { get; set; }
/// <summary>
/// Gets or sets the short description.
/// Gets or sets a long description of the plugin containing features or helpful explanations.
/// </summary>
/// <value>The short description.</value>
public string shortDescription { get; set; }
/// <value>The description.</value>
public string description { get; set; }
/// <summary>
/// Gets or sets the overview.
/// Gets or sets a short overview of what the plugin does.
/// </summary>
/// <value>The overview.</value>
public string overview { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is premium.
/// </summary>
/// <value><c>true</c> if this instance is premium; otherwise, <c>false</c>.</value>
public bool isPremium { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is adult only content.
/// </summary>
/// <value><c>true</c> if this instance is adult; otherwise, <c>false</c>.</value>
public bool adult { get; set; }
/// <summary>
/// Gets or sets the rich desc URL.
/// </summary>
/// <value>The rich desc URL.</value>
public string richDescUrl { get; set; }
/// <summary>
/// Gets or sets the thumb image.
/// </summary>
/// <value>The thumb image.</value>
public string thumbImage { get; set; }
/// <summary>
/// Gets or sets the preview image.
/// </summary>
/// <value>The preview image.</value>
public string previewImage { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public string type { get; set; }
/// <summary>
/// Gets or sets the target filename.
/// </summary>
/// <value>The target filename.</value>
public string targetFilename { get; set; }
/// <summary>
/// Gets or sets the owner.
/// </summary>
@ -87,90 +39,24 @@ namespace MediaBrowser.Model.Updates
public string category { get; set; }
/// <summary>
/// Gets or sets the catalog tile color.
/// </summary>
/// <value>The owner.</value>
public string tileColor { get; set; }
/// <summary>
/// Gets or sets the feature id of this package (if premium).
/// </summary>
/// <value>The feature id.</value>
public string featureId { get; set; }
/// <summary>
/// Gets or sets the registration info for this package (if premium).
/// </summary>
/// <value>The registration info.</value>
public string regInfo { get; set; }
/// <summary>
/// Gets or sets the price for this package (if premium).
/// </summary>
/// <value>The price.</value>
public float price { get; set; }
/// <summary>
/// Gets or sets the target system for this plug-in (Server, MBTheater, MBClassic).
/// </summary>
/// <value>The target system.</value>
public PackageTargetSystem targetSystem { get; set; }
/// <summary>
/// The guid of the assembly associated with this package (if a plug-in).
/// The guid of the assembly associated with this plugin.
/// This is used to identify the proper item for automatic updates.
/// </summary>
/// <value>The name.</value>
public string guid { get; set; }
/// <summary>
/// Gets or sets the total number of ratings for this package.
/// </summary>
/// <value>The total ratings.</value>
public int? totalRatings { get; set; }
/// <summary>
/// Gets or sets the average rating for this package .
/// </summary>
/// <value>The rating.</value>
public float avgRating { get; set; }
/// <summary>
/// Gets or sets whether or not this package is registered.
/// </summary>
/// <value>True if registered.</value>
public bool isRegistered { get; set; }
/// <summary>
/// Gets or sets the expiration date for this package.
/// </summary>
/// <value>Expiration Date.</value>
public DateTime expDate { get; set; }
/// <summary>
/// Gets or sets the versions.
/// </summary>
/// <value>The versions.</value>
public IReadOnlyList<PackageVersionInfo> versions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [enable in application store].
/// </summary>
/// <value><c>true</c> if [enable in application store]; otherwise, <c>false</c>.</value>
public bool enableInAppStore { get; set; }
/// <summary>
/// Gets or sets the installs.
/// </summary>
/// <value>The installs.</value>
public int installs { get; set; }
public IReadOnlyList<VersionInfo> versions { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PackageInfo"/> class.
/// </summary>
public PackageInfo()
{
versions = Array.Empty<PackageVersionInfo>();
versions = Array.Empty<VersionInfo>();
}
}
}

View File

@ -1,23 +0,0 @@
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Enum PackageType.
/// </summary>
public enum PackageTargetSystem
{
/// <summary>
/// Server.
/// </summary>
Server,
/// <summary>
/// MB Theater.
/// </summary>
MBTheater,
/// <summary>
/// MB Classic.
/// </summary>
MBClassic
}
}

View File

@ -1,23 +0,0 @@
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Enum PackageVersionClass.
/// </summary>
public enum PackageVersionClass
{
/// <summary>
/// The release.
/// </summary>
Release = 0,
/// <summary>
/// The beta.
/// </summary>
Beta = 1,
/// <summary>
/// The dev.
/// </summary>
Dev = 2
}
}

View File

@ -1,96 +0,0 @@
#pragma warning disable CS1591
using System;
using System.Text.Json.Serialization;
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Class PackageVersionInfo.
/// </summary>
public class PackageVersionInfo
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string name { get; set; }
/// <summary>
/// Gets or sets the guid.
/// </summary>
/// <value>The guid.</value>
public string guid { get; set; }
/// <summary>
/// Gets or sets the version STR.
/// </summary>
/// <value>The version STR.</value>
public string versionStr { get; set; }
/// <summary>
/// The _version
/// </summary>
private Version _version;
/// <summary>
/// Gets or sets the version.
/// Had to make this an interpreted property since Protobuf can't handle Version
/// </summary>
/// <value>The version.</value>
[JsonIgnore]
public Version Version
{
get
{
if (_version == null)
{
var ver = versionStr;
_version = new Version(string.IsNullOrEmpty(ver) ? "0.0.0.1" : ver);
}
return _version;
}
}
/// <summary>
/// Gets or sets the classification.
/// </summary>
/// <value>The classification.</value>
public PackageVersionClass classification { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string description { get; set; }
/// <summary>
/// Gets or sets the required version STR.
/// </summary>
/// <value>The required version STR.</value>
public string requiredVersionStr { get; set; }
/// <summary>
/// Gets or sets the source URL.
/// </summary>
/// <value>The source URL.</value>
public string sourceUrl { get; set; }
/// <summary>
/// Gets or sets the source URL.
/// </summary>
/// <value>The source URL.</value>
public string checksum { get; set; }
/// <summary>
/// Gets or sets the target filename.
/// </summary>
/// <value>The target filename.</value>
public string targetFilename { get; set; }
public string infoUrl { get; set; }
public string runtimes { get; set; }
}
}

View File

@ -0,0 +1,58 @@
using System;
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Class PackageVersionInfo.
/// </summary>
public class VersionInfo
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string name { get; set; }
/// <summary>
/// Gets or sets the guid.
/// </summary>
/// <value>The guid.</value>
public string guid { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
public Version version { get; set; }
/// <summary>
/// Gets or sets the changelog for this version.
/// </summary>
/// <value>The changelog.</value>
public string changelog { get; set; }
/// <summary>
/// Gets or sets the ABI that this version was built against.
/// </summary>
/// <value>The target ABI version.</value>
public string targetAbi { get; set; }
/// <summary>
/// Gets or sets the source URL.
/// </summary>
/// <value>The source URL.</value>
public string sourceUrl { get; set; }
/// <summary>
/// Gets or sets a checksum for the binary.
/// </summary>
/// <value>The checksum.</value>
public string checksum { get; set; }
/// <summary>
/// Gets or sets the target filename for the downloaded binary.
/// </summary>
/// <value>The target filename.</value>
public string filename { get; set; }
}
}

View File

@ -208,8 +208,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers
protected void ParseProviderLinks(T item, string xml)
{
// Look for a match for the Regex pattern "tt" followed by 7 digits
var m = Regex.Match(xml, @"tt([0-9]{7})", RegexOptions.IgnoreCase);
// Look for a match for the Regex pattern "tt" followed by 7 or 8 digits
var m = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.IgnoreCase);
if (m.Success)
{
item.SetProviderId(MetadataProviders.Imdb, m.Value);

View File

@ -69,3 +69,99 @@ Most of the translations can be found in the web client but we have several othe
<a href="https://translate.jellyfin.org/engage/jellyfin/?utm_source=widget">
<img src="https://translate.jellyfin.org/widgets/jellyfin/-/jellyfin-web/multi-auto.svg" alt="Detailed Translation Status"/>
</a>
## Jellyfin Server
This repository contains the code for Jellyfin's backend server. Note that this is only one of many projects under the Jellyfin GitHub [organization](https://github.com/jellyfin/) on GitHub. If you want to contribute, you can start by checking out our [documentation](https://jellyfin.org/docs/general/contributing/index.html) to see what to work on.
## Server Development
These instructions will help you get set up with a local development environment in order to contribute to this repository. Before you start, please be sure to completely read our [guidelines on development contributions](https://jellyfin.org/docs/general/contributing/development.html). Note that this project is supported on all major operating systems except FreeBSD, which is still incompatible.
### Prerequisites
Before the project can be built, you must first install the [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download) on your system.
Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download).
### Cloning the Repository
After dependencies are installed you will need to clone a local copy of this repository. If you just want to run the server from source you can clone this repository directly, but if you are intending to contribute code changes to the project, you should [set up your own fork](https://jellyfin.org/docs/general/contributing/development.html#set-up-your-copy-of-the-repo) of the repository. The following example shows how you can clone the repository directly over HTTPS.
```bash
git clone https://github.com/jellyfin/jellyfin.git
```
### Installing the Web Client
The server is configured to host the static files required for the [web client](https://github.com/jellyfin/jellyfin-web) in addition to serving the backend by default. Before you can run the server, you will need to get a copy of the web client since they are not included in this repository directly.
Note that it is also possible to [host the web client separately](#hosting-the-web-client-separately) from the web server with some additional configuration, in which case you can skip this step.
There are three options to get the files for the web client.
1. Download one of the finished builds from the [Azure DevOps pipeline](https://dev.azure.com/jellyfin-project/jellyfin/_build?definitionId=11). You can download the build for a specific release by looking at the [branches tab](https://dev.azure.com/jellyfin-project/jellyfin/_build?definitionId=11&_a=summary&repositoryFilter=6&view=branches) of the pipelines page.
2. Build them from source following the instructions on the [jellyfin-web repository](https://github.com/jellyfin/jellyfin-web)
3. Get the pre-built files from an existing installation of the server. For example, with a Windows server installation the client files are located at `C:\Program Files\Jellyfin\Server\jellyfin-web`
Once you have a copy of the built web client files, you need to copy them into a specific directory.
> `<repository root>/Mediabrowser.WebDashboard/jellyfin-web`
As part of the build process, this folder will be copied to the build output directory, where it can be accessed by the server.
### Running The Server
The following instructions will help you get the project up and running via the command line, or your preferred IDE.
#### Running With Visual Studio
To run the project with Visual Studio you can open the Solution (`.sln`) file and then press `F5` to run the server.
#### Running With Visual Studio Code
To run the project with Visual Studio Code you will first need to open the repository directory with Visual Studio Code using the `Open Folder...` option.
Second, you need to [install the recommended extensions for the workspace](https://code.visualstudio.com/docs/editor/extension-gallery#_recommended-extensions). Note that extension recommendations are classified as either "Workspace Recommendations" or "Other Recommendations", but only the "Workspace Recommendations" are required.
After the required extensions are installed, you can can run the server by pressing `F5`.
#### Running From The Command Line
To run the server from the command line you can use the `dotnet run` command. The example below shows how to do this if you have cloned the repository into a directory named `jellyfin` (the default directory name) and should work on all operating systems.
```bash
cd jellyfin # Move into the repository directory
dotnet run --project Jellyfin.Server # Run the server startup project
```
A second option is to build the project and then run the resulting executable file directly. When running the executable directly you can easily add command line options. Add the `--help` flag to list details on all the supported command line options.
1. Build the project
```bash
dotnet build # Build the project
cd bin/Debug/netcoreapp3.1 # Change into the build output directory
```
2. Execute the build output. On Linux, Mac, etc. use `./jellyfin` and on Windows use `jellyfin.exe`.
### Running The Tests
This repository also includes unit tests that are used to validate functionality as part of a CI pipeline on Azure. There are several ways to run these tests.
1. Run tests from the command line using `dotnet test`
2. Run tests in Visual Studio using the [Test Explorer](https://docs.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer)
3. Run individual tests in Visual Studio Code using the associated [CodeLens annotation](https://github.com/OmniSharp/omnisharp-vscode/wiki/How-to-run-and-debug-unit-tests)
### Advanced Configuration
The following sections describe some more advanced scenarios for running the server from source that build upon the standard instructions above.
#### Hosting The Web Client Separately
It is not necessary to host the frontend web client as part of the backend server. Hosting these two components separately may be useful for frontend developers who would prefer to host the client in a separate webpack development server for a tighter development loop. See the [jellyfin-web](https://github.com/jellyfin/jellyfin-web#getting-started) repo for instructions on how to do this.
To instruct the server not to host the web content, there is a `nowebcontent` configuration flag that must be set. This can specified using the command line switch `--nowebcontent` or the environment variable `JELLYFIN_NOWEBCONTENT=true`.
Since this is a common scenario, there is also a separate launch profile defined for Visual Studio called `Jellyfin.Server (nowebcontent)` that can be selected from the 'Start Debugging' dropdown in the main toolbar.