diff options
292 files changed, 4046 insertions, 3444 deletions
diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml index 31f861f63..cf74a4201 100644 --- a/.ci/azure-pipelines-abi.yml +++ b/.ci/azure-pipelines-abi.yml @@ -34,7 +34,6 @@ jobs: inputs: packageType: sdk version: ${{ parameters.DotNetSdkVersion }} - includePreviewVersions: true - task: DotNetCoreCLI@2 displayName: 'Install ABI CompatibilityChecker Tool' diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index 1086d51d2..b7112ba24 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -54,7 +54,6 @@ jobs: inputs: packageType: sdk version: ${{ parameters.DotNetSdkVersion }} - includePreviewVersions: true - task: DotNetCoreCLI@2 displayName: 'Publish Server' diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 4abe52b43..81693452f 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -181,7 +181,7 @@ jobs: inputs: sshEndpoint: repository runOptions: 'commands' - commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) & + commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) $(Build.SourceBranch) & - job: PublishNuget displayName: 'Publish NuGet packages' @@ -199,7 +199,6 @@ jobs: inputs: packageType: 'sdk' version: '6.0.x' - includePreviewVersions: true - task: DotNetCoreCLI@2 displayName: 'Build Stable Nuget packages' diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index 80a5732ee..cc94dc2c5 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -41,7 +41,6 @@ jobs: inputs: packageType: sdk version: ${{ parameters.DotNetSdkVersion }} - includePreviewVersions: true - task: SonarCloudPrepare@1 displayName: 'Prepare analysis on SonarCloud' diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index c1d49778e..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -name: Bug report -about: Create a bug report -title: '' -labels: bug -assignees: '' - ---- - -**Describe the bug** -<!-- A clear and concise description of what the bug is. --> - -**System (please complete the following information):** - - OS: [e.g. Debian, Windows] - - Virtualization: [e.g. Docker, KVM, LXC] - - Clients: [Browser, Android, Fire Stick, etc.] - - Browser: [e.g. Firefox 91, Chrome 93, Safari 13] - - Jellyfin Version: [e.g. 10.7.6, unstable 20191231] - - FFmpeg Version: [e.g. 4.3.2-Jellyfin] - - Playback: [Direct Play, Remux, Direct Stream, Transcode] - - Hardware Acceleration: [e.g. none, VAAPI, NVENC, etc.] - - Installed Plugins: [e.g. none, Fanart, Anime, etc.] - - Reverse Proxy: [e.g. none, nginx, apache, etc.] - - Base URL: [e.g. none, yes: /example] - - Networking: [e.g. Host, Bridge/NAT] - - Storage: [e.g. local, NFS, cloud] - -**To Reproduce** -<!-- Steps to reproduce the behavior: --> -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -<!-- A clear and concise description of what you expected to happen. --> - -**Server Logs** -<!-- Please paste any log errors. --> - -**FFmpeg Logs** -<!-- Please paste any log errors. --> - -**Browser Console Logs** -<!-- Please paste any log errors. --> - -**Screenshots** -<!-- If applicable, add screenshots to help explain your problem. --> - -**Additional context** -<!-- Add any other context about the problem here. --> diff --git a/.github/ISSUE_TEMPLATE/issue report.yml b/.github/ISSUE_TEMPLATE/issue report.yml new file mode 100644 index 000000000..63e0f0e22 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue report.yml @@ -0,0 +1,106 @@ +name: Issue Report +description: File an issue report +title: "[Issue]: " +labels: [bug, triage] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! Please provide as much detail as necessary, most questions may not be applicable to you. If you need real-time help, join us on [Matrix](https://matrix.to/#/#jellyfin-troubleshooting:matrix.org) or [Discord](https://discord.gg/zHBxVSXdBV). + - type: textarea + id: what-happened + attributes: + label: Please describe your bug + description: Also tell us, what did you expect to happen? + placeholder: | + The more information that you are able to provide, the better. Did you do anything before this happened? Did you upgrade or change anything? Any screenshots or logs you can provide will be helpful. + + This is my issue. + + Steps to Reproduce + 1. In this environment... + 2. With this config... + 3. Run '...' + 4. See error... + validations: + required: true + - type: dropdown + id: version + attributes: + label: Jellyfin Version + description: What version of Jellyfin are you running? + options: + - 10.7.7 + - 10.7.z + - 10.6.4 + - Other + validations: + required: true + - type: input + id: version-other + attributes: + label: "if other:" + placeholder: Other + - type: textarea + attributes: + label: Environment + description: | + Examples: + - **OS**: [e.g. Debian, Windows] + - **Virtualization**: [e.g. Docker, KVM, LXC] + - **Clients**: [Browser, Android, Fire Stick, etc.] + - **Browser**: [e.g. Firefox 91, Chrome 93, Safari 13] + - **FFmpeg Version**: [e.g. 4.3.2-Jellyfin] + - **Playback**: [Direct Play, Remux, Direct Stream, Transcode] + - **Hardware Acceleration**: [e.g. none, VAAPI, NVENC, etc.] + - **Installed Plugins**: [e.g. none, Fanart, Anime, etc.] + - **Reverse Proxy**: [e.g. none, nginx, apache, etc.] + - **Base URL**: [e.g. none, yes: /example] + - **Networking**: [e.g. Host, Bridge/NAT] + - **Storage**: [e.g. local, NFS, cloud] + value: | + - OS: + - Virtualization: + - Clients: + - Browser: + - FFmpeg Version: + - Playback Method: + - Hardware Acceleration: + - Plugins: + - Reverse Proxy: + - Base URL: + - Networking: + - Storage: + render: markdown + - type: textarea + id: logs + attributes: + label: Jellyfin logs + description: Please copy and paste any relevant log output. This can be found in Dashboard > Logs. + placeholder: For playback issues, browser/client and FFmpeg logs may be more useful. + render: shell + - type: textarea + id: ffmpeg-logs + attributes: + label: FFmpeg logs + description: Please copy and paste any relevant log output. This can be found in Dashboard > Logs. + placeholder: It's important to include the specific codec details. If no FFmpeg logs appear, the file was Direct Played and did not use FFmpeg. + render: shell + - type: textarea + id: browserlogs + attributes: + label: Please attach any browser or client logs here + placeholder: Access browser logs by using the F12 to bring up the console. Screenshots are typically easier to read than raw logs. For clients such as Android or iOS, please see our documentation. + - type: textarea + id: screenshots + attributes: + label: Please attach any screenshots here + placeholder: Images can be pasted directly into the textbox and will be hosted by github. + - type: checkboxes + id: terms + attributes: + label: Code of Conduct + description: By submitting this issue, you agree to follow our [Code of Conduct](https://jellyfin.org/docs/general/community-standards.html#code-of-conduct) + options: + - label: I agree to follow this project's Code of Conduct + required: true diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index e07d913b5..ea1d30cdf 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -25,8 +25,7 @@ jobs: uses: actions/setup-dotnet@v1 with: dotnet-version: '6.0.x' - include-prerelease: true - + - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: diff --git a/.github/workflows/openapi.yml b/.github/workflows/openapi.yml new file mode 100644 index 000000000..3e9346840 --- /dev/null +++ b/.github/workflows/openapi.yml @@ -0,0 +1,124 @@ +name: OpenAPI +on: + push: + branches: + - master + pull_request_target: + +jobs: + openapi-head: + name: OpenAPI - HEAD + runs-on: ubuntu-latest + permissions: read-all + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + ref: ${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Generate openapi.json + run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests" + - name: Upload openapi.json + uses: actions/upload-artifact@v2 + with: + name: openapi-head + retention-days: 14 + if-no-files-found: error + path: tests/Jellyfin.Server.Integration.Tests/bin/Release/net6.0/openapi.json + + openapi-base: + name: OpenAPI - BASE + if: ${{ github.base_ref != '' }} + runs-on: ubuntu-latest + permissions: read-all + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + ref: ${{ github.base_ref }} + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Generate openapi.json + run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests" + - name: Upload openapi.json + uses: actions/upload-artifact@v2 + with: + name: openapi-base + retention-days: 14 + if-no-files-found: error + path: tests/Jellyfin.Server.Integration.Tests/bin/Release/net6.0/openapi.json + + openapi-diff: + name: OpenAPI - Difference + if: ${{ github.event_name == 'pull_request_target' }} + runs-on: ubuntu-latest + needs: + - openapi-head + - openapi-base + steps: + - name: Download openapi-head + uses: actions/download-artifact@v2 + with: + name: openapi-head + path: openapi-head + - name: Download openapi-base + uses: actions/download-artifact@v2 + with: + name: openapi-base + path: openapi-base + - name: Workaround openapi-diff issue + run: | + sed -i 's/"allOf"/"oneOf"/g' openapi-head/openapi.json + sed -i 's/"allOf"/"oneOf"/g' openapi-base/openapi.json + - name: Calculate OpenAPI difference + uses: docker://openapitools/openapi-diff + continue-on-error: true + with: + args: --fail-on-changed --markdown openapi-changes.md openapi-base/openapi.json openapi-head/openapi.json + - id: read-diff + name: Read openapi-diff output + run: | + body=$(cat openapi-changes.md) + body="${body//'%'/'%25'}" + body="${body//$'\n'/'%0A'}" + body="${body//$'\r'/'%0D'}" + echo ::set-output name=body::$body + - name: Find difference comment + uses: peter-evans/find-comment@v1 + id: find-comment + with: + issue-number: ${{ github.event.pull_request.number }} + direction: last + body-includes: openapi-diff-workflow-comment + - name: Reply or edit difference comment (changed) + uses: peter-evans/create-or-update-comment@v1.4.5 + if: ${{ steps.read-diff.outputs.body != '' }} + with: + issue-number: ${{ github.event.pull_request.number }} + comment-id: ${{ steps.find-comment.outputs.comment-id }} + edit-mode: replace + body: | + <!--openapi-diff-workflow-comment--> + <details> + <summary>Changes in OpenAPI specification found. Expand to see details.</summary> + + ${{ steps.read-diff.outputs.body }} + + </details> + - name: Edit difference comment (unchanged) + uses: peter-evans/create-or-update-comment@v1.4.5 + if: ${{ steps.read-diff.outputs.body == '' && steps.find-comment.outputs.comment-id != '' }} + with: + issue-number: ${{ github.event.pull_request.number }} + comment-id: ${{ steps.find-comment.outputs.comment-id }} + edit-mode: replace + body: | + <!--openapi-diff-workflow-comment--> + + No changes to OpenAPI specification found. See history of this comment for previous changes. diff --git a/Directory.Build.props b/Directory.Build.props index b899999ef..d243cde2b 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,10 +3,13 @@ <PropertyGroup> <Nullable>enable</Nullable> - <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)/jellyfin.ruleset</CodeAnalysisRuleSet> </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <AnalysisMode>AllEnabledByDefault</AnalysisMode> </PropertyGroup> diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index ac336e5dc..26a816107 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -25,6 +25,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.TV; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Querying; @@ -50,7 +51,6 @@ namespace Emby.Dlna.ContentDirectory private readonly ILibraryManager _libraryManager; private readonly IUserDataManager _userDataManager; - private readonly IServerConfigurationManager _config; private readonly User _user; private readonly IUserViewManager _userViewManager; private readonly ITVSeriesManager _tvSeriesManager; @@ -104,7 +104,6 @@ namespace Emby.Dlna.ContentDirectory _userViewManager = userViewManager; _tvSeriesManager = tvSeriesManager; _profile = profile; - _config = config; _didlBuilder = new DidlBuilder( profile, @@ -291,9 +290,9 @@ namespace Emby.Dlna.ContentDirectory return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Features xmlns=\"urn:schemas-upnp-org:av:avs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd\">" + "<Feature name=\"samsung.com_BASICVIEW\" version=\"1\">" - + "<container id=\"I\" type=\"object.item.imageItem\"/>" - + "<container id=\"A\" type=\"object.item.audioItem\"/>" - + "<container id=\"V\" type=\"object.item.videoItem\"/>" + + "<container id=\"0\" type=\"object.item.imageItem\"/>" + + "<container id=\"0\" type=\"object.item.audioItem\"/>" + + "<container id=\"0\" type=\"object.item.videoItem\"/>" + "</Feature>" + "</Features>"; } @@ -330,75 +329,73 @@ namespace Emby.Dlna.ContentDirectory int totalCount; + var settings = new XmlWriterSettings + { + Encoding = Encoding.UTF8, + CloseOutput = false, + OmitXmlDeclaration = true, + ConformanceLevel = ConformanceLevel.Fragment + }; + using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8)) + using (var writer = XmlWriter.Create(builder, settings)) { - var settings = new XmlWriterSettings() - { - Encoding = Encoding.UTF8, - CloseOutput = false, - OmitXmlDeclaration = true, - ConformanceLevel = ConformanceLevel.Fragment - }; + writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl); - using (var writer = XmlWriter.Create(builder, settings)) - { - writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl); + writer.WriteAttributeString("xmlns", "dc", null, NsDc); + writer.WriteAttributeString("xmlns", "dlna", null, NsDlna); + writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp); - writer.WriteAttributeString("xmlns", "dc", null, NsDc); - writer.WriteAttributeString("xmlns", "dlna", null, NsDlna); - writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp); + DidlBuilder.WriteXmlRootAttributes(_profile, writer); - DidlBuilder.WriteXmlRootAttributes(_profile, writer); + var serverItem = GetItemFromObjectId(id); + var item = serverItem.Item; - var serverItem = GetItemFromObjectId(id); - var item = serverItem.Item; + if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal)) + { + totalCount = 1; - if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal)) + if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue) { - totalCount = 1; - - if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue) - { - var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); - - _didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id); - } - else - { - _didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter); - } + var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); - provided++; + _didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id); } else { - var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); - totalCount = childrenResult.TotalRecordCount; + _didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter); + } + + provided++; + } + else + { + var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); + totalCount = childrenResult.TotalRecordCount; + + provided = childrenResult.Items.Count; + + foreach (var i in childrenResult.Items) + { + var childItem = i.Item; + var displayStubType = i.StubType; - provided = childrenResult.Items.Count; + if (childItem.IsDisplayedAsFolder || displayStubType.HasValue) + { + var childCount = GetUserItems(childItem, displayStubType, _user, sortCriteria, null, 0) + .TotalRecordCount; - foreach (var i in childrenResult.Items) + _didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter); + } + else { - var childItem = i.Item; - var displayStubType = i.StubType; - - if (childItem.IsDisplayedAsFolder || displayStubType.HasValue) - { - var childCount = GetUserItems(childItem, displayStubType, _user, sortCriteria, null, 0) - .TotalRecordCount; - - _didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter); - } - else - { - _didlBuilder.WriteItemElement(writer, childItem, _user, item, serverItem.StubType, deviceId, filter); - } + _didlBuilder.WriteItemElement(writer, childItem, _user, item, serverItem.StubType, deviceId, filter); } } - - writer.WriteFullEndElement(); } + writer.WriteFullEndElement(); + writer.Flush(); xmlWriter.WriteElementString("Result", builder.ToString()); } @@ -449,53 +446,46 @@ namespace Emby.Dlna.ContentDirectory } QueryResult<BaseItem> childrenResult; + var settings = new XmlWriterSettings + { + Encoding = Encoding.UTF8, + CloseOutput = false, + OmitXmlDeclaration = true, + ConformanceLevel = ConformanceLevel.Fragment + }; using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8)) + using (var writer = XmlWriter.Create(builder, settings)) { - var settings = new XmlWriterSettings() - { - Encoding = Encoding.UTF8, - CloseOutput = false, - OmitXmlDeclaration = true, - ConformanceLevel = ConformanceLevel.Fragment - }; - - using (var writer = XmlWriter.Create(builder, settings)) - { - writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl); - - writer.WriteAttributeString("xmlns", "dc", null, NsDc); - writer.WriteAttributeString("xmlns", "dlna", null, NsDlna); - writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp); - - DidlBuilder.WriteXmlRootAttributes(_profile, writer); - - var serverItem = GetItemFromObjectId(sparams["ContainerID"]); + writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl); + writer.WriteAttributeString("xmlns", "dc", null, NsDc); + writer.WriteAttributeString("xmlns", "dlna", null, NsDlna); + writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp); - var item = serverItem.Item; + DidlBuilder.WriteXmlRootAttributes(_profile, writer); - childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount); + var serverItem = GetItemFromObjectId(sparams["ContainerID"]); - var dlnaOptions = _config.GetDlnaConfiguration(); + var item = serverItem.Item; - foreach (var i in childrenResult.Items) + childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount); + foreach (var i in childrenResult.Items) + { + if (i.IsDisplayedAsFolder) { - if (i.IsDisplayedAsFolder) - { - var childCount = GetChildrenSorted(i, _user, searchCriteria, sortCriteria, null, 0) - .TotalRecordCount; + var childCount = GetChildrenSorted(i, _user, searchCriteria, sortCriteria, null, 0) + .TotalRecordCount; - _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter); - } - else - { - _didlBuilder.WriteItemElement(writer, i, _user, item, serverItem.StubType, deviceId, filter); - } + _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter); + } + else + { + _didlBuilder.WriteItemElement(writer, i, _user, item, serverItem.StubType, deviceId, filter); } - - writer.WriteFullEndElement(); } + writer.WriteFullEndElement(); + writer.Flush(); xmlWriter.WriteElementString("Result", builder.ToString()); } @@ -518,44 +508,34 @@ namespace Emby.Dlna.ContentDirectory { var folder = (Folder)item; - var sortOrders = folder.IsPreSorted - ? Array.Empty<(string, SortOrder)>() - : new[] { (ItemSortBy.SortName, sort.SortOrder) }; - string[] mediaTypes = Array.Empty<string>(); bool? isFolder = null; - if (search.SearchType == SearchType.Audio) - { - mediaTypes = new[] { MediaType.Audio }; - isFolder = false; - } - else if (search.SearchType == SearchType.Video) - { - mediaTypes = new[] { MediaType.Video }; - isFolder = false; - } - else if (search.SearchType == SearchType.Image) - { - mediaTypes = new[] { MediaType.Photo }; - isFolder = false; - } - else if (search.SearchType == SearchType.Playlist) - { - // items = items.OfType<Playlist>(); - isFolder = true; - } - else if (search.SearchType == SearchType.MusicAlbum) + switch (search.SearchType) { - // items = items.OfType<MusicAlbum>(); - isFolder = true; + case SearchType.Audio: + mediaTypes = new[] { MediaType.Audio }; + isFolder = false; + break; + case SearchType.Video: + mediaTypes = new[] { MediaType.Video }; + isFolder = false; + break; + case SearchType.Image: + mediaTypes = new[] { MediaType.Photo }; + isFolder = false; + break; + case SearchType.Playlist: + case SearchType.MusicAlbum: + isFolder = true; + break; } return folder.GetItems(new InternalItemsQuery { Limit = limit, StartIndex = startIndex, - OrderBy = sortOrders, + OrderBy = GetOrderBy(sort, folder.IsPreSorted), User = user, Recursive = true, IsMissing = false, @@ -587,52 +567,49 @@ namespace Emby.Dlna.ContentDirectory /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> private QueryResult<ServerItem> GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit) { - if (item is MusicGenre) - { - return GetMusicGenreItems(item, Guid.Empty, user, sort, startIndex, limit); - } - - if (item is MusicArtist) - { - return GetMusicArtistItems(item, Guid.Empty, user, sort, startIndex, limit); + switch (item) + { + case MusicGenre: + return GetMusicGenreItems(item, user, sort, startIndex, limit); + case MusicArtist: + return GetMusicArtistItems(item, user, sort, startIndex, limit); + case Genre: + return GetGenreItems(item, user, sort, startIndex, limit); } - if (item is Genre) + if (stubType != StubType.Folder && item is IHasCollectionType collectionFolder) { - return GetGenreItems(item, Guid.Empty, user, sort, startIndex, limit); - } - - if ((!stubType.HasValue || stubType.Value != StubType.Folder) - && item is IHasCollectionType collectionFolder) - { - if (string.Equals(CollectionType.Music, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase)) + var collectionType = collectionFolder.CollectionType; + if (string.Equals(CollectionType.Music, collectionType, StringComparison.OrdinalIgnoreCase)) { return GetMusicFolders(item, user, stubType, sort, startIndex, limit); } - else if (string.Equals(CollectionType.Movies, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(CollectionType.Movies, collectionType, StringComparison.OrdinalIgnoreCase)) { return GetMovieFolders(item, user, stubType, sort, startIndex, limit); } - else if (string.Equals(CollectionType.TvShows, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(CollectionType.TvShows, collectionType, StringComparison.OrdinalIgnoreCase)) { return GetTvFolders(item, user, stubType, sort, startIndex, limit); } - else if (string.Equals(CollectionType.Folders, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(CollectionType.Folders, collectionType, StringComparison.OrdinalIgnoreCase)) { return GetFolders(user, startIndex, limit); } - else if (string.Equals(CollectionType.LiveTv, collectionFolder.CollectionType, StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(CollectionType.LiveTv, collectionType, StringComparison.OrdinalIgnoreCase)) { return GetLiveTvChannels(user, sort, startIndex, limit); } } - if (stubType.HasValue) + if (stubType.HasValue && stubType.Value != StubType.Folder) { - if (stubType.Value != StubType.Folder) - { - return ApplyPaging(new QueryResult<ServerItem>(), startIndex, limit); - } + // TODO should this be doing something? + return new QueryResult<ServerItem>(); } var folder = (Folder)item; @@ -644,11 +621,10 @@ namespace Emby.Dlna.ContentDirectory IsVirtualItem = false, ExcludeItemTypes = new[] { nameof(Book) }, IsPlaceHolder = false, - DtoOptions = GetDtoOptions() + DtoOptions = GetDtoOptions(), + OrderBy = GetOrderBy(sort, folder.IsPreSorted) }; - SetSorting(query, sort, folder.IsPreSorted); - var queryResult = folder.GetItems(query); return ToResult(queryResult); @@ -668,10 +644,9 @@ namespace Emby.Dlna.ContentDirectory { StartIndex = startIndex, Limit = limit, + IncludeItemTypes = new[] { nameof(LiveTvChannel) }, + OrderBy = GetOrderBy(sort, false) }; - query.IncludeItemTypes = new[] { nameof(LiveTvChannel) }; - - SetSorting(query, sort, false); var result = _libraryManager.GetItemsResult(query); @@ -693,117 +668,57 @@ namespace Emby.Dlna.ContentDirectory var query = new InternalItemsQuery(user) { StartIndex = startIndex, - Limit = limit + Limit = limit, + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - - if (stubType.HasValue && stubType.Value == StubType.Latest) - { - return GetMusicLatest(item, user, query); - } - if (stubType.HasValue && stubType.Value == StubType.Playlists) - { - return GetMusicPlaylists(user, query); + switch (stubType) + { + case StubType.Latest: + return GetLatest(item, query, nameof(Audio)); + case StubType.Playlists: + return GetMusicPlaylists(query); + case StubType.Albums: + return GetChildrenOfItem(item, query, nameof(MusicAlbum)); + case StubType.Artists: + return GetMusicArtists(item, query); + case StubType.AlbumArtists: + return GetMusicAlbumArtists(item, query); + case StubType.FavoriteAlbums: + return GetChildrenOfItem(item, query, nameof(MusicAlbum), true); + case StubType.FavoriteArtists: + return GetFavoriteArtists(item, query); + case StubType.FavoriteSongs: + return GetChildrenOfItem(item, query, nameof(Audio), true); + case StubType.Songs: + return GetChildrenOfItem(item, query, nameof(Audio)); + case StubType.Genres: + return GetMusicGenres(item, query); } - if (stubType.HasValue && stubType.Value == StubType.Albums) - { - return GetMusicAlbums(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Artists) - { - return GetMusicArtists(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.AlbumArtists) - { - return GetMusicAlbumArtists(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.FavoriteAlbums) - { - return GetFavoriteAlbums(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.FavoriteArtists) - { - return GetFavoriteArtists(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.FavoriteSongs) - { - return GetFavoriteSongs(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Songs) - { - return GetMusicSongs(item, user, query); - } + var serverItems = new ServerItem[] + { + new (item, StubType.Latest), + new (item, StubType.Playlists), + new (item, StubType.Albums), + new (item, StubType.AlbumArtists), + new (item, StubType.Artists), + new (item, StubType.Songs), + new (item, StubType.Genres), + new (item, StubType.FavoriteArtists), + new (item, StubType.FavoriteAlbums), + new (item, StubType.FavoriteSongs) + }; - if (stubType.HasValue && stubType.Value == StubType.Genres) + if (limit < serverItems.Length) { - return GetMusicGenres(item, user, query); + serverItems = serverItems[..limit.Value]; } - var list = new List<ServerItem> - { - new ServerItem(item) - { - StubType = StubType.Latest - }, - - new ServerItem(item) - { - StubType = StubType.Playlists - }, - - new ServerItem(item) - { - StubType = StubType.Albums - }, - - new ServerItem(item) - { - StubType = StubType.AlbumArtists - }, - - new ServerItem(item) - { - StubType = StubType.Artists - }, - - new ServerItem(item) - { - StubType = StubType.Songs - }, - - new ServerItem(item) - { - StubType = StubType.Genres - }, - - new ServerItem(item) - { - StubType = StubType.FavoriteArtists - }, - - new ServerItem(item) - { - StubType = StubType.FavoriteAlbums - }, - - new ServerItem(item) - { - StubType = StubType.FavoriteSongs - } - }; - return new QueryResult<ServerItem> { - Items = list, - TotalRecordCount = list.Count + Items = serverItems, + TotalRecordCount = serverItems.Length }; } @@ -822,68 +737,41 @@ namespace Emby.Dlna.ContentDirectory var query = new InternalItemsQuery(user) { StartIndex = startIndex, - Limit = limit + Limit = limit, + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - if (stubType.HasValue && stubType.Value == StubType.ContinueWatching) - { - return GetMovieContinueWatching(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Latest) - { - return GetMovieLatest(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Movies) - { - return GetMovieMovies(item, user, query); + switch (stubType) + { + case StubType.ContinueWatching: + return GetMovieContinueWatching(item, query); + case StubType.Latest: + return GetLatest(item, query, nameof(Movie)); + case StubType.Movies: + return GetChildrenOfItem(item, query, nameof(Movie)); + case StubType.Collections: + return GetMovieCollections(query); + case StubType.Favorites: + return GetChildrenOfItem(item, query, nameof(Movie), true); + case StubType.Genres: + return GetGenres(item, query); } - if (stubType.HasValue && stubType.Value == StubType.Collections) + var array = new ServerItem[] { - return GetMovieCollections(user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Favorites) - { - return GetMovieFavorites(item, user, query); - } + new (item, StubType.ContinueWatching), + new (item, StubType.Latest), + new (item, StubType.Movies), + new (item, StubType.Collections), + new (item, StubType.Favorites), + new (item, StubType.Genres) + }; - if (stubType.HasValue && stubType.Value == StubType.Genres) + if (limit < array.Length) { - return GetGenres(item, user, query); + array = array[..limit.Value]; } - var array = new[] - { - new ServerItem(item) - { - StubType = StubType.ContinueWatching - }, - new ServerItem(item) - { - StubType = StubType.Latest - }, - new ServerItem(item) - { - StubType = StubType.Movies - }, - new ServerItem(item) - { - StubType = StubType.Collections - }, - new ServerItem(item) - { - StubType = StubType.Favorites - }, - new ServerItem(item) - { - StubType = StubType.Genres - } - }; - return new QueryResult<ServerItem> { Items = array, @@ -900,22 +788,21 @@ namespace Emby.Dlna.ContentDirectory /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> private QueryResult<ServerItem> GetFolders(User user, int? startIndex, int? limit) { - var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true) + var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true); + var totalRecordCount = folders.Count; + // Handle paging + var items = folders .OrderBy(i => i.SortName) - .Select(i => new ServerItem(i) - { - StubType = StubType.Folder - }) + .Skip(startIndex ?? 0) + .Take(limit ?? int.MaxValue) + .Select(i => new ServerItem(i, StubType.Folder)) .ToArray(); - return ApplyPaging( - new QueryResult<ServerItem> - { - Items = folders, - TotalRecordCount = folders.Length - }, - startIndex, - limit); + return new QueryResult<ServerItem> + { + Items = items, + TotalRecordCount = totalRecordCount + }; } /// <summary> @@ -933,87 +820,48 @@ namespace Emby.Dlna.ContentDirectory var query = new InternalItemsQuery(user) { StartIndex = startIndex, - Limit = limit + Limit = limit, + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - if (stubType.HasValue && stubType.Value == StubType.ContinueWatching) - { - return GetMovieContinueWatching(item, user, query); + switch (stubType) + { + case StubType.ContinueWatching: + return GetMovieContinueWatching(item, query); + case StubType.NextUp: + return GetNextUp(item, query); + case StubType.Latest: + return GetLatest(item, query, nameof(Episode)); + case StubType.Series: + return GetChildrenOfItem(item, query, nameof(Series)); + case StubType.FavoriteSeries: + return GetChildrenOfItem(item, query, nameof(Series), true); + case StubType.FavoriteEpisodes: + return GetChildrenOfItem(item, query, nameof(Episode), true); + case StubType.Genres: + return GetGenres(item, query); } - if (stubType.HasValue && stubType.Value == StubType.NextUp) + var serverItems = new ServerItem[] { - return GetNextUp(item, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Latest) - { - return GetTvLatest(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.Series) - { - return GetSeries(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.FavoriteSeries) - { - return GetFavoriteSeries(item, user, query); - } - - if (stubType.HasValue && stubType.Value == StubType.FavoriteEpisodes) - { - return GetFavoriteEpisodes(item, user, query); - } + new (item, StubType.ContinueWatching), + new (item, StubType.NextUp), + new (item, StubType.Latest), + new (item, StubType.Series), + new (item, StubType.FavoriteSeries), + new (item, StubType.FavoriteEpisodes), + new (item, StubType.Genres) + }; - if (stubType.HasValue && stubType.Value == StubType.Genres) + if (limit < serverItems.Length) { - return GetGenres(item, user, query); + serverItems = serverItems[..limit.Value]; } - var list = new List<ServerItem> - { - new ServerItem(item) - { - StubType = StubType.ContinueWatching - }, - - new ServerItem(item) - { - StubType = StubType.NextUp - }, - - new ServerItem(item) - { - StubType = StubType.Latest - }, - - new ServerItem(item) - { - StubType = StubType.Series - }, - - new ServerItem(item) - { - StubType = StubType.FavoriteSeries - }, - - new ServerItem(item) - { - StubType = StubType.FavoriteEpisodes - }, - - new ServerItem(item) - { - StubType = StubType.Genres - } - }; - return new QueryResult<ServerItem> { - Items = list, - TotalRecordCount = list.Count + Items = serverItems, + TotalRecordCount = serverItems.Length }; } @@ -1021,14 +869,12 @@ namespace Emby.Dlna.ContentDirectory /// Returns the Movies that are part watched that meet the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMovieContinueWatching(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMovieContinueWatching(BaseItem parent, InternalItemsQuery query) { query.Recursive = true; query.Parent = parent; - query.SetUser(user); query.OrderBy = new[] { @@ -1037,47 +883,7 @@ namespace Emby.Dlna.ContentDirectory }; query.IsResumable = true; - query.Limit = 10; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the series meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetSeries(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - - query.IncludeItemTypes = new[] { nameof(Series) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the Movie folders meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMovieMovies(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - - query.IncludeItemTypes = new[] { nameof(Movie) }; + query.Limit ??= 10; var result = _libraryManager.GetItemsResult(query); @@ -1087,15 +893,11 @@ namespace Emby.Dlna.ContentDirectory /// <summary> /// Returns the Movie collections meeting the criteria. /// </summary> - /// <param name="user">The see cref="User"/>.</param> /// <param name="query">The see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMovieCollections(User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMovieCollections(InternalItemsQuery query) { query.Recursive = true; - // query.Parent = parent; - query.SetUser(user); - query.IncludeItemTypes = new[] { nameof(BoxSet) }; var result = _libraryManager.GetItemsResult(query); @@ -1104,139 +906,19 @@ namespace Emby.Dlna.ContentDirectory } /// <summary> - /// Returns the Music albums meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicAlbums(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - - query.IncludeItemTypes = new[] { nameof(MusicAlbum) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the Music songs meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicSongs(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - - query.IncludeItemTypes = new[] { nameof(Audio) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the songs tagged as favourite that meet the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetFavoriteSongs(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - query.IsFavorite = true; - query.IncludeItemTypes = new[] { nameof(Audio) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the series tagged as favourite that meet the criteria. + /// Returns the children that meet the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> + /// <param name="itemType">The item type.</param> + /// <param name="isFavorite">A value indicating whether to only fetch favorite items.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetFavoriteSeries(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetChildrenOfItem(BaseItem parent, InternalItemsQuery query, string itemType, bool isFavorite = false) { query.Recursive = true; query.Parent = parent; - query.SetUser(user); - query.IsFavorite = true; - query.IncludeItemTypes = new[] { nameof(Series) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the episodes tagged as favourite that meet the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetFavoriteEpisodes(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - query.IsFavorite = true; - query.IncludeItemTypes = new[] { nameof(Episode) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// Returns the movies tagged as favourite that meet the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMovieFavorites(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - query.IsFavorite = true; - query.IncludeItemTypes = new[] { nameof(Movie) }; - - var result = _libraryManager.GetItemsResult(query); - - return ToResult(result); - } - - /// <summary> - /// /// Returns the albums tagged as favourite that meet the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetFavoriteAlbums(BaseItem parent, User user, InternalItemsQuery query) - { - query.Recursive = true; - query.Parent = parent; - query.SetUser(user); - query.IsFavorite = true; - query.IncludeItemTypes = new[] { nameof(MusicAlbum) }; + query.IsFavorite = isFavorite; + query.IncludeItemTypes = new[] { itemType }; var result = _libraryManager.GetItemsResult(query); @@ -1248,139 +930,90 @@ namespace Emby.Dlna.ContentDirectory /// The GetGenres. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetGenres(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetGenres(BaseItem parent, InternalItemsQuery query) { - var genresResult = _libraryManager.GetGenres(new InternalItemsQuery(user) - { - AncestorIds = new[] { parent.Id }, - StartIndex = query.StartIndex, - Limit = query.Limit - }); - - var result = new QueryResult<BaseItem> - { - TotalRecordCount = genresResult.TotalRecordCount, - Items = genresResult.Items.Select(i => i.Item1).ToArray() - }; + // Don't sort + query.OrderBy = Array.Empty<(string, SortOrder)>(); + query.AncestorIds = new[] { parent.Id }; + var genresResult = _libraryManager.GetGenres(query); - return ToResult(result); + return ToResult(genresResult); } /// <summary> /// Returns the music genres meeting the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicGenres(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMusicGenres(BaseItem parent, InternalItemsQuery query) { - var genresResult = _libraryManager.GetMusicGenres(new InternalItemsQuery(user) - { - AncestorIds = new[] { parent.Id }, - StartIndex = query.StartIndex, - Limit = query.Limit - }); - - var result = new QueryResult<BaseItem> - { - TotalRecordCount = genresResult.TotalRecordCount, - Items = genresResult.Items.Select(i => i.Item1).ToArray() - }; + // Don't sort + query.OrderBy = Array.Empty<(string, SortOrder)>(); + query.AncestorIds = new[] { parent.Id }; + var genresResult = _libraryManager.GetMusicGenres(query); - return ToResult(result); + return ToResult(genresResult); } /// <summary> /// Returns the music albums by artist that meet the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicAlbumArtists(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMusicAlbumArtists(BaseItem parent, InternalItemsQuery query) { - var artists = _libraryManager.GetAlbumArtists(new InternalItemsQuery(user) - { - AncestorIds = new[] { parent.Id }, - StartIndex = query.StartIndex, - Limit = query.Limit - }); - - var result = new QueryResult<BaseItem> - { - TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray() - }; + // Don't sort + query.OrderBy = Array.Empty<(string, SortOrder)>(); + query.AncestorIds = new[] { parent.Id }; + var artists = _libraryManager.GetAlbumArtists(query); - return ToResult(result); + return ToResult(artists); } /// <summary> /// Returns the music artists meeting the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicArtists(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMusicArtists(BaseItem parent, InternalItemsQuery query) { - var artists = _libraryManager.GetArtists(new InternalItemsQuery(user) - { - AncestorIds = new[] { parent.Id }, - StartIndex = query.StartIndex, - Limit = query.Limit - }); - - var result = new QueryResult<BaseItem> - { - TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray() - }; - - return ToResult(result); + // Don't sort + query.OrderBy = Array.Empty<(string, SortOrder)>(); + query.AncestorIds = new[] { parent.Id }; + var artists = _libraryManager.GetArtists(query); + return ToResult(artists); } /// <summary> /// Returns the artists tagged as favourite that meet the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetFavoriteArtists(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetFavoriteArtists(BaseItem parent, InternalItemsQuery query) { - var artists = _libraryManager.GetArtists(new InternalItemsQuery(user) - { - AncestorIds = new[] { parent.Id }, - StartIndex = query.StartIndex, - Limit = query.Limit, - IsFavorite = true - }); - - var result = new QueryResult<BaseItem> - { - TotalRecordCount = artists.TotalRecordCount, - Items = artists.Items.Select(i => i.Item1).ToArray() - }; - - return ToResult(result); + // Don't sort + query.OrderBy = Array.Empty<(string, SortOrder)>(); + query.AncestorIds = new[] { parent.Id }; + query.IsFavorite = true; + var artists = _libraryManager.GetArtists(query); + return ToResult(artists); } /// <summary> /// Returns the music playlists meeting the criteria. /// </summary> - /// <param name="user">The user<see cref="User"/>.</param> /// <param name="query">The query<see cref="InternalItemsQuery"/>.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicPlaylists(User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetMusicPlaylists(InternalItemsQuery query) { query.Parent = null; query.IncludeItemTypes = new[] { nameof(Playlist) }; - query.SetUser(user); query.Recursive = true; var result = _libraryManager.GetItemsResult(query); @@ -1389,31 +1022,6 @@ namespace Emby.Dlna.ContentDirectory } /// <summary> - /// Returns the latest music meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicLatest(BaseItem parent, User user, InternalItemsQuery query) - { - query.OrderBy = Array.Empty<(string, SortOrder)>(); - - var items = _userViewManager.GetLatestItems( - new LatestItemsQuery - { - UserId = user.Id, - Limit = 50, - IncludeItemTypes = new[] { nameof(Audio) }, - ParentId = parent?.Id ?? Guid.Empty, - GroupItems = true - }, - query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray(); - - return ToResult(items); - } - - /// <summary> /// Returns the next up item meeting the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> @@ -1428,7 +1036,8 @@ namespace Emby.Dlna.ContentDirectory { Limit = query.Limit, StartIndex = query.StartIndex, - UserId = query.User.Id + // User cannot be null here as the caller has set it + UserId = query.User!.Id }, new[] { parent }, query.DtoOptions); @@ -1437,47 +1046,23 @@ namespace Emby.Dlna.ContentDirectory } /// <summary> - /// Returns the latest tv meeting the criteria. - /// </summary> - /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetTvLatest(BaseItem parent, User user, InternalItemsQuery query) - { - query.OrderBy = Array.Empty<(string, SortOrder)>(); - - var items = _userViewManager.GetLatestItems( - new LatestItemsQuery - { - UserId = user.Id, - Limit = 50, - IncludeItemTypes = new[] { nameof(Episode) }, - ParentId = parent == null ? Guid.Empty : parent.Id, - GroupItems = false - }, - query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray(); - - return ToResult(items); - } - - /// <summary> - /// Returns the latest movies meeting the criteria. + /// Returns the latest items of [itemType] meeting the criteria. /// </summary> /// <param name="parent">The <see cref="BaseItem"/>.</param> - /// <param name="user">The <see cref="User"/>.</param> /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> + /// <param name="itemType">The item type.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMovieLatest(BaseItem parent, User user, InternalItemsQuery query) + private QueryResult<ServerItem> GetLatest(BaseItem parent, InternalItemsQuery query, string itemType) { query.OrderBy = Array.Empty<(string, SortOrder)>(); var items = _userViewManager.GetLatestItems( new LatestItemsQuery { - UserId = user.Id, - Limit = 50, - IncludeItemTypes = new[] { nameof(Movie) }, + // User cannot be null here as the caller has set it + UserId = query.User!.Id, + Limit = query.Limit ?? 50, + IncludeItemTypes = new[] { itemType }, ParentId = parent?.Id ?? Guid.Empty, GroupItems = true }, @@ -1490,27 +1075,24 @@ namespace Emby.Dlna.ContentDirectory /// Returns music artist items that meet the criteria. /// </summary> /// <param name="item">The <see cref="BaseItem"/>.</param> - /// <param name="parentId">The <see cref="Guid"/>.</param> /// <param name="user">The <see cref="User"/>.</param> /// <param name="sort">The <see cref="SortCriteria"/>.</param> /// <param name="startIndex">The start index.</param> /// <param name="limit">The maximum number to return.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicArtistItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) + private QueryResult<ServerItem> GetMusicArtistItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) { Recursive = true, - ParentId = parentId, ArtistIds = new[] { item.Id }, IncludeItemTypes = new[] { nameof(MusicAlbum) }, Limit = limit, StartIndex = startIndex, - DtoOptions = GetDtoOptions() + DtoOptions = GetDtoOptions(), + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - var result = _libraryManager.GetItemsResult(query); return ToResult(result); @@ -1520,18 +1102,16 @@ namespace Emby.Dlna.ContentDirectory /// Returns the genre items meeting the criteria. /// </summary> /// <param name="item">The <see cref="BaseItem"/>.</param> - /// <param name="parentId">The <see cref="Guid"/>.</param> /// <param name="user">The <see cref="User"/>.</param> /// <param name="sort">The <see cref="SortCriteria"/>.</param> /// <param name="startIndex">The start index.</param> /// <param name="limit">The maximum number to return.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) + private QueryResult<ServerItem> GetGenreItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) { Recursive = true, - ParentId = parentId, GenreIds = new[] { item.Id }, IncludeItemTypes = new[] { @@ -1540,11 +1120,10 @@ namespace Emby.Dlna.ContentDirectory }, Limit = limit, StartIndex = startIndex, - DtoOptions = GetDtoOptions() + DtoOptions = GetDtoOptions(), + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - var result = _libraryManager.GetItemsResult(query); return ToResult(result); @@ -1554,46 +1133,43 @@ namespace Emby.Dlna.ContentDirectory /// Returns the music genre items meeting the criteria. /// </summary> /// <param name="item">The <see cref="BaseItem"/>.</param> - /// <param name="parentId">The <see cref="Guid"/>.</param> /// <param name="user">The <see cref="User"/>.</param> /// <param name="sort">The <see cref="SortCriteria"/>.</param> /// <param name="startIndex">The start index.</param> /// <param name="limit">The maximum number to return.</param> /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> - private QueryResult<ServerItem> GetMusicGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) + private QueryResult<ServerItem> GetMusicGenreItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) { Recursive = true, - ParentId = parentId, GenreIds = new[] { item.Id }, IncludeItemTypes = new[] { nameof(MusicAlbum) }, Limit = limit, StartIndex = startIndex, - DtoOptions = GetDtoOptions() + DtoOptions = GetDtoOptions(), + OrderBy = GetOrderBy(sort, false) }; - SetSorting(query, sort, false); - var result = _libraryManager.GetItemsResult(query); return ToResult(result); } /// <summary> - /// Converts a <see cref="BaseItem"/> array into a <see cref="QueryResult{ServerItem}"/>. + /// Converts <see cref="IReadOnlyCollection{BaseItem}"/> into a <see cref="QueryResult{ServerItem}"/>. /// </summary> /// <param name="result">An array of <see cref="BaseItem"/>.</param> /// <returns>A <see cref="QueryResult{ServerItem}"/>.</returns> - private static QueryResult<ServerItem> ToResult(BaseItem[] result) + private static QueryResult<ServerItem> ToResult(IReadOnlyCollection<BaseItem> result) { var serverItems = result - .Select(i => new ServerItem(i)) + .Select(i => new ServerItem(i, null)) .ToArray(); return new QueryResult<ServerItem> { - TotalRecordCount = result.Length, + TotalRecordCount = result.Count, Items = serverItems }; } @@ -1605,10 +1181,12 @@ namespace Emby.Dlna.ContentDirectory /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> private static QueryResult<ServerItem> ToResult(QueryResult<BaseItem> result) { - var serverItems = result - .Items - .Select(i => new ServerItem(i)) - .ToArray(); + var length = result.Items.Count; + var serverItems = new ServerItem[length]; + for (var i = 0; i < length; i++) + { + serverItems[i] = new ServerItem(result.Items[i], null); + } return new QueryResult<ServerItem> { @@ -1618,35 +1196,34 @@ namespace Emby.Dlna.ContentDirectory } /// <summary> - /// Sets the sorting method on a query. + /// Converts a query result to a <see cref="QueryResult{ServerItem}"/>. /// </summary> - /// <param name="query">The <see cref="InternalItemsQuery"/>.</param> - /// <param name="sort">The <see cref="SortCriteria"/>.</param> - /// <param name="isPreSorted">True if pre-sorted.</param> - private static void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted) + /// <param name="result">A <see cref="QueryResult{BaseItem}"/>.</param> + /// <returns>The <see cref="QueryResult{ServerItem}"/>.</returns> + private static QueryResult<ServerItem> ToResult(QueryResult<(BaseItem, ItemCounts)> result) { - if (isPreSorted) + var length = result.Items.Count; + var serverItems = new ServerItem[length]; + for (var i = 0; i < length; i++) { - query.OrderBy = Array.Empty<(string, SortOrder)>(); + serverItems[i] = new ServerItem(result.Items[i].Item1, null); } - else + + return new QueryResult<ServerItem> { - query.OrderBy = new[] { (ItemSortBy.SortName, sort.SortOrder) }; - } + TotalRecordCount = result.TotalRecordCount, + Items = serverItems + }; } /// <summary> - /// Apply paging to a query. + /// Gets the sorting method on a query. /// </summary> - /// <param name="result">The <see cref="QueryResult{ServerItem}"/>.</param> - /// <param name="startIndex">The start index.</param> - /// <param name="limit">The maximum number to return.</param> - /// <returns>A <see cref="QueryResult{ServerItem}"/>.</returns> - private static QueryResult<ServerItem> ApplyPaging(QueryResult<ServerItem> result, int? startIndex, int? limit) + /// <param name="sort">The <see cref="SortCriteria"/>.</param> + /// <param name="isPreSorted">True if pre-sorted.</param> + private static (string, SortOrder)[] GetOrderBy(SortCriteria sort, bool isPreSorted) { - result.Items = result.Items.Skip(startIndex ?? 0).Take(limit ?? int.MaxValue).ToArray(); - - return result; + return isPreSorted ? Array.Empty<(string, SortOrder)>() : new[] { (ItemSortBy.SortName, sort.SortOrder) }; } /// <summary> @@ -1657,7 +1234,7 @@ namespace Emby.Dlna.ContentDirectory private ServerItem GetItemFromObjectId(string id) { return DidlBuilder.IsIdRoot(id) - ? new ServerItem(_libraryManager.GetUserRootFolder()) + ? new ServerItem(_libraryManager.GetUserRootFolder(), null) : ParseItemId(id); } @@ -1675,37 +1252,29 @@ namespace Emby.Dlna.ContentDirectory var paramsIndex = id.IndexOf(ParamsSrch, StringComparison.OrdinalIgnoreCase); if (paramsIndex != -1) { - id = id.Substring(paramsIndex + ParamsSrch.Length); + id = id[(paramsIndex + ParamsSrch.Length)..]; var parts = id.Split(';'); id = parts[23]; } - var enumNames = Enum.GetNames(typeof(StubType)); - foreach (var name in enumNames) + var dividerIndex = id.IndexOf('_', StringComparison.Ordinal); + if (dividerIndex != -1 && Enum.TryParse<StubType>(id.AsSpan(0, dividerIndex), true, out var parsedStubType)) { - if (id.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase)) - { - stubType = Enum.Parse<StubType>(name, true); - id = id.Split('_', 2)[1]; - - break; - } + id = id[(dividerIndex + 1)..]; + stubType = parsedStubType; } if (Guid.TryParse(id, out var itemId)) { var item = _libraryManager.GetItemById(itemId); - return new ServerItem(item) - { - StubType = stubType - }; + return new ServerItem(item, stubType); } Logger.LogError("Error parsing item Id: {Id}. Returning user root folder.", id); - return new ServerItem(_libraryManager.GetUserRootFolder()); + return new ServerItem(_libraryManager.GetUserRootFolder(), null); } } } diff --git a/Emby.Dlna/ContentDirectory/ServerItem.cs b/Emby.Dlna/ContentDirectory/ServerItem.cs index ff30e6e4a..df05fa966 100644 --- a/Emby.Dlna/ContentDirectory/ServerItem.cs +++ b/Emby.Dlna/ContentDirectory/ServerItem.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using MediaBrowser.Controller.Entities; namespace Emby.Dlna.ContentDirectory @@ -13,24 +11,29 @@ namespace Emby.Dlna.ContentDirectory /// Initializes a new instance of the <see cref="ServerItem"/> class. /// </summary> /// <param name="item">The <see cref="BaseItem"/>.</param> - public ServerItem(BaseItem item) + /// <param name="stubType">The stub type.</param> + public ServerItem(BaseItem item, StubType? stubType) { Item = item; - if (item is IItemByName && item is not Folder) + if (stubType.HasValue) + { + StubType = stubType; + } + else if (item is IItemByName and not Folder) { StubType = Dlna.ContentDirectory.StubType.Folder; } } /// <summary> - /// Gets or sets the underlying base item. + /// Gets the underlying base item. /// </summary> - public BaseItem Item { get; set; } + public BaseItem Item { get; } /// <summary> - /// Gets or sets the DLNA item type. + /// Gets the DLNA item type. /// </summary> - public StubType? StubType { get; set; } + public StubType? StubType { get; } } } diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 0a84f30c4..b00e1c98a 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -729,7 +729,7 @@ namespace Emby.Dlna.Didl { if (item.PremiereDate.HasValue) { - AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("o", CultureInfo.InvariantCulture), NsDc); + AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), NsDc); } } diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 73e8a0008..93efa4b38 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -112,7 +112,7 @@ namespace Emby.Dlna if (profile == null) { - LogUnmatchedProfile(deviceInfo); + _logger.LogInformation("No matching device profile found. The default will need to be used. \n{@Profile}", deviceInfo); } else { @@ -122,23 +122,6 @@ namespace Emby.Dlna return profile; } - private void LogUnmatchedProfile(DeviceIdentification profile) - { - var builder = new StringBuilder(); - - builder.AppendLine("No matching device profile found. The default will need to be used."); - builder.Append("FriendlyName: ").AppendLine(profile.FriendlyName); - builder.Append("Manufacturer: ").AppendLine(profile.Manufacturer); - builder.Append("ManufacturerUrl: ").AppendLine(profile.ManufacturerUrl); - builder.Append("ModelDescription: ").AppendLine(profile.ModelDescription); - builder.Append("ModelName: ").AppendLine(profile.ModelName); - builder.Append("ModelNumber: ").AppendLine(profile.ModelNumber); - builder.Append("ModelUrl: ").AppendLine(profile.ModelUrl); - builder.Append("SerialNumber: ").AppendLine(profile.SerialNumber); - - _logger.LogInformation(builder.ToString()); - } - /// <summary> /// Attempts to match a device with a profile. /// Rules: @@ -367,7 +350,7 @@ namespace Emby.Dlna Directory.CreateDirectory(systemProfilesPath); var fileOptions = AsyncFile.WriteOptions; - fileOptions.Mode = FileMode.CreateNew; + fileOptions.Mode = FileMode.Create; fileOptions.PreallocationSize = length; using (var fileStream = new FileStream(path, fileOptions)) { @@ -416,7 +399,7 @@ namespace Emby.Dlna } /// <inheritdoc /> - public void UpdateProfile(DeviceProfile profile) + public void UpdateProfile(string profileId, DeviceProfile profile) { profile = ReserializeProfile(profile); @@ -430,7 +413,7 @@ namespace Emby.Dlna throw new ArgumentException("Profile is missing Name"); } - var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase)); + var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profileId, StringComparison.OrdinalIgnoreCase)); var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml"; var path = Path.Combine(UserProfilesPath, newFilename); diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index c8332e44e..7fdbd44f0 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -72,7 +72,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> </ItemGroup> </Project> diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 5d252d8dc..f35d90f21 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -52,7 +52,6 @@ namespace Emby.Dlna.Main private readonly ISocketFactory _socketFactory; private readonly INetworkManager _networkManager; private readonly object _syncLock = new object(); - private readonly NetworkConfiguration _netConfig; private readonly bool _disabled; private PlayToManager _manager; @@ -125,8 +124,8 @@ namespace Emby.Dlna.Main config); Current = this; - _netConfig = config.GetConfiguration<NetworkConfiguration>("network"); - _disabled = appHost.ListenWithHttps && _netConfig.RequireHttps; + var netConfig = config.GetConfiguration<NetworkConfiguration>("network"); + _disabled = appHost.ListenWithHttps && netConfig.RequireHttps; if (_disabled && _config.GetDlnaConfiguration().EnableServer) { @@ -219,11 +218,6 @@ namespace Emby.Dlna.Main } } - private void LogMessage(string msg) - { - _logger.LogDebug(msg); - } - private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer) { try @@ -268,12 +262,11 @@ namespace Emby.Dlna.Main { _publisher = new SsdpDevicePublisher( _communicationsServer, - _networkManager, MediaBrowser.Common.System.OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost) { - LogFunction = LogMessage, + LogFunction = (msg) => _logger.LogDebug("{Msg}", msg), SupportPnpRootDevice = false }; @@ -318,15 +311,9 @@ namespace Emby.Dlna.Main var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); + _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address); - var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); - if (!string.IsNullOrEmpty(_appHost.PublishedServerUrl)) - { - // DLNA will only work over http, so we must reset to http:// : {port}. - uri.Scheme = "http"; - uri.Port = _netConfig.HttpServerPortNumber; - } + var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(false) + descriptorUri); var device = new SsdpRootDevice { @@ -412,7 +399,6 @@ namespace Emby.Dlna.Main _imageProcessor, _deviceDiscovery, _httpClientFactory, - _config, _userDataManager, _localization, _mediaSourceManager, diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 7927f5f8f..294bda5b6 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Jellyfin.Data.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; @@ -35,7 +34,6 @@ namespace Emby.Dlna.PlayTo private readonly IServerApplicationHost _appHost; private readonly IImageProcessor _imageProcessor; private readonly IHttpClientFactory _httpClientFactory; - private readonly IServerConfigurationManager _config; private readonly IUserDataManager _userDataManager; private readonly ILocalizationManager _localization; @@ -47,7 +45,7 @@ namespace Emby.Dlna.PlayTo private SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1); private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource(); - public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClientFactory httpClientFactory, IServerConfigurationManager config, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder) + public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClientFactory httpClientFactory, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder) { _logger = logger; _sessionManager = sessionManager; @@ -58,7 +56,6 @@ namespace Emby.Dlna.PlayTo _imageProcessor = imageProcessor; _deviceDiscovery = deviceDiscovery; _httpClientFactory = httpClientFactory; - _config = config; _userDataManager = userDataManager; _localization = localization; _mediaSourceManager = mediaSourceManager; diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 581e4a286..780aad9c1 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -64,7 +64,7 @@ namespace Emby.Dlna.Service requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false); } - Logger.LogDebug("Received control request {0}", requestInfo.LocalName); + Logger.LogDebug("Received control request {LocalName}, params: {@Headers}", requestInfo.LocalName, requestInfo.Headers); var settings = new XmlWriterSettings { diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index ac73cfa42..3f75e4fc7 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -26,7 +26,7 @@ namespace Emby.Drawing public sealed class ImageProcessor : IImageProcessor, IDisposable { // Increment this when there's a change requiring caches to be invalidated - private const string Version = "3"; + private const char Version = '3'; private static readonly HashSet<string> _transparentImageTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" }; diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 6355f8b1b..7bc9fbce8 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -1,3 +1,5 @@ +#pragma warning disable CA1819 + using System; using System.Linq; using System.Text.RegularExpressions; @@ -253,6 +255,8 @@ namespace Emby.Naming.Common }, // <!-- foo.ep01, foo.EP_01 --> new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"), + // <!-- foo.E01., foo.e01. --> + new EpisodeExpression(@"[^\\/]*?()\.?[Ee]([0-9]+)\.([^\\/]*)$"), new EpisodeExpression("(?<year>[0-9]{4})[\\.-](?<month>[0-9]{2})[\\.-](?<day>[0-9]{2})", true) { DateTimeFormats = new[] @@ -371,6 +375,20 @@ namespace Emby.Naming.Common IsOptimistic = true, IsNamed = true }, + + // Series and season only expression + // "the show/season 1", "the show/s01" + new EpisodeExpression(@"(.*(\\|\/))*(?<seriesname>.+)\/[Ss](eason)?[\. _\-]*(?<seasonnumber>[0-9]+)") + { + IsNamed = true + }, + + // Series and season only expression + // "the show S01", "the show season 1" + new EpisodeExpression(@"(.*(\\|\/))*(?<seriesname>.+)[\. _\-]+[sS](eason)?[\. _\-]*(?<seasonnumber>[0-9]+)") + { + IsNamed = true + }, }; EpisodeWithoutSeasonExpressions = new[] diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index e9e9edda6..2bf8eacb1 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -38,7 +38,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> </ItemGroup> <!-- Code Analyzers--> diff --git a/Emby.Naming/TV/SeriesInfo.cs b/Emby.Naming/TV/SeriesInfo.cs new file mode 100644 index 000000000..5d6cb4bd3 --- /dev/null +++ b/Emby.Naming/TV/SeriesInfo.cs @@ -0,0 +1,29 @@ +namespace Emby.Naming.TV +{ + /// <summary> + /// Holder object for Series information. + /// </summary> + public class SeriesInfo + { + /// <summary> + /// Initializes a new instance of the <see cref="SeriesInfo"/> class. + /// </summary> + /// <param name="path">Path to the file.</param> + public SeriesInfo(string path) + { + Path = path; + } + + /// <summary> + /// Gets or sets the path. + /// </summary> + /// <value>The path.</value> + public string Path { get; set; } + + /// <summary> + /// Gets or sets the name of the series. + /// </summary> + /// <value>The name of the series.</value> + public string? Name { get; set; } + } +} diff --git a/Emby.Naming/TV/SeriesPathParser.cs b/Emby.Naming/TV/SeriesPathParser.cs new file mode 100644 index 000000000..a62e5f4d6 --- /dev/null +++ b/Emby.Naming/TV/SeriesPathParser.cs @@ -0,0 +1,61 @@ +using System.Globalization; +using Emby.Naming.Common; + +namespace Emby.Naming.TV +{ + /// <summary> + /// Used to parse information about series from paths containing more information that only the series name. + /// Uses the same regular expressions as the EpisodePathParser but have different success criteria. + /// </summary> + public static class SeriesPathParser + { + /// <summary> + /// Parses information about series from path. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing EpisodeExpressions and MultipleEpisodeExpressions.</param> + /// <param name="path">Path.</param> + /// <returns>Returns <see cref="SeriesPathParserResult"/> object.</returns> + public static SeriesPathParserResult Parse(NamingOptions options, string path) + { + SeriesPathParserResult? result = null; + + foreach (var expression in options.EpisodeExpressions) + { + var currentResult = Parse(path, expression); + if (currentResult.Success) + { + result = currentResult; + break; + } + } + + if (result != null) + { + if (!string.IsNullOrEmpty(result.SeriesName)) + { + result.SeriesName = result.SeriesName.Trim(' ', '_', '.', '-'); + } + } + + return result ?? new SeriesPathParserResult(); + } + + private static SeriesPathParserResult Parse(string name, EpisodeExpression expression) + { + var result = new SeriesPathParserResult(); + + var match = expression.Regex.Match(name); + + if (match.Success && match.Groups.Count >= 3) + { + if (expression.IsNamed) + { + result.SeriesName = match.Groups["seriesname"].Value; + result.Success = !string.IsNullOrEmpty(result.SeriesName) && !string.IsNullOrEmpty(match.Groups["seasonnumber"]?.Value); + } + } + + return result; + } + } +} diff --git a/Emby.Naming/TV/SeriesPathParserResult.cs b/Emby.Naming/TV/SeriesPathParserResult.cs new file mode 100644 index 000000000..44cd2fdfa --- /dev/null +++ b/Emby.Naming/TV/SeriesPathParserResult.cs @@ -0,0 +1,19 @@ +namespace Emby.Naming.TV +{ + /// <summary> + /// Holder object for <see cref="SeriesPathParser"/> result. + /// </summary> + public class SeriesPathParserResult + { + /// <summary> + /// Gets or sets the name of the series. + /// </summary> + /// <value>The name of the series.</value> + public string? SeriesName { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether parsing was successful. + /// </summary> + public bool Success { get; set; } + } +} diff --git a/Emby.Naming/TV/SeriesResolver.cs b/Emby.Naming/TV/SeriesResolver.cs new file mode 100644 index 000000000..156a03c9e --- /dev/null +++ b/Emby.Naming/TV/SeriesResolver.cs @@ -0,0 +1,49 @@ +using System.IO; +using System.Text.RegularExpressions; +using Emby.Naming.Common; + +namespace Emby.Naming.TV +{ + /// <summary> + /// Used to resolve information about series from path. + /// </summary> + public static class SeriesResolver + { + /// <summary> + /// Regex that matches strings of at least 2 characters separated by a dot or underscore. + /// Used for removing separators between words, i.e turns "The_show" into "The show" while + /// preserving namings like "S.H.O.W". + /// </summary> + private static readonly Regex _seriesNameRegex = new Regex(@"((?<a>[^\._]{2,})[\._]*)|([\._](?<b>[^\._]{2,}))"); + + /// <summary> + /// Resolve information about series from path. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object passed to <see cref="SeriesPathParser"/>.</param> + /// <param name="path">Path to series.</param> + /// <returns>SeriesInfo.</returns> + public static SeriesInfo Resolve(NamingOptions options, string path) + { + string seriesName = Path.GetFileName(path); + + SeriesPathParserResult result = SeriesPathParser.Parse(options, path); + if (result.Success) + { + if (!string.IsNullOrEmpty(result.SeriesName)) + { + seriesName = result.SeriesName; + } + } + + if (!string.IsNullOrEmpty(seriesName)) + { + seriesName = _seriesNameRegex.Replace(seriesName, "${a} ${b}").Trim(); + } + + return new SeriesInfo(path) + { + Name = seriesName + }; + } + } +} diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 6fd152a42..903c31133 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -3,6 +3,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -18,6 +19,7 @@ using Emby.Dlna; using Emby.Dlna.Main; using Emby.Dlna.Ssdp; using Emby.Drawing; +using Emby.Naming.Common; using Emby.Notifications; using Emby.Photos; using Emby.Server.Implementations.Archiving; @@ -56,6 +58,7 @@ using MediaBrowser.Common.Updates; using MediaBrowser.Controller; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Chapters; +using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; @@ -117,7 +120,7 @@ namespace Emby.Server.Implementations /// <summary> /// The disposable parts. /// </summary> - private readonly List<IDisposable> _disposableParts = new List<IDisposable>(); + private readonly ConcurrentDictionary<IDisposable, byte> _disposableParts = new (); private readonly IFileSystem _fileSystemManager; private readonly IConfiguration _startupConfig; @@ -128,7 +131,6 @@ namespace Emby.Server.Implementations private List<Type> _creatingInstances; private IMediaEncoder _mediaEncoder; private ISessionManager _sessionManager; - private string[] _urlPrefixes; /// <summary> /// Gets or sets all concrete types. @@ -147,25 +149,20 @@ namespace Emby.Server.Implementations /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param> /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param> - /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> - /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param> public ApplicationHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, - IConfiguration startupConfig, - IFileSystem fileSystem, - IServiceCollection serviceCollection) + IConfiguration startupConfig) { ApplicationPaths = applicationPaths; LoggerFactory = loggerFactory; _startupOptions = options; _startupConfig = startupConfig; - _fileSystemManager = fileSystem; - ServiceCollection = serviceCollection; + _fileSystemManager = new ManagedFileSystem(LoggerFactory.CreateLogger<ManagedFileSystem>(), applicationPaths); Logger = LoggerFactory.CreateLogger<ApplicationHost>(); - fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); + _fileSystemManager.AddShortcutHandler(new MbLinkShortcutHandler(_fileSystemManager)); ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; ApplicationVersionString = ApplicationVersion.ToString(3); @@ -214,7 +211,7 @@ namespace Emby.Server.Implementations /// <summary> /// Gets the <see cref="INetworkManager"/> singleton instance. /// </summary> - public INetworkManager NetManager { get; internal set; } + public INetworkManager NetManager { get; private set; } /// <summary> /// Gets a value indicating whether this instance has changes that require the entire application to restart. @@ -230,24 +227,22 @@ namespace Emby.Server.Implementations /// </summary> protected ILogger<ApplicationHost> Logger { get; } - protected IServiceCollection ServiceCollection { get; } - /// <summary> /// Gets the logger factory. /// </summary> protected ILoggerFactory LoggerFactory { get; } /// <summary> - /// Gets or sets the application paths. + /// Gets the application paths. /// </summary> /// <value>The application paths.</value> - protected IServerApplicationPaths ApplicationPaths { get; set; } + protected IServerApplicationPaths ApplicationPaths { get; } /// <summary> - /// Gets or sets the configuration manager. + /// Gets the configuration manager. /// </summary> /// <value>The configuration manager.</value> - public ServerConfigurationManager ConfigurationManager { get; set; } + public ServerConfigurationManager ConfigurationManager { get; } /// <summary> /// Gets or sets the service provider. @@ -351,22 +346,6 @@ namespace Emby.Server.Implementations } /// <summary> - /// Creates an instance of type and resolves all constructor dependencies. - /// </summary> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - public object CreateInstance(Type type) - => ActivatorUtilities.CreateInstance(ServiceProvider, type); - - /// <summary> - /// Creates an instance of type and resolves all constructor dependencies. - /// </summary> - /// <typeparam name="T">The type.</typeparam> - /// <returns>T.</returns> - public T CreateInstance<T>() - => ActivatorUtilities.CreateInstance<T>(ServiceProvider); - - /// <summary> /// Creates the instance safe. /// </summary> /// <param name="type">The type.</param> @@ -375,7 +354,7 @@ namespace Emby.Server.Implementations { _creatingInstances ??= new List<Type>(); - if (_creatingInstances.IndexOf(type) != -1) + if (_creatingInstances.Contains(type)) { Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName); foreach (var entry in _creatingInstances) @@ -385,7 +364,7 @@ namespace Emby.Server.Implementations _pluginManager.FailPlugin(type.Assembly); - throw new ExternalException("DI Loop detected."); + throw new TypeLoadException("DI Loop detected"); } try @@ -418,8 +397,15 @@ namespace Emby.Server.Implementations public IEnumerable<Type> GetExportTypes<T>() { var currentType = typeof(T); - - return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i)); + var numberOfConcreteTypes = _allConcreteTypes.Length; + for (var i = 0; i < numberOfConcreteTypes; i++) + { + var type = _allConcreteTypes[i]; + if (currentType.IsAssignableFrom(type)) + { + yield return type; + } + } } /// <inheritdoc /> @@ -434,9 +420,9 @@ namespace Emby.Server.Implementations if (manageLifetime) { - lock (_disposableParts) + foreach (var part in parts.OfType<IDisposable>()) { - _disposableParts.AddRange(parts.OfType<IDisposable>()); + _disposableParts.TryAdd(part, byte.MinValue); } } @@ -455,9 +441,9 @@ namespace Emby.Server.Implementations if (manageLifetime) { - lock (_disposableParts) + foreach (var part in parts.OfType<IDisposable>()) { - _disposableParts.AddRange(parts.OfType<IDisposable>()); + _disposableParts.TryAdd(part, byte.MinValue); } } @@ -521,7 +507,7 @@ namespace Emby.Server.Implementations } /// <inheritdoc/> - public void Init() + public void Init(IServiceCollection serviceCollection) { DiscoverTypes(); @@ -551,128 +537,130 @@ namespace Emby.Server.Implementations CertificatePath = networkConfiguration.CertificatePath; Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword); - RegisterServices(); + RegisterServices(serviceCollection); - _pluginManager.RegisterServices(ServiceCollection); + _pluginManager.RegisterServices(serviceCollection); } /// <summary> /// Registers services/resources with the service collection that will be available via DI. /// </summary> - protected virtual void RegisterServices() + /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param> + protected virtual void RegisterServices(IServiceCollection serviceCollection) { - ServiceCollection.AddSingleton(_startupOptions); + serviceCollection.AddSingleton(_startupOptions); - ServiceCollection.AddMemoryCache(); + serviceCollection.AddMemoryCache(); - ServiceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager); - ServiceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager); - ServiceCollection.AddSingleton<IApplicationHost>(this); - ServiceCollection.AddSingleton<IPluginManager>(_pluginManager); - ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths); + serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager); + serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager); + serviceCollection.AddSingleton<IApplicationHost>(this); + serviceCollection.AddSingleton(_pluginManager); + serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths); - ServiceCollection.AddSingleton(_fileSystemManager); - ServiceCollection.AddSingleton<TmdbClientManager>(); + serviceCollection.AddSingleton(_fileSystemManager); + serviceCollection.AddSingleton<TmdbClientManager>(); - ServiceCollection.AddSingleton(NetManager); + serviceCollection.AddSingleton(NetManager); - ServiceCollection.AddSingleton<ITaskManager, TaskManager>(); + serviceCollection.AddSingleton<ITaskManager, TaskManager>(); - ServiceCollection.AddSingleton(_xmlSerializer); + serviceCollection.AddSingleton(_xmlSerializer); - ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>(); + serviceCollection.AddSingleton<IStreamHelper, StreamHelper>(); - ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>(); + serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>(); - ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>(); + serviceCollection.AddSingleton<ISocketFactory, SocketFactory>(); - ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>(); + serviceCollection.AddSingleton<IInstallationManager, InstallationManager>(); - ServiceCollection.AddSingleton<IZipClient, ZipClient>(); + serviceCollection.AddSingleton<IZipClient, ZipClient>(); - ServiceCollection.AddSingleton<IServerApplicationHost>(this); - ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths); + serviceCollection.AddSingleton<IServerApplicationHost>(this); + serviceCollection.AddSingleton(ApplicationPaths); - ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>(); + serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>(); - ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>(); + serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>(); - ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>(); - ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>(); + serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>(); + serviceCollection.AddSingleton<IUserDataManager, UserDataManager>(); - ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>(); + serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>(); - ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(); - ServiceCollection.AddSingleton<EncodingHelper>(); + serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(); + serviceCollection.AddSingleton<EncodingHelper>(); // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required - ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>)); - ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>)); - ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>)); - ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>(); + serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>)); + serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>)); + serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>)); + serviceCollection.AddSingleton<ILibraryManager, LibraryManager>(); + serviceCollection.AddSingleton<NamingOptions>(); - ServiceCollection.AddSingleton<IMusicManager, MusicManager>(); + serviceCollection.AddSingleton<IMusicManager, MusicManager>(); - ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>(); + serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>(); - ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>(); + serviceCollection.AddSingleton<ISearchEngine, SearchEngine>(); - ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>(); + serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>(); - ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>(); + serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>(); - ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>(); + serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>(); - ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>(); + serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>(); - ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>(); + serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>(); - ServiceCollection.AddSingleton<IProviderManager, ProviderManager>(); + serviceCollection.AddSingleton<IProviderManager, ProviderManager>(); // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required - ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>)); - ServiceCollection.AddSingleton<IDtoService, DtoService>(); - - ServiceCollection.AddSingleton<IChannelManager, ChannelManager>(); + serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>)); + serviceCollection.AddSingleton<IDtoService, DtoService>(); - ServiceCollection.AddSingleton<ISessionManager, SessionManager>(); + serviceCollection.AddSingleton<IChannelManager, ChannelManager>(); - ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>(); + serviceCollection.AddSingleton<ISessionManager, SessionManager>(); - ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>(); + serviceCollection.AddSingleton<IDlnaManager, DlnaManager>(); - ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>(); + serviceCollection.AddSingleton<ICollectionManager, CollectionManager>(); - ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>(); + serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>(); - ServiceCollection.AddSingleton<LiveTvDtoService>(); - ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>(); + serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>(); - ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>(); + serviceCollection.AddSingleton<LiveTvDtoService>(); + serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>(); - ServiceCollection.AddSingleton<INotificationManager, NotificationManager>(); + serviceCollection.AddSingleton<IUserViewManager, UserViewManager>(); - ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>(); + serviceCollection.AddSingleton<INotificationManager, NotificationManager>(); - ServiceCollection.AddSingleton<IChapterManager, ChapterManager>(); + serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>(); - ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>(); + serviceCollection.AddSingleton<IChapterManager, ChapterManager>(); - ServiceCollection.AddScoped<ISessionContext, SessionContext>(); + serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>(); - ServiceCollection.AddSingleton<IAuthService, AuthService>(); - ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>(); + serviceCollection.AddScoped<ISessionContext, SessionContext>(); - ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>(); + serviceCollection.AddSingleton<IAuthService, AuthService>(); + serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>(); - ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>(); + serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>(); - ServiceCollection.AddSingleton<TranscodingJobHelper>(); - ServiceCollection.AddScoped<MediaInfoHelper>(); - ServiceCollection.AddScoped<AudioHelper>(); - ServiceCollection.AddScoped<DynamicHlsHelper>(); + serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>(); - ServiceCollection.AddSingleton<IDirectoryService, DirectoryService>(); + serviceCollection.AddSingleton<TranscodingJobHelper>(); + serviceCollection.AddScoped<MediaInfoHelper>(); + serviceCollection.AddScoped<AudioHelper>(); + serviceCollection.AddScoped<DynamicHlsHelper>(); + serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>(); + serviceCollection.AddSingleton<IDirectoryService, DirectoryService>(); } /// <summary> @@ -795,8 +783,6 @@ namespace Emby.Server.Implementations _pluginManager.CreatePlugins(); - _urlPrefixes = GetUrlPrefixes().ToArray(); - Resolve<ILibraryManager>().AddParts( GetExports<IResolverIgnoreRule>(), GetExports<IItemResolver>(), @@ -864,32 +850,12 @@ namespace Emby.Server.Implementations } } - private IEnumerable<string> GetUrlPrefixes() - { - var hosts = new[] { "+" }; - - return hosts.SelectMany(i => - { - var prefixes = new List<string> - { - "http://" + i + ":" + HttpPort + "/" - }; - - if (Certificate != null) - { - prefixes.Add("https://" + i + ":" + HttpsPort + "/"); - } - - return prefixes; - }); - } - /// <summary> /// Called when [configuration updated]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> - protected void OnConfigurationUpdated(object sender, EventArgs e) + private void OnConfigurationUpdated(object sender, EventArgs e) { var requiresRestart = false; var networkConfiguration = ConfigurationManager.GetNetworkConfiguration(); @@ -898,8 +864,8 @@ namespace Emby.Server.Implementations if (HttpPort != 0 && HttpsPort != 0) { // Need to restart if ports have changed - if (networkConfiguration.HttpServerPortNumber != HttpPort || - networkConfiguration.HttpsPortNumber != HttpsPort) + if (networkConfiguration.HttpServerPortNumber != HttpPort + || networkConfiguration.HttpsPortNumber != HttpsPort) { if (ConfigurationManager.Configuration.IsPortAuthorized) { @@ -911,11 +877,6 @@ namespace Emby.Server.Implementations } } - if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase)) - { - requiresRestart = true; - } - if (ValidateSslCertificate(networkConfiguration)) { requiresRestart = true; @@ -957,7 +918,7 @@ namespace Emby.Server.Implementations } /// <summary> - /// Notifies that the kernel that a change has been made that requires a restart. + /// Notifies the kernel that a change has been made that requires a restart. /// </summary> public void NotifyPendingRestart() { @@ -1098,11 +1059,6 @@ namespace Emby.Server.Implementations }; } - public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo() - => NetManager.GetMacAddresses() - .Select(i => new WakeOnLanInfo(i)) - .ToList(); - public PublicSystemInfo GetPublicSystemInfo(HttpRequest request) { return new PublicSystemInfo @@ -1118,7 +1074,7 @@ namespace Emby.Server.Implementations } /// <inheritdoc/> - public string GetSmartApiUrl(IPAddress remoteAddr, int? port = null) + public string GetSmartApiUrl(IPAddress remoteAddr) { // Published server ends with a / if (!string.IsNullOrEmpty(PublishedServerUrl)) @@ -1127,18 +1083,12 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(remoteAddr, out port); - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - + string smart = NetManager.GetBindInterface(remoteAddr, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } /// <inheritdoc/> - public string GetSmartApiUrl(HttpRequest request, int? port = null) + public string GetSmartApiUrl(HttpRequest request) { // Return the host in the HTTP request as the API url if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest) @@ -1159,18 +1109,12 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(request, out port); - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - + string smart = NetManager.GetBindInterface(request, out var port); return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port); } /// <inheritdoc/> - public string GetSmartApiUrl(string hostname, int? port = null) + public string GetSmartApiUrl(string hostname) { // Published server ends with a / if (!string.IsNullOrEmpty(PublishedServerUrl)) @@ -1179,31 +1123,29 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(hostname, out port); - - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - + string smart = NetManager.GetBindInterface(hostname, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } /// <inheritdoc/> - public string GetLoopbackHttpApiUrl() + public string GetApiUrlForLocalAccess(bool allowHttps = true) { - if (NetManager.IsIP6Enabled) - { - return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort); - } - - return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort); + // With an empty source, the port will be null + string smart = NetManager.GetBindInterface(string.Empty, out _); + var scheme = !allowHttps ? Uri.UriSchemeHttp : null; + int? port = !allowHttps ? HttpPort : null; + return GetLocalApiUrl(smart.Trim('/'), scheme, port); } /// <inheritdoc/> public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null) { + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return hostname.TrimEnd('/'); + } + // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does // not. For consistency, always trim the trailing slash. return new UriBuilder @@ -1277,12 +1219,15 @@ namespace Emby.Server.Implementations Logger.LogInformation("Disposing {Type}", type.Name); - var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList(); - _disposableParts.Clear(); - - foreach (var part in parts) + foreach (var (part, _) in _disposableParts) { - Logger.LogInformation("Disposing {Type}", part.GetType().Name); + var partType = part.GetType(); + if (partType == type) + { + continue; + } + + Logger.LogInformation("Disposing {Type}", partType.Name); try { @@ -1290,9 +1235,11 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name); + Logger.LogError(ex, "Error disposing {Type}", partType.Name); } } + + _disposableParts.Clear(); } _disposed = true; diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 09aee602a..f65eaec1c 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -1075,14 +1075,6 @@ namespace Emby.Server.Implementations.Channels forceUpdate = true; } - // was used for status - // if (!string.Equals(item.ExternalEtag ?? string.Empty, info.Etag ?? string.Empty, StringComparison.Ordinal)) - // { - // item.ExternalEtag = info.Etag; - // forceUpdate = true; - // _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name); - // } - if (!internalChannelId.Equals(item.ChannelId)) { forceUpdate = true; diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 673810c49..e9c005cea 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Security.Cryptography; +using System.Text; using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Cryptography; -using static MediaBrowser.Common.Cryptography.Constants; +using static MediaBrowser.Model.Cryptography.Constants; namespace Emby.Server.Implementations.Cryptography { @@ -12,10 +14,7 @@ namespace Emby.Server.Implementations.Cryptography /// </summary> public class CryptographyProvider : ICryptoProvider { - // FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto - // Currently supported hash methods from https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptoconfig?view=netcore-2.1 - // there might be a better way to autogenerate this list as dotnet updates, but I couldn't find one - // Please note the default method of PBKDF2 is not included, it cannot be used to generate hashes cleanly as it is actually a pbkdf with sha1 + // TODO: remove when not needed for backwards compat private static readonly HashSet<string> _supportedHashMethods = new HashSet<string>() { "MD5", @@ -35,60 +34,81 @@ namespace Emby.Server.Implementations.Cryptography }; /// <inheritdoc /> - public string DefaultHashMethod => "PBKDF2"; + public string DefaultHashMethod => "PBKDF2-SHA512"; /// <inheritdoc /> - public IEnumerable<string> GetSupportedHashMethods() - => _supportedHashMethods; - - private byte[] PBKDF2(string method, byte[] bytes, byte[] salt, int iterations) + public PasswordHash CreatePasswordHash(ReadOnlySpan<char> password) { - // downgrading for now as we need this library to be dotnetstandard compliant - // with this downgrade we'll add a check to make sure we're on the downgrade method at the moment - if (method != DefaultHashMethod) - { - throw new CryptographicException($"Cannot currently use PBKDF2 with requested hash method: {method}"); - } - - using var r = new Rfc2898DeriveBytes(bytes, salt, iterations); - return r.GetBytes(32); + byte[] salt = GenerateSalt(); + return new PasswordHash( + DefaultHashMethod, + Rfc2898DeriveBytes.Pbkdf2( + password, + salt, + DefaultIterations, + HashAlgorithmName.SHA512, + DefaultOutputLength), + salt, + new Dictionary<string, string> + { + { "iterations", DefaultIterations.ToString(CultureInfo.InvariantCulture) } + }); } /// <inheritdoc /> - public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt) + public bool Verify(PasswordHash hash, ReadOnlySpan<char> password) { - if (hashMethod == DefaultHashMethod) + if (string.Equals(hash.Id, "PBKDF2", StringComparison.Ordinal)) { - return PBKDF2(hashMethod, bytes, salt, DefaultIterations); + return hash.Hash.SequenceEqual( + Rfc2898DeriveBytes.Pbkdf2( + password, + hash.Salt, + int.Parse(hash.Parameters["iterations"], CultureInfo.InvariantCulture), + HashAlgorithmName.SHA1, + 32)); } - if (!_supportedHashMethods.Contains(hashMethod)) + if (string.Equals(hash.Id, "PBKDF2-SHA512", StringComparison.Ordinal)) { - throw new CryptographicException($"Requested hash method is not supported: {hashMethod}"); + return hash.Hash.SequenceEqual( + Rfc2898DeriveBytes.Pbkdf2( + password, + hash.Salt, + int.Parse(hash.Parameters["iterations"], CultureInfo.InvariantCulture), + HashAlgorithmName.SHA512, + DefaultOutputLength)); } - using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException($"Unknown hash method: {hashMethod}."); - if (salt.Length == 0) + if (!_supportedHashMethods.Contains(hash.Id)) { - return h.ComputeHash(bytes); + throw new CryptographicException($"Requested hash method is not supported: {hash.Id}"); } - byte[] salted = new byte[bytes.Length + salt.Length]; + using var h = HashAlgorithm.Create(hash.Id) ?? throw new ResourceNotFoundException($"Unknown hash method: {hash.Id}."); + var bytes = Encoding.UTF8.GetBytes(password.ToArray()); + if (hash.Salt.Length == 0) + { + return hash.Hash.SequenceEqual(h.ComputeHash(bytes)); + } + + byte[] salted = new byte[bytes.Length + hash.Salt.Length]; Array.Copy(bytes, salted, bytes.Length); - Array.Copy(salt, 0, salted, bytes.Length, salt.Length); - return h.ComputeHash(salted); + hash.Salt.CopyTo(salted.AsSpan(bytes.Length)); + return hash.Hash.SequenceEqual(h.ComputeHash(salted)); } /// <inheritdoc /> - public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt) - => PBKDF2(DefaultHashMethod, bytes, salt, DefaultIterations); - - /// <inheritdoc /> public byte[] GenerateSalt() => GenerateSalt(DefaultSaltLength); /// <inheritdoc /> public byte[] GenerateSalt(int length) - => RandomNumberGenerator.GetBytes(length); + { + var salt = new byte[length]; + using var rng = RandomNumberGenerator.Create(); + rng.GetNonZeroBytes(salt); + return salt; + } } } diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs index 44dad5b17..11e33278d 100644 --- a/Emby.Server.Implementations/Data/ManagedConnection.cs +++ b/Emby.Server.Implementations/Data/ManagedConnection.cs @@ -7,7 +7,7 @@ using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data { - public class ManagedConnection : IDisposable + public sealed class ManagedConnection : IDisposable { private readonly SemaphoreSlim _writeLock; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index ad76f3d6d..b91ff6408 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -134,14 +134,11 @@ namespace Emby.Server.Implementations.Dto var dto = GetBaseItemDtoInternal(item, options, user, owner); if (item is LiveTvChannel tvChannel) { - var list = new List<(BaseItemDto, LiveTvChannel)>(1) { (dto, tvChannel) }; - LivetvManager.AddChannelInfo(list, options, user); + LivetvManager.AddChannelInfo(new[] { (dto, tvChannel) }, options, user); } else if (item is LiveTvProgram) { - var list = new List<(BaseItem, BaseItemDto)>(1) { (item, dto) }; - var task = LivetvManager.AddInfoToProgramDto(list, options.Fields, user); - Task.WaitAll(task); + LivetvManager.AddInfoToProgramDto(new[] { (item, dto) }, options.Fields, user).GetAwaiter().GetResult(); } if (item is IItemByName itemByName @@ -373,6 +370,12 @@ namespace Emby.Server.Implementations.Dto if (item is MusicAlbum || item is Season || item is Playlist) { dto.ChildCount = dto.RecursiveItemCount; + var folderChildCount = folder.LinkedChildren.Length; + // The default is an empty array, so we can't reliably use the count when it's empty + if (folderChildCount > 0) + { + dto.ChildCount ??= folderChildCount; + } } if (options.ContainsField(ItemFields.ChildCount)) @@ -497,7 +500,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError(ex, "Error getting {imageType} image info for {path}", image.Type, image.Path); + _logger.LogError(ex, "Error getting {ImageType} image info for {Path}", image.Type, image.Path); return null; } } @@ -755,15 +758,6 @@ namespace Emby.Server.Implementations.Dto dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit); } - if (options.ContainsField(ItemFields.ScreenshotImageTags)) - { - var screenshotLimit = options.GetImageLimit(ImageType.Screenshot); - if (screenshotLimit > 0) - { - dto.ScreenshotImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Screenshot, screenshotLimit); - } - } - if (options.ContainsField(ItemFields.Genres)) { dto.Genres = item.Genres; diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index c1ce4b557..95acd216d 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -25,14 +25,14 @@ <ItemGroup> <PackageReference Include="DiscUtils.Udf" Version="0.16.13" /> <PackageReference Include="Jellyfin.XmlTv" Version="10.6.2" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0-rc.2*" /> - <PackageReference Include="Mono.Nat" Version="3.0.1" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0" /> + <PackageReference Include="Mono.Nat" Version="3.0.2" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.2.2" /> - <PackageReference Include="sharpcompress" Version="0.30.0" /> + <PackageReference Include="sharpcompress" Version="0.30.1" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="3.1.0" /> <PackageReference Include="DotNet.Glob" Version="3.1.3" /> </ItemGroup> diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 640754af4..d325fa14f 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -27,7 +27,6 @@ namespace Emby.Server.Implementations.EntryPoints private readonly IServerApplicationHost _appHost; private readonly ILogger<ExternalPortForwarding> _logger; private readonly IServerConfigurationManager _config; - private readonly IDeviceDiscovery _deviceDiscovery; private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>(); @@ -42,17 +41,14 @@ namespace Emby.Server.Implementations.EntryPoints /// <param name="logger">The logger.</param> /// <param name="appHost">The application host.</param> /// <param name="config">The configuration manager.</param> - /// <param name="deviceDiscovery">The device discovery.</param> public ExternalPortForwarding( ILogger<ExternalPortForwarding> logger, IServerApplicationHost appHost, - IServerConfigurationManager config, - IDeviceDiscovery deviceDiscovery) + IServerConfigurationManager config) { _logger = logger; _appHost = appHost; _config = config; - _deviceDiscovery = deviceDiscovery; } private string GetConfigIdentifier() diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index e2ad07177..e7103ec95 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -24,7 +24,7 @@ namespace Emby.Server.Implementations.HttpServer.Security if (!auth.HasToken) { - throw new AuthenticationException("Request does not contain a token."); + return auth; } if (!auth.IsAuthenticated) diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index f86bfd755..e99876dce 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -35,7 +35,12 @@ namespace Emby.Server.Implementations.HttpServer /// <inheritdoc /> public async Task WebSocketRequestHandler(HttpContext context) { - _ = await _authService.Authenticate(context.Request).ConfigureAwait(false); + var authorizationInfo = await _authService.Authenticate(context.Request).ConfigureAwait(false); + if (!authorizationInfo.IsAuthenticated) + { + throw new SecurityException("Token is required"); + } + try { _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress); diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 47a83d77c..e62361c1e 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -1,5 +1,3 @@ -#nullable disable - #pragma warning disable CS1591 using System; @@ -14,7 +12,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.IO { - public class FileRefresher : IDisposable + public sealed class FileRefresher : IDisposable { private readonly ILogger _logger; private readonly ILibraryManager _libraryManager; @@ -22,7 +20,7 @@ namespace Emby.Server.Implementations.IO private readonly List<string> _affectedPaths = new List<string>(); private readonly object _timerLock = new object(); - private Timer _timer; + private Timer? _timer; private bool _disposed; public FileRefresher(string path, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger logger) @@ -36,7 +34,7 @@ namespace Emby.Server.Implementations.IO AddPath(path); } - public event EventHandler<EventArgs> Completed; + public event EventHandler<EventArgs>? Completed; public string Path { get; private set; } @@ -111,7 +109,7 @@ namespace Emby.Server.Implementations.IO RestartTimer(); } - private void OnTimerCallback(object state) + private void OnTimerCallback(object? state) { List<string> paths; @@ -127,7 +125,7 @@ namespace Emby.Server.Implementations.IO try { - ProcessPathChanges(paths.ToList()); + ProcessPathChanges(paths); } catch (Exception ex) { @@ -137,12 +135,12 @@ namespace Emby.Server.Implementations.IO private void ProcessPathChanges(List<string> paths) { - var itemsToRefresh = paths + IEnumerable<BaseItem> itemsToRefresh = paths .Distinct(StringComparer.OrdinalIgnoreCase) .Select(GetAffectedBaseItem) .Where(item => item != null) - .GroupBy(x => x.Id) - .Select(x => x.First()); + .GroupBy(x => x!.Id) // Removed null values in the previous .Where() + .Select(x => x.First())!; foreach (var item in itemsToRefresh) { @@ -176,15 +174,15 @@ namespace Emby.Server.Implementations.IO /// </summary> /// <param name="path">The path.</param> /// <returns>BaseItem.</returns> - private BaseItem GetAffectedBaseItem(string path) + private BaseItem? GetAffectedBaseItem(string path) { - BaseItem item = null; + BaseItem? item = null; while (item == null && !string.IsNullOrEmpty(path)) { item = _libraryManager.FindByPath(path, null); - path = System.IO.Path.GetDirectoryName(path); + path = System.IO.Path.GetDirectoryName(path) ?? string.Empty; } if (item != null) diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index e9d069cd3..9fcc7fe59 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations.IO if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; - _logger.LogInformation("Watching directory " + path); + _logger.LogInformation("Watching directory {Path}", path); } else { @@ -276,7 +276,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - _logger.LogError(ex, "Error watching path: {path}", path); + _logger.LogError(ex, "Error watching path: {Path}", path); } }); } @@ -449,12 +449,12 @@ namespace Emby.Server.Implementations.IO } var newRefresher = new FileRefresher(path, _configurationManager, _libraryManager, _logger); - newRefresher.Completed += NewRefresher_Completed; + newRefresher.Completed += OnNewRefresherCompleted; _activeRefreshers.Add(newRefresher); } } - private void NewRefresher_Completed(object sender, EventArgs e) + private void OnNewRefresherCompleted(object sender, EventArgs e) { var refresher = (FileRefresher)sender; DisposeRefresher(refresher); @@ -481,6 +481,7 @@ namespace Emby.Server.Implementations.IO { lock (_activeRefreshers) { + refresher.Completed -= OnNewRefresherCompleted; refresher.Dispose(); _activeRefreshers.Remove(refresher); } @@ -492,6 +493,7 @@ namespace Emby.Server.Implementations.IO { foreach (var refresher in _activeRefreshers.ToList()) { + refresher.Completed -= OnNewRefresherCompleted; refresher.Dispose(); } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index eeee28842..777cd2cd4 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; using System.Globalization; @@ -23,6 +21,11 @@ namespace Emby.Server.Implementations.IO private readonly string _tempPath; private static readonly bool _isEnvironmentCaseInsensitive = OperatingSystem.IsWindows(); + /// <summary> + /// Initializes a new instance of the <see cref="ManagedFileSystem"/> class. + /// </summary> + /// <param name="logger">The <see cref="ILogger"/> instance to use.</param> + /// <param name="applicationPaths">The <see cref="IApplicationPaths"/> instance to use.</param> public ManagedFileSystem( ILogger<ManagedFileSystem> logger, IApplicationPaths applicationPaths) @@ -31,6 +34,7 @@ namespace Emby.Server.Implementations.IO _tempPath = applicationPaths.TempDirectory; } + /// <inheritdoc /> public virtual void AddShortcutHandler(IShortcutHandler handler) { _shortcutHandlers.Add(handler); @@ -72,6 +76,7 @@ namespace Emby.Server.Implementations.IO return handler?.Resolve(filename); } + /// <inheritdoc /> public virtual string MakeAbsolutePath(string folderPath, string filePath) { // path is actually a stream @@ -358,11 +363,13 @@ namespace Emby.Server.Implementations.IO return GetCreationTimeUtc(GetFileSystemInfo(path)); } + /// <inheritdoc /> public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info) { return info.CreationTimeUtc; } + /// <inheritdoc /> public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info) { return info.LastWriteTimeUtc; @@ -397,6 +404,7 @@ namespace Emby.Server.Implementations.IO return GetLastWriteTimeUtc(GetFileSystemInfo(path)); } + /// <inheritdoc /> public virtual void SetHidden(string path, bool isHidden) { if (!OperatingSystem.IsWindows()) @@ -421,6 +429,7 @@ namespace Emby.Server.Implementations.IO } } + /// <inheritdoc /> public virtual void SetAttributes(string path, bool isHidden, bool readOnly) { if (!OperatingSystem.IsWindows()) @@ -444,7 +453,7 @@ namespace Emby.Server.Implementations.IO if (readOnly) { - attributes = attributes | FileAttributes.ReadOnly; + attributes |= FileAttributes.ReadOnly; } else { @@ -453,7 +462,7 @@ namespace Emby.Server.Implementations.IO if (isHidden) { - attributes = attributes | FileAttributes.Hidden; + attributes |= FileAttributes.Hidden; } else { @@ -498,6 +507,7 @@ namespace Emby.Server.Implementations.IO File.Copy(temp1, file2, true); } + /// <inheritdoc /> public virtual bool ContainsSubPath(string parentPath, string path) { if (string.IsNullOrEmpty(parentPath)) @@ -515,6 +525,7 @@ namespace Emby.Server.Implementations.IO _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } + /// <inheritdoc /> public virtual string NormalizePath(string path) { if (string.IsNullOrEmpty(path)) @@ -530,6 +541,7 @@ namespace Emby.Server.Implementations.IO return Path.TrimEndingDirectorySeparator(path); } + /// <inheritdoc /> public virtual bool AreEqual(string path1, string path2) { if (path1 == null && path2 == null) @@ -548,6 +560,7 @@ namespace Emby.Server.Implementations.IO _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } + /// <inheritdoc /> public virtual string GetFileNameWithoutExtension(FileSystemMetadata info) { if (info.IsDirectory) @@ -558,11 +571,11 @@ namespace Emby.Server.Implementations.IO return Path.GetFileNameWithoutExtension(info.FullName); } + /// <inheritdoc /> public virtual bool IsPathFile(string path) { - // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\ - if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 && - !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) + if (path.Contains("://", StringComparison.OrdinalIgnoreCase) + && !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -570,17 +583,23 @@ namespace Emby.Server.Implementations.IO return true; } + /// <inheritdoc /> public virtual void DeleteFile(string path) { SetAttributes(path, false, false); File.Delete(path); } + /// <inheritdoc /> public virtual List<FileSystemMetadata> GetDrives() { // check for ready state to avoid waiting for drives to timeout // some drives on linux have no actual size or are used for other purposes - return DriveInfo.GetDrives().Where(d => d.IsReady && d.TotalSize != 0 && d.DriveType != DriveType.Ram) + return DriveInfo.GetDrives() + .Where( + d => (d.DriveType == DriveType.Fixed || d.DriveType == DriveType.Network || d.DriveType == DriveType.Removable) + && d.IsReady + && d.TotalSize != 0) .Select(d => new FileSystemMetadata { Name = d.Name, @@ -589,16 +608,19 @@ namespace Emby.Server.Implementations.IO }).ToList(); } + /// <inheritdoc /> public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false) { return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive))); } + /// <inheritdoc /> public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false) { return GetFiles(path, null, false, recursive); } + /// <inheritdoc /> public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string>? extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { var enumerationOptions = GetEnumerationOptions(recursive); @@ -629,6 +651,7 @@ namespace Emby.Server.Implementations.IO return ToMetadata(files); } + /// <inheritdoc /> public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false) { var directoryInfo = new DirectoryInfo(path); @@ -642,16 +665,19 @@ namespace Emby.Server.Implementations.IO return infos.Select(GetFileSystemMetadata); } + /// <inheritdoc /> public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false) { return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive)); } + /// <inheritdoc /> public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false) { return GetFilePaths(path, null, false, recursive); } + /// <inheritdoc /> public virtual IEnumerable<string> GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { var enumerationOptions = GetEnumerationOptions(recursive); @@ -682,6 +708,7 @@ namespace Emby.Server.Implementations.IO return files; } + /// <inheritdoc /> public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false) { return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive)); diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index bc5b4499f..29758a078 100644 --- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -1,8 +1,9 @@ using System; using System.IO; +using Emby.Naming.Audio; +using Emby.Naming.Common; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.IO; @@ -13,17 +14,17 @@ namespace Emby.Server.Implementations.Library /// </summary> public class CoreResolutionIgnoreRule : IResolverIgnoreRule { - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; private readonly IServerApplicationPaths _serverApplicationPaths; /// <summary> /// Initializes a new instance of the <see cref="CoreResolutionIgnoreRule"/> class. /// </summary> - /// <param name="libraryManager">The library manager.</param> + /// <param name="namingOptions">The naming options.</param> /// <param name="serverApplicationPaths">The server application paths.</param> - public CoreResolutionIgnoreRule(ILibraryManager libraryManager, IServerApplicationPaths serverApplicationPaths) + public CoreResolutionIgnoreRule(NamingOptions namingOptions, IServerApplicationPaths serverApplicationPaths) { - _libraryManager = libraryManager; + _namingOptions = namingOptions; _serverApplicationPaths = serverApplicationPaths; } @@ -78,7 +79,7 @@ namespace Emby.Server.Implementations.Library { // Don't resolve these into audio files if (Path.GetFileNameWithoutExtension(filename.AsSpan()).Equals(BaseItem.ThemeSongFileName, StringComparison.Ordinal) - && _libraryManager.IsAudioFile(filename)) + && AudioFileParser.IsAudioFile(filename, _namingOptions)) { return true; } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 1326f60fe..778b6225e 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -79,6 +79,7 @@ namespace Emby.Server.Implementations.Library private readonly IFileSystem _fileSystem; private readonly IItemRepository _itemRepository; private readonly IImageProcessor _imageProcessor; + private readonly NamingOptions _namingOptions; /// <summary> /// The _root folder sync lock. @@ -88,9 +89,6 @@ namespace Emby.Server.Implementations.Library private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24); - private NamingOptions _namingOptions; - private string[] _videoFileExtensions; - /// <summary> /// The _root folder. /// </summary> @@ -116,6 +114,7 @@ namespace Emby.Server.Implementations.Library /// <param name="itemRepository">The item repository.</param> /// <param name="imageProcessor">The image processor.</param> /// <param name="memoryCache">The memory cache.</param> + /// <param name="namingOptions">The naming options.</param> public LibraryManager( IServerApplicationHost appHost, ILogger<LibraryManager> logger, @@ -130,7 +129,8 @@ namespace Emby.Server.Implementations.Library IMediaEncoder mediaEncoder, IItemRepository itemRepository, IImageProcessor imageProcessor, - IMemoryCache memoryCache) + IMemoryCache memoryCache, + NamingOptions namingOptions) { _appHost = appHost; _logger = logger; @@ -146,6 +146,7 @@ namespace Emby.Server.Implementations.Library _itemRepository = itemRepository; _imageProcessor = imageProcessor; _memoryCache = memoryCache; + _namingOptions = namingOptions; _configurationManager.ConfigurationUpdated += ConfigurationUpdated; @@ -333,8 +334,7 @@ namespace Emby.Server.Implementations.Library { try { - var task = BaseItem.ChannelManager.DeleteItem(item); - Task.WaitAll(task); + BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult(); } catch (ArgumentException) { @@ -492,7 +492,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Error in {resolver} resolving {path}", resolver.GetType().Name, args.Path); + _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path); return null; } } @@ -799,7 +799,7 @@ namespace Emby.Server.Implementations.Library { var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; - _logger.LogDebug("Creating userRootPath at {path}", userRootPath); + _logger.LogDebug("Creating userRootPath at {Path}", userRootPath); Directory.CreateDirectory(userRootPath); var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder)); @@ -810,7 +810,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Error creating UserRootFolder {path}", newItemId); + _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId); } if (tmpItem == null) @@ -827,7 +827,7 @@ namespace Emby.Server.Implementations.Library } _userRootFolder = tmpItem; - _logger.LogDebug("Setting userRootFolder: {folder}", _userRootFolder); + _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder); } } } @@ -1213,7 +1213,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Error resolving shortcut file {file}", i); + _logger.LogError(ex, "Error resolving shortcut file {File}", i); return null; } }) @@ -1698,7 +1698,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.LogError("Intro resolver returned null for {path}.", info.Path); + _logger.LogError("Intro resolver returned null for {Path}.", info.Path); } else { @@ -1717,7 +1717,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Error resolving path {path}.", info.Path); + _logger.LogError(ex, "Error resolving path {Path}.", info.Path); } } else @@ -2502,16 +2502,6 @@ namespace Emby.Server.Implementations.Library } /// <inheritdoc /> - public bool IsVideoFile(string path) - { - return VideoResolver.IsVideoFile(path, GetNamingOptions()); - } - - /// <inheritdoc /> - public bool IsAudioFile(string path) - => AudioFileParser.IsAudioFile(path, GetNamingOptions()); - - /// <inheritdoc /> public int? GetSeasonNumberFromPath(string path) => SeasonPathParser.Parse(path, true, true).SeasonNumber; @@ -2526,7 +2516,7 @@ namespace Emby.Server.Implementations.Library isAbsoluteNaming = null; } - var resolver = new EpisodeResolver(GetNamingOptions()); + var resolver = new EpisodeResolver(_namingOptions); var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd; @@ -2683,21 +2673,9 @@ namespace Emby.Server.Implementations.Library return changed; } - /// <inheritdoc /> - public NamingOptions GetNamingOptions() - { - if (_namingOptions == null) - { - _namingOptions = new NamingOptions(); - _videoFileExtensions = _namingOptions.VideoFileExtensions; - } - - return _namingOptions; - } - public ItemLookupInfo ParseName(string name) { - var namingOptions = GetNamingOptions(); + var namingOptions = _namingOptions; var result = VideoResolver.CleanDateTime(name, namingOptions); return new ItemLookupInfo @@ -2709,11 +2687,11 @@ namespace Emby.Server.Implementations.Library public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService) { - var namingOptions = GetNamingOptions(); + var namingOptions = _namingOptions; var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory) .Where(i => string.Equals(i.Name, BaseItem.TrailersFolderName, StringComparison.OrdinalIgnoreCase)) - .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false)) + .SelectMany(i => _fileSystem.GetFiles(i.FullName, namingOptions.VideoFileExtensions, false, false)) .ToList(); var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions); @@ -2727,7 +2705,7 @@ namespace Emby.Server.Implementations.Library var resolvers = new IItemResolver[] { - new GenericVideoResolver<Trailer>(this) + new GenericVideoResolver<Trailer>(_namingOptions) }; return ResolvePaths(files, directoryService, null, new LibraryOptions(), null, resolvers) @@ -2753,11 +2731,11 @@ namespace Emby.Server.Implementations.Library public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService) { - var namingOptions = GetNamingOptions(); + var namingOptions = _namingOptions; var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory) .Where(i => BaseItem.AllExtrasTypesFolderNames.ContainsKey(i.Name ?? string.Empty)) - .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false)) + .SelectMany(i => _fileSystem.GetFiles(i.FullName, namingOptions.VideoFileExtensions, false, false)) .ToList(); var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions); @@ -2841,7 +2819,7 @@ namespace Emby.Server.Implementations.Library private void SetExtraTypeFromFilename(Video item) { - var resolver = new ExtraResolver(GetNamingOptions()); + var resolver = new ExtraResolver(_namingOptions); var result = resolver.GetExtraInfo(item.Path); diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 351fced34..972d4ebbb 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -45,6 +45,7 @@ namespace Emby.Server.Implementations.Library private readonly IMediaEncoder _mediaEncoder; private readonly ILocalizationManager _localizationManager; private readonly IApplicationPaths _appPaths; + private readonly IDirectoryService _directoryService; private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase); private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1); @@ -61,7 +62,8 @@ namespace Emby.Server.Implementations.Library ILogger<MediaSourceManager> logger, IFileSystem fileSystem, IUserDataManager userDataManager, - IMediaEncoder mediaEncoder) + IMediaEncoder mediaEncoder, + IDirectoryService directoryService) { _itemRepo = itemRepo; _userManager = userManager; @@ -72,6 +74,7 @@ namespace Emby.Server.Implementations.Library _mediaEncoder = mediaEncoder; _localizationManager = localizationManager; _appPaths = applicationPaths; + _directoryService = directoryService; } public void AddParts(IEnumerable<IMediaSourceProvider> providers) @@ -106,16 +109,6 @@ namespace Emby.Server.Implementations.Library return false; } - public List<MediaStream> GetMediaStreams(string mediaSourceId) - { - var list = GetMediaStreams(new MediaStreamQuery - { - ItemId = new Guid(mediaSourceId) - }); - - return GetMediaStreamsForItem(list); - } - public List<MediaStream> GetMediaStreams(Guid itemId) { var list = GetMediaStreams(new MediaStreamQuery @@ -161,7 +154,7 @@ namespace Emby.Server.Implementations.Library if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video)) { await item.RefreshMetadata( - new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + new MetadataRefreshOptions(_directoryService) { EnableRemoteContentProbe = true, MetadataRefreshMode = MetadataRefreshMode.FullRefresh @@ -212,6 +205,7 @@ namespace Emby.Server.Implementations.Library return SortMediaSources(list); } + /// <inheritdoc />> public MediaProtocol GetPathProtocol(string path) { if (path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase)) @@ -258,7 +252,7 @@ namespace Emby.Server.Implementations.Library { if (path != null) { - if (path.IndexOf(".m3u", StringComparison.OrdinalIgnoreCase) != -1) + if (path.Contains(".m3u", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -297,7 +291,7 @@ namespace Emby.Server.Implementations.Library catch (Exception ex) { _logger.LogError(ex, "Error getting media sources"); - return new List<MediaSourceInfo>(); + return Enumerable.Empty<MediaSourceInfo>(); } } @@ -494,14 +488,11 @@ namespace Emby.Server.Implementations.Library _liveStreamSemaphore.Release(); } - // TODO: Don't hardcode this - const bool isAudio = false; - try { if (mediaSource.MediaStreams.Any(i => i.Index != -1) || !mediaSource.SupportsProbing) { - AddMediaInfo(mediaSource, isAudio); + AddMediaInfo(mediaSource); } else { @@ -509,14 +500,14 @@ namespace Emby.Server.Implementations.Library string cacheKey = request.OpenToken; await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) - .AddMediaInfoWithProbe(mediaSource, isAudio, cacheKey, true, cancellationToken) + .AddMediaInfoWithProbe(mediaSource, false, cacheKey, true, cancellationToken) .ConfigureAwait(false); } } catch (Exception ex) { _logger.LogError(ex, "Error probing live tv stream"); - AddMediaInfo(mediaSource, isAudio); + AddMediaInfo(mediaSource); } // TODO: @bond Fix @@ -536,7 +527,7 @@ namespace Emby.Server.Implementations.Library return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDirectStreamProvider); } - private static void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio) + private static void AddMediaInfo(MediaSourceInfo mediaSource) { mediaSource.DefaultSubtitleStreamIndex = null; @@ -855,9 +846,7 @@ namespace Emby.Server.Implementations.Library return (provider, keyId); } - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> + /// <inheritdoc /> public void Dispose() { Dispose(true); diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index fd9747b4b..7a6aea9c1 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -6,7 +6,10 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Emby.Naming.Audio; using Emby.Naming.AudioBook; +using Emby.Naming.Common; +using Emby.Naming.Video; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -21,11 +24,11 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// </summary> public class AudioResolver : ItemResolver<MediaBrowser.Controller.Entities.Audio.Audio>, IMultiItemResolver { - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; - public AudioResolver(ILibraryManager libraryManager) + public AudioResolver(NamingOptions namingOptions) { - _libraryManager = libraryManager; + _namingOptions = namingOptions; } /// <summary> @@ -40,7 +43,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio string collectionType, IDirectoryService directoryService) { - var result = ResolveMultipleInternal(parent, files, collectionType, directoryService); + var result = ResolveMultipleInternal(parent, files, collectionType); if (result != null) { @@ -56,12 +59,11 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio private MultiItemResolverResult ResolveMultipleInternal( Folder parent, List<FileSystemMetadata> files, - string collectionType, - IDirectoryService directoryService) + string collectionType) { if (string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase)) { - return ResolveMultipleAudio<AudioBook>(parent, files, directoryService, false, collectionType, true); + return ResolveMultipleAudio(parent, files, true); } return null; @@ -87,14 +89,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return null; } - var files = args.FileSystemChildren - .Where(i => !_libraryManager.IgnoreFile(i, args.Parent)) - .ToList(); - - return FindAudio<AudioBook>(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false); + return FindAudioBook(args, false); } - if (_libraryManager.IsAudioFile(args.Path)) + if (AudioFileParser.IsAudioFile(args.Path, _namingOptions)) { var extension = Path.GetExtension(args.Path); @@ -107,7 +105,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var isMixedCollectionType = string.IsNullOrEmpty(collectionType); // For conflicting extensions, give priority to videos - if (isMixedCollectionType && _libraryManager.IsVideoFile(args.Path)) + if (isMixedCollectionType && VideoResolver.IsVideoFile(args.Path, _namingOptions)) { return null; } @@ -141,29 +139,23 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return null; } - private T FindAudio<T>(ItemResolveArgs args, string path, Folder parent, List<FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool parseName) - where T : MediaBrowser.Controller.Entities.Audio.Audio, new() + private AudioBook FindAudioBook(ItemResolveArgs args, bool parseName) { // TODO: Allow GetMultiDiscMovie in here - const bool supportsMultiVersion = false; + var result = ResolveMultipleAudio(args.Parent, args.GetActualFileSystemChildren(), parseName); - var result = ResolveMultipleAudio<T>(parent, fileSystemEntries, directoryService, supportsMultiVersion, collectionType, parseName) ?? - new MultiItemResolverResult(); - - if (result.Items.Count == 1) + if (result == null || result.Items.Count != 1 || result.Items[0] is not AudioBook item) { - // If we were supporting this we'd be checking filesFromOtherItems - var item = (T)result.Items[0]; - item.IsInMixedFolder = false; - item.Name = Path.GetFileName(item.ContainingFolderPath); - return item; + return null; } - return null; + // If we were supporting this we'd be checking filesFromOtherItems + item.IsInMixedFolder = false; + item.Name = Path.GetFileName(item.ContainingFolderPath); + return item; } - private MultiItemResolverResult ResolveMultipleAudio<T>(Folder parent, IEnumerable<FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, bool suppportMultiEditions, string collectionType, bool parseName) - where T : MediaBrowser.Controller.Entities.Audio.Audio, new() + private MultiItemResolverResult ResolveMultipleAudio(Folder parent, IEnumerable<FileSystemMetadata> fileSystemEntries, bool parseName) { var files = new List<FileSystemMetadata>(); var items = new List<BaseItem>(); @@ -176,15 +168,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { leftOver.Add(child); } - else if (!IsIgnored(child.Name)) + else { files.Add(child); } } - var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions(); - - var resolver = new AudioBookListResolver(namingOptions); + var resolver = new AudioBookListResolver(_namingOptions); var resolverResult = resolver.Resolve(files).ToList(); var result = new MultiItemResolverResult @@ -210,7 +200,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var firstMedia = resolvedItem.Files[0]; - var libraryItem = new T + var libraryItem = new AudioBook { Path = firstMedia.Path, IsInMixedFolder = isInMixedFolder, @@ -230,12 +220,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return result; } - private bool ContainsFile(List<AudioBookInfo> result, FileSystemMetadata file) + private static bool ContainsFile(IEnumerable<AudioBookInfo> result, FileSystemMetadata file) { return result.Any(i => ContainsFile(i, file)); } - private bool ContainsFile(AudioBookInfo result, FileSystemMetadata file) + private static bool ContainsFile(AudioBookInfo result, FileSystemMetadata file) { return result.Files.Any(i => ContainsFile(i, file)) || result.AlternateVersions.Any(i => ContainsFile(i, file)) || @@ -246,10 +236,5 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { return string.Equals(result.Path, file.FullName, StringComparison.OrdinalIgnoreCase); } - - private static bool IsIgnored(string filename) - { - return false; - } } } diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index 60720dd2f..a9819a364 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using Emby.Naming.Audio; +using Emby.Naming.Common; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -22,20 +23,17 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio public class MusicAlbumResolver : ItemResolver<MusicAlbum> { private readonly ILogger<MusicAlbumResolver> _logger; - private readonly IFileSystem _fileSystem; - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; /// <summary> /// Initializes a new instance of the <see cref="MusicAlbumResolver"/> class. /// </summary> /// <param name="logger">The logger.</param> - /// <param name="fileSystem">The file system.</param> - /// <param name="libraryManager">The library manager.</param> - public MusicAlbumResolver(ILogger<MusicAlbumResolver> logger, IFileSystem fileSystem, ILibraryManager libraryManager) + /// <param name="namingOptions">The naming options.</param> + public MusicAlbumResolver(ILogger<MusicAlbumResolver> logger, NamingOptions namingOptions) { _logger = logger; - _fileSystem = fileSystem; - _libraryManager = libraryManager; + _namingOptions = namingOptions; } /// <summary> @@ -87,7 +85,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// <returns><c>true</c> if the provided path points to a music album, <c>false</c> otherwise.</returns> public bool IsMusicAlbum(string path, IDirectoryService directoryService) { - return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, _libraryManager); + return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService); } /// <summary> @@ -101,7 +99,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio if (args.IsDirectory) { // if (args.Parent is MusicArtist) return true; // saves us from testing children twice - if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, _libraryManager)) + if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService)) { return true; } @@ -116,13 +114,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio private bool ContainsMusic( IEnumerable<FileSystemMetadata> list, bool allowSubfolders, - IDirectoryService directoryService, - ILogger<MusicAlbumResolver> logger, - IFileSystem fileSystem, - ILibraryManager libraryManager) + IDirectoryService directoryService) { // check for audio files before digging down into directories - var foundAudioFile = list.Any(fileSystemInfo => !fileSystemInfo.IsDirectory && libraryManager.IsAudioFile(fileSystemInfo.FullName)); + var foundAudioFile = list.Any(fileSystemInfo => !fileSystemInfo.IsDirectory && AudioFileParser.IsAudioFile(fileSystemInfo.FullName, _namingOptions)); if (foundAudioFile) { // at least one audio file exists @@ -137,21 +132,20 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var discSubfolderCount = 0; - var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions(); - var parser = new AlbumParser(namingOptions); + var parser = new AlbumParser(_namingOptions); var directories = list.Where(fileSystemInfo => fileSystemInfo.IsDirectory); var result = Parallel.ForEach(directories, (fileSystemInfo, state) => { var path = fileSystemInfo.FullName; - var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryManager); + var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService); if (hasMusic) { if (parser.IsMultiPart(path)) { - logger.LogDebug("Found multi-disc folder: " + path); + _logger.LogDebug("Found multi-disc folder: {Path}", path); Interlocked.Increment(ref discSubfolderCount); } else diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 3d2ae95d2..27e18be42 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -3,6 +3,7 @@ using System; using System.Linq; using System.Threading.Tasks; +using Emby.Naming.Common; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; @@ -19,27 +20,19 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio public class MusicArtistResolver : ItemResolver<MusicArtist> { private readonly ILogger<MusicAlbumResolver> _logger; - private readonly IFileSystem _fileSystem; - private readonly ILibraryManager _libraryManager; - private readonly IServerConfigurationManager _config; + private NamingOptions _namingOptions; /// <summary> /// Initializes a new instance of the <see cref="MusicArtistResolver"/> class. /// </summary> /// <param name="logger">The logger for the created <see cref="MusicAlbumResolver"/> instances.</param> - /// <param name="fileSystem">The file system.</param> - /// <param name="libraryManager">The library manager.</param> - /// <param name="config">The configuration manager.</param> + /// <param name="namingOptions">The naming options.</param> public MusicArtistResolver( ILogger<MusicAlbumResolver> logger, - IFileSystem fileSystem, - ILibraryManager libraryManager, - IServerConfigurationManager config) + NamingOptions namingOptions) { _logger = logger; - _fileSystem = fileSystem; - _libraryManager = libraryManager; - _config = config; + _namingOptions = namingOptions; } /// <summary> @@ -89,7 +82,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var directoryService = args.DirectoryService; - var albumResolver = new MusicAlbumResolver(_logger, _fileSystem, _libraryManager); + var albumResolver = new MusicAlbumResolver(_logger, _namingOptions); // If we contain an album assume we are an artist folder var directories = args.FileSystemChildren.Where(i => i.IsDirectory); diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 9ff99fa43..0ebf0e530 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -6,6 +6,7 @@ using System; using System.IO; using System.Linq; using DiscUtils.Udf; +using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -21,12 +22,12 @@ namespace Emby.Server.Implementations.Library.Resolvers public abstract class BaseVideoResolver<T> : MediaBrowser.Controller.Resolvers.ItemResolver<T> where T : Video, new() { - protected BaseVideoResolver(ILibraryManager libraryManager) + protected BaseVideoResolver(NamingOptions namingOptions) { - LibraryManager = libraryManager; + NamingOptions = namingOptions; } - protected ILibraryManager LibraryManager { get; } + protected NamingOptions NamingOptions { get; } /// <summary> /// Resolves the specified args. @@ -48,7 +49,7 @@ namespace Emby.Server.Implementations.Library.Resolvers protected virtual TVideoType ResolveVideo<TVideoType>(ItemResolveArgs args, bool parseName) where TVideoType : Video, new() { - var namingOptions = LibraryManager.GetNamingOptions(); + var namingOptions = NamingOptions; // If the path is a file check for a matching extensions if (args.IsDirectory) @@ -138,7 +139,7 @@ namespace Emby.Server.Implementations.Library.Resolvers return null; } - if (LibraryManager.IsVideoFile(args.Path) || videoInfo.IsStub) + if (VideoResolver.IsVideoFile(args.Path, NamingOptions) || videoInfo.IsStub) { var path = args.Path; @@ -267,7 +268,7 @@ namespace Emby.Server.Implementations.Library.Resolvers protected void Set3DFormat(Video video) { - var result = Format3DParser.Parse(video.Path, LibraryManager.GetNamingOptions()); + var result = Format3DParser.Parse(video.Path, NamingOptions); Set3DFormat(video, result.Is3D, result.Format3D); } diff --git a/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs index 9599faea4..72341d9db 100644 --- a/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/GenericVideoResolver.cs @@ -2,16 +2,16 @@ #pragma warning disable CS1591 +using Emby.Naming.Common; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; namespace Emby.Server.Implementations.Library.Resolvers { public class GenericVideoResolver<T> : BaseVideoResolver<T> where T : Video, new() { - public GenericVideoResolver(ILibraryManager libraryManager) - : base(libraryManager) + public GenericVideoResolver(NamingOptions namingOptions) + : base(namingOptions) { } } diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index f3b6ef0a2..732be0fe5 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Common; using Emby.Naming.Video; using Jellyfin.Extensions; using MediaBrowser.Controller.Drawing; @@ -25,6 +26,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies public class MovieResolver : BaseVideoResolver<Video>, IMultiItemResolver { private readonly IImageProcessor _imageProcessor; + private readonly StackResolver _stackResolver; private string[] _validCollectionTypes = new[] { @@ -38,12 +40,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// <summary> /// Initializes a new instance of the <see cref="MovieResolver"/> class. /// </summary> - /// <param name="libraryManager">The library manager.</param> /// <param name="imageProcessor">The image processor.</param> - public MovieResolver(ILibraryManager libraryManager, IImageProcessor imageProcessor) - : base(libraryManager) + /// <param name="namingOptions">The naming options.</param> + public MovieResolver(IImageProcessor imageProcessor, NamingOptions namingOptions) + : base(namingOptions) { _imageProcessor = imageProcessor; + _stackResolver = new StackResolver(NamingOptions); } /// <summary> @@ -89,9 +92,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return null; } - var files = args.FileSystemChildren - .Where(i => !LibraryManager.IgnoreFile(i, args.Parent)) - .ToList(); + var files = args.GetActualFileSystemChildren().ToList(); if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase)) { @@ -258,9 +259,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies } } - var namingOptions = LibraryManager.GetNamingOptions(); - - var resolverResult = VideoListResolver.Resolve(files, namingOptions, suppportMultiEditions).ToList(); + var resolverResult = VideoListResolver.Resolve(files, NamingOptions, suppportMultiEditions).ToList(); var result = new MultiItemResolverResult { @@ -438,7 +437,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies if (result.Items.Count == 1) { var videoPath = result.Items[0].Path; - var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, videoPath, i.Name)); + var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(videoPath, i.Name)); if (!hasPhotos) { @@ -511,9 +510,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return null; } - var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); - - var result = new StackResolver(namingOptions).ResolveDirectories(folderPaths).ToList(); + var result = _stackResolver.ResolveDirectories(folderPaths).ToList(); if (result.Count != 1) { diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 1c560e8a6..7dd0ab185 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -1,6 +1,7 @@ #nullable disable using System; +using Emby.Naming.Common; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -15,17 +16,17 @@ namespace Emby.Server.Implementations.Library.Resolvers public class PhotoAlbumResolver : GenericFolderResolver<PhotoAlbum> { private readonly IImageProcessor _imageProcessor; - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; /// <summary> /// Initializes a new instance of the <see cref="PhotoAlbumResolver"/> class. /// </summary> /// <param name="imageProcessor">The image processor.</param> - /// <param name="libraryManager">The library manager.</param> - public PhotoAlbumResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager) + /// <param name="namingOptions">The naming options.</param> + public PhotoAlbumResolver(IImageProcessor imageProcessor, NamingOptions namingOptions) { _imageProcessor = imageProcessor; - _libraryManager = libraryManager; + _namingOptions = namingOptions; } /// <inheritdoc /> @@ -73,7 +74,7 @@ namespace Emby.Server.Implementations.Library.Resolvers foreach (var siblingFile in files) { - if (PhotoResolver.IsOwnedByMedia(_libraryManager, siblingFile.FullName, filename)) + if (PhotoResolver.IsOwnedByMedia(_namingOptions, siblingFile.FullName, filename)) { ownedByMedia = true; break; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index 57bf40e9e..51d819303 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -6,6 +6,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Emby.Naming.Common; +using Emby.Naming.Video; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -16,7 +18,8 @@ namespace Emby.Server.Implementations.Library.Resolvers public class PhotoResolver : ItemResolver<Photo> { private readonly IImageProcessor _imageProcessor; - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; + private static readonly HashSet<string> _ignoreFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "folder", @@ -30,10 +33,11 @@ namespace Emby.Server.Implementations.Library.Resolvers "default" }; - public PhotoResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager) + + public PhotoResolver(IImageProcessor imageProcessor, NamingOptions namingOptions) { _imageProcessor = imageProcessor; - _libraryManager = libraryManager; + _namingOptions = namingOptions; } /// <summary> @@ -60,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Resolvers foreach (var file in files) { - if (IsOwnedByMedia(_libraryManager, file.FullName, filename)) + if (IsOwnedByMedia(_namingOptions, file.FullName, filename)) { return null; } @@ -77,17 +81,12 @@ namespace Emby.Server.Implementations.Library.Resolvers return null; } - internal static bool IsOwnedByMedia(ILibraryManager libraryManager, string file, string imageFilename) + internal static bool IsOwnedByMedia(NamingOptions namingOptions, string file, string imageFilename) { - if (libraryManager.IsVideoFile(file)) - { - return IsOwnedByResolvedMedia(libraryManager, file, imageFilename); - } - - return false; + return VideoResolver.IsVideoFile(file, namingOptions) && IsOwnedByResolvedMedia(file, imageFilename); } - internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, string file, string imageFilename) + internal static bool IsOwnedByResolvedMedia(string file, string imageFilename) => imageFilename.StartsWith(Path.GetFileNameWithoutExtension(file), StringComparison.OrdinalIgnoreCase); internal static bool IsImageFile(string path, IImageProcessor imageProcessor) diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index cf2d22f4d..f72da3617 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -2,6 +2,7 @@ using System; using System.Linq; +using Emby.Naming.Common; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -17,9 +18,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// <summary> /// Initializes a new instance of the <see cref="EpisodeResolver"/> class. /// </summary> - /// <param name="libraryManager">The library manager.</param> - public EpisodeResolver(ILibraryManager libraryManager) - : base(libraryManager) + /// <param name="namingOptions">The naming options.</param> + public EpisodeResolver(NamingOptions namingOptions) + : base(namingOptions) { } diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 063f67543..ea4851458 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -1,6 +1,7 @@ #nullable disable using System.Globalization; +using Emby.Naming.Common; using Emby.Naming.TV; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -14,22 +15,22 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// </summary> public class SeasonResolver : GenericFolderResolver<Season> { - private readonly ILibraryManager _libraryManager; private readonly ILocalizationManager _localization; private readonly ILogger<SeasonResolver> _logger; + private readonly NamingOptions _namingOptions; /// <summary> /// Initializes a new instance of the <see cref="SeasonResolver"/> class. /// </summary> - /// <param name="libraryManager">The library manager.</param> + /// <param name="namingOptions">The naming options.</param> /// <param name="localization">The localization.</param> /// <param name="logger">The logger.</param> public SeasonResolver( - ILibraryManager libraryManager, + NamingOptions namingOptions, ILocalizationManager localization, ILogger<SeasonResolver> logger) { - _libraryManager = libraryManager; + _namingOptions = namingOptions; _localization = localization; _logger = logger; } @@ -43,7 +44,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (args.Parent is Series series && args.IsDirectory) { - var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions(); + var namingOptions = _namingOptions; var path = args.Path; @@ -65,18 +66,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV var episodeInfo = resolver.Resolve(testPath, true); - if (episodeInfo != null) + if (episodeInfo?.EpisodeNumber != null && episodeInfo.SeasonNumber.HasValue) { - if (episodeInfo.EpisodeNumber.HasValue && episodeInfo.SeasonNumber.HasValue) - { - _logger.LogDebug( - "Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", - path, - episodeInfo.SeasonNumber.Value, - episodeInfo.EpisodeNumber.Value); - - return null; - } + _logger.LogDebug( + "Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", + path, + episodeInfo.SeasonNumber.Value, + episodeInfo.EpisodeNumber.Value); + + return null; } } diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index b7fbe01c5..4e15acd18 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -5,7 +5,12 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using Emby.Naming.Common; using Emby.Naming.TV; +using Emby.Naming.Video; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; @@ -21,17 +26,17 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV public class SeriesResolver : GenericFolderResolver<Series> { private readonly ILogger<SeriesResolver> _logger; - private readonly ILibraryManager _libraryManager; + private readonly NamingOptions _namingOptions; /// <summary> /// Initializes a new instance of the <see cref="SeriesResolver"/> class. /// </summary> /// <param name="logger">The logger.</param> - /// <param name="libraryManager">The library manager.</param> - public SeriesResolver(ILogger<SeriesResolver> logger, ILibraryManager libraryManager) + /// <param name="namingOptions">The naming options.</param> + public SeriesResolver(ILogger<SeriesResolver> logger, NamingOptions namingOptions) { _logger = logger; - _libraryManager = libraryManager; + _namingOptions = namingOptions; } /// <summary> @@ -54,16 +59,19 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } + var seriesInfo = Naming.TV.SeriesResolver.Resolve(_namingOptions, args.Path); + var collectionType = args.GetCollectionType(); if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)) { - var configuredContentType = _libraryManager.GetConfiguredContentType(args.Path); + // TODO refactor into separate class or something, this is copied from LibraryManager.GetConfiguredContentType + var configuredContentType = args.GetConfiguredContentType(); if (!string.Equals(configuredContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)) { return new Series { Path = args.Path, - Name = Path.GetFileName(args.Path) + Name = seriesInfo.Name }; } } @@ -80,7 +88,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return new Series { Path = args.Path, - Name = Path.GetFileName(args.Path) + Name = seriesInfo.Name }; } @@ -89,12 +97,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - if (IsSeriesFolder(args.Path, args.FileSystemChildren, _logger, _libraryManager, false)) + if (IsSeriesFolder(args.Path, args.FileSystemChildren, false)) { return new Series { Path = args.Path, - Name = Path.GetFileName(args.Path) + Name = seriesInfo.Name }; } } @@ -103,11 +111,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - public static bool IsSeriesFolder( + private bool IsSeriesFolder( string path, IEnumerable<FileSystemMetadata> fileSystemChildren, - ILogger<SeriesResolver> logger, - ILibraryManager libraryManager, bool isTvContentType) { foreach (var child in fileSystemChildren) @@ -116,21 +122,21 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (IsSeasonFolder(child.FullName, isTvContentType)) { - logger.LogDebug("{Path} is a series because of season folder {Dir}.", path, child.FullName); + _logger.LogDebug("{Path} is a series because of season folder {Dir}.", path, child.FullName); return true; } } else { string fullName = child.FullName; - if (libraryManager.IsVideoFile(fullName)) + if (VideoResolver.IsVideoFile(path, _namingOptions)) { if (isTvContentType) { return true; } - var namingOptions = ((LibraryManager)libraryManager).GetNamingOptions(); + var namingOptions = _namingOptions; var episodeResolver = new Naming.TV.EpisodeResolver(namingOptions); @@ -143,7 +149,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV } } - logger.LogDebug("{Path} is not a series folder.", path); + _logger.LogDebug("{Path} is not a series folder.", path); return false; } diff --git a/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs new file mode 100644 index 000000000..945b559ad --- /dev/null +++ b/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs @@ -0,0 +1,156 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using MediaBrowser.Controller.Collections; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Querying; +using Jellyfin.Data.Enums; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Entities; + +namespace Emby.Server.Implementations.Library.Validators +{ + /// <summary> + /// Class CollectionPostScanTask. + /// </summary> + public class CollectionPostScanTask : ILibraryPostScanTask + { + private readonly ILibraryManager _libraryManager; + private readonly ICollectionManager _collectionManager; + private readonly ILogger<CollectionPostScanTask> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="CollectionPostScanTask" /> class. + /// </summary> + /// <param name="libraryManager">The library manager.</param> + /// <param name="collectionManager">The collection manager.</param> + /// <param name="logger">The logger.</param> + public CollectionPostScanTask( + ILibraryManager libraryManager, + ICollectionManager collectionManager, + ILogger<CollectionPostScanTask> logger) + { + _libraryManager = libraryManager; + _collectionManager = collectionManager; + _logger = logger; + } + + /// <summary> + /// Runs the specified progress. + /// </summary> + /// <param name="progress">The progress.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>Task.</returns> + public async Task Run(IProgress<double> progress, CancellationToken cancellationToken) + { + var collectionNameMoviesMap = new Dictionary<string, HashSet<Guid>>(); + + foreach (var library in _libraryManager.RootFolder.Children) + { + if (!_libraryManager.GetLibraryOptions(library).AutomaticallyAddToCollection) + { + continue; + } + + var startIndex = 0; + var pagesize = 1000; + + while (true) + { + var movies = _libraryManager.GetItemList(new InternalItemsQuery + { + MediaTypes = new string[] { MediaType.Video }, + IncludeItemTypes = new[] { nameof(Movie) }, + IsVirtualItem = false, + OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }, + Parent = library, + StartIndex = startIndex, + Limit = pagesize, + Recursive = true + }); + + foreach (var m in movies) + { + if (m is Movie movie && !string.IsNullOrEmpty(movie.CollectionName)) + { + if (collectionNameMoviesMap.TryGetValue(movie.CollectionName, out var movieList)) + { + movieList.Add(movie.Id); + } + else + { + collectionNameMoviesMap[movie.CollectionName] = new HashSet<Guid> { movie.Id }; + } + } + } + + if (movies.Count < pagesize) + { + break; + } + + startIndex += pagesize; + } + } + + var numComplete = 0; + var count = collectionNameMoviesMap.Count; + + if (count == 0) + { + progress.Report(100); + return; + } + + var boxSets = _libraryManager.GetItemList(new InternalItemsQuery + { + IncludeItemTypes = new[] { nameof(BoxSet) }, + CollapseBoxSetItems = false, + Recursive = true + }); + + foreach (var (collectionName, movieIds) in collectionNameMoviesMap) + { + try + { + var boxSet = boxSets.FirstOrDefault(b => b?.Name == collectionName) as BoxSet; + if (boxSet == null) + { + // won't automatically create collection if only one movie in it + if (movieIds.Count >= 2) + { + boxSet = await _collectionManager.CreateCollectionAsync(new CollectionCreationOptions + { + Name = collectionName, + IsLocked = true + }); + + await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds); + } + } + else + { + await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds); + } + + numComplete++; + double percent = numComplete; + percent /= count; + percent *= 100; + + progress.Report(percent); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error refreshing {CollectionName} with {@MovieIds}", collectionName, movieIds); + } + } + + progress.Report(100); + } + } +} diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index 8739a9e1b..8a9a4b865 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError(ex, "Error validating IBN entry {person}", person); + _logger.LogError(ex, "Error validating IBN entry {Person}", person); } // Update progress diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 980b42729..644f9050d 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -957,7 +957,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public async Task<ILiveStream> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken) { - _logger.LogInformation("Streaming Channel " + channelId); + _logger.LogInformation("Streaming Channel {Id}", channelId); var result = string.IsNullOrEmpty(streamId) ? null : @@ -1027,7 +1027,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var stream = new MediaSourceInfo { - EncoderPath = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveRecordings/" + info.Id + "/stream", + EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream", EncoderProtocol = MediaProtocol.Http, Path = info.Path, Protocol = MediaProtocol.File, @@ -1308,16 +1308,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false); recordingStatus = RecordingStatus.Completed; - _logger.LogInformation("Recording completed: {recordPath}", recordPath); + _logger.LogInformation("Recording completed: {RecordPath}", recordPath); } catch (OperationCanceledException) { - _logger.LogInformation("Recording stopped: {recordPath}", recordPath); + _logger.LogInformation("Recording stopped: {RecordPath}", recordPath); recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { - _logger.LogError(ex, "Error recording to {recordPath}", recordPath); + _logger.LogError(ex, "Error recording to {RecordPath}", recordPath); recordingStatus = RecordingStatus.Error; } @@ -1404,7 +1404,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError(ex, "Error deleting 0-byte failed recording file {path}", path); + _logger.LogError(ex, "Error deleting 0-byte failed recording file {Path}", path); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 835028b92..a88a1fe84 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -87,8 +87,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV ErrorDialog = false }; - var commandLineLogMessage = processStartInfo.FileName + " " + processStartInfo.Arguments; - _logger.LogInformation(commandLineLogMessage); + _logger.LogInformation("{Filename} {Arguments}", processStartInfo.FileName, processStartInfo.Arguments); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); @@ -97,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _logFileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false); - await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false); + await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + processStartInfo.FileName + " " + processStartInfo.Arguments + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false); _process = new Process { @@ -188,7 +187,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV CultureInfo.InvariantCulture, "-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"", inputTempFile, - targetFile.Replace("\"", "\\\""), // Escape quotes in filename + targetFile.Replace("\"", "\\\"", StringComparison.Ordinal), // Escape quotes in filename videoArgs, GetAudioArgs(mediaSource), subtitleArgs, @@ -225,13 +224,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath); + _logger.LogInformation("Stopping ffmpeg recording process for {Path}", _targetPath); _process.StandardInput.WriteLine("q"); } catch (Exception ex) { - _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath); + _logger.LogError(ex, "Error stopping recording transcoding job for {Path}", _targetPath); } if (_hasExited) @@ -241,7 +240,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath); + _logger.LogInformation("Calling recording process.WaitForExit for {Path}", _targetPath); if (_process.WaitForExit(10000)) { @@ -250,7 +249,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath); + _logger.LogError(ex, "Error waiting for recording process to exit for {Path}", _targetPath); } if (_hasExited) @@ -260,13 +259,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath); + _logger.LogInformation("Killing ffmpeg recording process for {Path}", _targetPath); _process.Kill(); } catch (Exception ex) { - _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath); + _logger.LogError(ex, "Error killing recording transcoding job for {Path}", _targetPath); } } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 1f963e4a2..08aa0cfd7 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -11,6 +11,7 @@ using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; +using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; @@ -20,7 +21,6 @@ using Jellyfin.Extensions; using Jellyfin.Extensions.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; @@ -35,7 +35,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly ILogger<SchedulesDirect> _logger; private readonly IHttpClientFactory _httpClientFactory; private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1); - private readonly ICryptoProvider _cryptoProvider; private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>(); private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; @@ -43,12 +42,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings public SchedulesDirect( ILogger<SchedulesDirect> logger, - IHttpClientFactory httpClientFactory, - ICryptoProvider cryptoProvider) + IHttpClientFactory httpClientFactory) { _logger = logger; _httpClientFactory = httpClientFactory; - _cryptoProvider = cryptoProvider; } /// <inheritdoc /> @@ -169,12 +166,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings const double DesiredAspect = 2.0 / 3; - programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, true, DesiredAspect) ?? - GetProgramImage(ApiUrl, allImages, true, DesiredAspect); + programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect) ?? + GetProgramImage(ApiUrl, allImages, DesiredAspect); const double WideAspect = 16.0 / 9; - programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, true, WideAspect); + programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect); // Don't supply the same image twice if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal)) @@ -182,7 +179,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings programEntry.ThumbImage = null; } - programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, WideAspect); + programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect); // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ?? // GetProgramImage(ApiUrl, data, "Banner-L1", false) ?? @@ -403,7 +400,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return info; } - private string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, bool returnDefaultImage, double desiredAspect) + private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect) { var match = images .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) @@ -648,7 +645,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken cancellationToken) { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); - var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>()); + var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password)); // TODO: remove ToLower when Convert.ToHexString supports lowercase // Schedules Direct requires the hex to be lowercase string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant(); diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index 21e1409ac..598e3f88a 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -393,7 +393,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError(ex, "Error getting image info for {name}", info.Name); + _logger.LogError(ex, "Error getting image info for {Name}", info.Name); } return null; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index ea1a28fe8..a41b63f28 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1054,7 +1054,7 @@ namespace Emby.Server.Implementations.LiveTv { cancellationToken.ThrowIfCancellationRequested(); - _logger.LogDebug("Refreshing guide from {name}", service.Name); + _logger.LogDebug("Refreshing guide from {Name}", service.Name); try { @@ -1135,7 +1135,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name); + _logger.LogError(ex, "Error getting channel information for {Name}", channelInfo.Item2.Name); } numComplete++; @@ -1248,7 +1248,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name); + _logger.LogError(ex, "Error getting programs for channel {Name}", currentChannel.Name); } numComplete++; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index ecd28097d..4b7584af3 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.LiveTv // Dummy this up so that direct play checks can still run if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http) { - source.Path = _appHost.GetSmartApiUrl(string.Empty); + source.Path = _appHost.GetApiUrlForLocalAccess(); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index f9d151a81..9ab4cc628 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public async Task<bool> CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) { using var client = new TcpClient(); - client.Connect(remoteIp, HdHomeRunPort); + await client.ConnectAsync(remoteIp, HdHomeRunPort).ConfigureAwait(false); using var stream = client.GetStream(); return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 31445e1ec..9fba17ca3 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -82,7 +82,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath)); - Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host); + Logger.LogInformation("Opening HDHR UDP Live stream from {Host}", uri.Host); var remoteAddress = IPAddress.Parse(uri.Host); IPAddress localAddress = null; @@ -147,7 +147,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun // OpenedMediaSource.Path = tempFile; // OpenedMediaSource.ReadAtNativeFramerate = true; - MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts"; + MediaSource.Path = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts"; MediaSource.Protocol = MediaProtocol.Http; // OpenedMediaSource.SupportsDirectPlay = false; // OpenedMediaSource.SupportsDirectStream = true; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 506ef5548..708ff52d7 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -283,7 +283,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts // #EXTINF:0,84.0 - VOX Schweiz if (!string.IsNullOrWhiteSpace(nameInExtInf)) { - var numberIndex = nameInExtInf.IndexOf(' '); + var numberIndex = nameInExtInf.IndexOf(' ', StringComparison.Ordinal); if (numberIndex > 0) { var numberPart = nameInExtInf.Substring(0, numberIndex).Trim(new[] { ' ', '.' }); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 3b69e55b0..b1ce7b2b3 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts // OpenedMediaSource.Path = tempFile; // OpenedMediaSource.ReadAtNativeFramerate = true; - MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts"; + MediaSource.Path = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts"; MediaSource.Protocol = MediaProtocol.Http; // OpenedMediaSource.Path = TempFilePath; diff --git a/Emby.Server.Implementations/Localization/Core/as.json b/Emby.Server.Implementations/Localization/Core/as.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/as.json @@ -0,0 +1 @@ +{} diff --git a/Emby.Server.Implementations/Localization/Core/be.json b/Emby.Server.Implementations/Localization/Core/be.json new file mode 100644 index 000000000..56c4e7d39 --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/be.json @@ -0,0 +1,4 @@ +{ + "Sync": "Сінхранізацыя", + "Playlists": "Плэйліст" +} diff --git a/Emby.Server.Implementations/Localization/Core/ca.json b/Emby.Server.Implementations/Localization/Core/ca.json index db3c13d80..2dee5e327 100644 --- a/Emby.Server.Implementations/Localization/Core/ca.json +++ b/Emby.Server.Implementations/Localization/Core/ca.json @@ -25,7 +25,7 @@ "HeaderLiveTV": "TV en Directe", "HeaderNextUp": "A continuació", "HeaderRecordingGroups": "Grups d'Enregistrament", - "HomeVideos": "Vídeos domèstics", + "HomeVideos": "Vídeos Domèstics", "Inherit": "Hereta", "ItemAddedWithName": "{0} ha estat afegit a la biblioteca", "ItemRemovedWithName": "{0} ha estat eliminat de la biblioteca", @@ -39,7 +39,7 @@ "MixedContent": "Contingut barrejat", "Movies": "Pel·lícules", "Music": "Música", - "MusicVideos": "Vídeos musicals", + "MusicVideos": "Vídeos Musicals", "NameInstallFailed": "Instalació de {0} fallida", "NameSeasonNumber": "Temporada {0}", "NameSeasonUnknown": "Temporada Desconeguda", diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index 1ea378321..25f51db16 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -15,7 +15,7 @@ "Favorites": "Oblíbené", "Folders": "Složky", "Genres": "Žánry", - "HeaderAlbumArtists": "Album umělce", + "HeaderAlbumArtists": "Umělci alba", "HeaderContinueWatching": "Pokračovat ve sledování", "HeaderFavoriteAlbums": "Oblíbená alba", "HeaderFavoriteArtists": "Oblíbení interpreti", diff --git a/Emby.Server.Implementations/Localization/Core/en-GB.json b/Emby.Server.Implementations/Localization/Core/en-GB.json index 86ce9240e..add578376 100644 --- a/Emby.Server.Implementations/Localization/Core/en-GB.json +++ b/Emby.Server.Implementations/Localization/Core/en-GB.json @@ -15,7 +15,7 @@ "Favorites": "Favourites", "Folders": "Folders", "Genres": "Genres", - "HeaderAlbumArtists": "Artist's Album", + "HeaderAlbumArtists": "Album artists", "HeaderContinueWatching": "Continue Watching", "HeaderFavoriteAlbums": "Favourite Albums", "HeaderFavoriteArtists": "Favourite Artists", diff --git a/Emby.Server.Implementations/Localization/Core/en-US.json b/Emby.Server.Implementations/Localization/Core/en-US.json index ca127cdb8..568a8e447 100644 --- a/Emby.Server.Implementations/Localization/Core/en-US.json +++ b/Emby.Server.Implementations/Localization/Core/en-US.json @@ -12,12 +12,12 @@ "Default": "Default", "DeviceOfflineWithName": "{0} has disconnected", "DeviceOnlineWithName": "{0} is connected", - "FailedLoginAttemptWithUserName": "Failed login attempt from {0}", + "FailedLoginAttemptWithUserName": "Failed login try from {0}", "Favorites": "Favorites", "Folders": "Folders", "Forced": "Forced", "Genres": "Genres", - "HeaderAlbumArtists": "Artist's Album", + "HeaderAlbumArtists": "Album artists", "HeaderContinueWatching": "Continue Watching", "HeaderFavoriteAlbums": "Favorite Albums", "HeaderFavoriteArtists": "Favorite Artists", diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json index f92b5f673..3cadde0a0 100644 --- a/Emby.Server.Implementations/Localization/Core/eo.json +++ b/Emby.Server.Implementations/Localization/Core/eo.json @@ -1,5 +1,5 @@ { - "NotificationOptionInstallationFailed": "Instalada fiasko", + "NotificationOptionInstallationFailed": "Instalada malsukceso", "NotificationOptionAudioPlaybackStopped": "Ludado de sono haltis", "NotificationOptionAudioPlayback": "Ludado de sono lanĉis", "NameSeasonUnknown": "Sezono Nekonata", @@ -11,7 +11,7 @@ "ItemAddedWithName": "{0} aldonis al la plurmediteko", "HeaderLiveTV": "TV-etero", "HeaderContinueWatching": "Daŭrigi Spektadon", - "HeaderAlbumArtists": "Albumo de artisto", + "HeaderAlbumArtists": "Artistoj de albumo", "Folders": "Dosierujoj", "DeviceOnlineWithName": "{0} estas konektita", "Default": "Defaŭlte", @@ -48,17 +48,17 @@ "Shows": "Serioj", "HeaderFavoriteShows": "Favorataj Serioj", "TvShows": "TV-serioj", - "Favorites": "Favoratoj", + "Favorites": "Favorataj", "TaskCleanLogs": "Purigi Ĵurnalan Katalogon", - "TaskRefreshLibrary": "Skanu Plurmeditekon", + "TaskRefreshLibrary": "Skani Plurmeditekon", "ValueSpecialEpisodeName": "Speciala - {0}", - "TaskOptimizeDatabase": "Optimigi datumbazon", + "TaskOptimizeDatabase": "Optimumigi datenbazon", "TaskRefreshChannels": "Refreŝigi Kanalojn", "TaskUpdatePlugins": "Ĝisdatigi Kromprogramojn", "TaskRefreshPeople": "Refreŝigi Homojn", "TasksChannelsCategory": "Interretaj Kanaloj", "ProviderValue": "Provizanto: {0}", - "NotificationOptionPluginError": "Kromprograma malsukceso", + "NotificationOptionPluginError": "Kromprogramo malsukcesis", "MixedContent": "Miksita enhavo", "TasksApplicationCategory": "Aplikaĵo", "TasksMaintenanceCategory": "Prizorgado", @@ -75,7 +75,7 @@ "ServerNameNeedsToBeRestarted": "{0} devas esti relanĉita", "NotificationOptionVideoPlayback": "La videoludado lanĉis", "NotificationOptionServerRestartRequired": "Servila relanĉigo bezonata", - "TaskOptimizeDatabaseDescription": "Kompaktigas datenbazon kaj trunkas liberan lokon. Lanĉi ĉi tiun taskon post la teka skanado aŭ fari aliajn ŝanĝojn, kiuj implicas datenbazajn modifojn, povus plibonigi rendimenton.", + "TaskOptimizeDatabaseDescription": "Kompaktigas datenbazon kaj trunkas liberan lokon. Lanĉi ĉi tiun taskon post la plurmediteka skanado aŭ fari aliajn ŝanĝojn, kiuj implicas datenbazajn modifojn, povus plibonigi rendimenton.", "TaskUpdatePluginsDescription": "Elŝutas kaj instalas ĝisdatigojn por kromprogramojn, kiuj estas agorditaj por ĝisdatigi aŭtomate.", "TaskDownloadMissingSubtitlesDescription": "Serĉas en interreto mankantajn subtekstojn surbaze de metadatena agordaro.", "TaskRefreshPeopleDescription": "Ĝisdatigas metadatenojn por aktoroj kaj reĵisoroj en via plurmediteko.", @@ -102,9 +102,9 @@ "MessageApplicationUpdatedTo": "Jellyfin Server estis ĝisdatigita al {0}", "MessageApplicationUpdated": "Jellyfin Server estis ĝisdatigita", "TaskRefreshChannelsDescription": "Refreŝigas informon pri interretaj kanaloj.", - "TaskDownloadMissingSubtitles": "Elŝutu mankantajn subtekstojn", + "TaskDownloadMissingSubtitles": "Elŝuti mankantajn subtekstojn", "TaskCleanTranscode": "Malplenigi Transkodadan Katalogon", - "TaskRefreshChapterImages": "Eltiru Ĉapitro-Bildojn", + "TaskRefreshChapterImages": "Eltiri Ĉapitraj Bildojn", "TaskCleanCache": "Malplenigi Staplan Katalogon", "TaskCleanActivityLog": "Malplenigi Aktivecan Ĵurnalon", "PluginUpdatedWithName": "{0} estis ĝisdatigita", diff --git a/Emby.Server.Implementations/Localization/Core/es_419.json b/Emby.Server.Implementations/Localization/Core/es_419.json index a968c6dab..2ca736ad9 100644 --- a/Emby.Server.Implementations/Localization/Core/es_419.json +++ b/Emby.Server.Implementations/Localization/Core/es_419.json @@ -15,7 +15,7 @@ "HeaderFavoriteEpisodes": "Episodios favoritos", "HeaderFavoriteShows": "Programas favoritos", "HeaderContinueWatching": "Continuar viendo", - "HeaderAlbumArtists": "Artistas del álbum", + "HeaderAlbumArtists": "Artistas de álbum", "Genres": "Géneros", "Folders": "Carpetas", "Favorites": "Favoritos", @@ -29,7 +29,7 @@ "TaskRefreshChannelsDescription": "Actualiza la información de canales de Internet.", "TaskRefreshChannels": "Actualizar canales", "TaskCleanTranscodeDescription": "Elimina archivos transcodificados que tengan más de un día.", - "TaskCleanTranscode": "Limpiar directorio de transcodificado", + "TaskCleanTranscode": "Limpiar el directorio de transcodificaciones", "TaskUpdatePluginsDescription": "Descarga e instala actualizaciones para complementos que están configurados para actualizarse automáticamente.", "TaskUpdatePlugins": "Actualizar complementos", "TaskRefreshPeopleDescription": "Actualiza metadatos de actores y directores en tu biblioteca de medios.", @@ -105,7 +105,7 @@ "Inherit": "Heredar", "HomeVideos": "Videos caseros", "HeaderRecordingGroups": "Grupos de grabación", - "FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión desde {0}", + "FailedLoginAttemptWithUserName": "Intento de inicio de sesión fallido desde {0}", "DeviceOnlineWithName": "{0} está conectado", "DeviceOfflineWithName": "{0} se ha desconectado", "ChapterNameValue": "Capítulo {0}", @@ -114,10 +114,10 @@ "Application": "Aplicación", "AppDeviceValues": "App: {0}, Dispositivo: {1}", "TaskCleanActivityLogDescription": "Elimina las entradas del registro de actividad anteriores al periodo configurado.", - "TaskCleanActivityLog": "Limpiar Registro de Actividades", + "TaskCleanActivityLog": "Limpiar registro de actividades", "Undefined": "Sin definir", "Forced": "Forzado", - "Default": "Por Defecto", - "TaskOptimizeDatabaseDescription": "Compacta la base de datos y restaura el espacio libre. Ejecutar esta tarea después de actualizar las librerías o realizar otros cambios que impliquen modificar las bases de datos puede mejorar la performance.", - "TaskOptimizeDatabase": "Optimización de base de datos" + "Default": "Por defecto", + "TaskOptimizeDatabaseDescription": "Compacta la base de datos y libera espacio. Ejecutar esta tarea después de escanear la biblioteca o hacer otros cambios que impliquen modificaciones en la base de datos puede mejorar el rendimiento.", + "TaskOptimizeDatabase": "Optimizar base de datos" } diff --git a/Emby.Server.Implementations/Localization/Core/et.json b/Emby.Server.Implementations/Localization/Core/et.json index c3596ecf1..8db6a0b38 100644 --- a/Emby.Server.Implementations/Localization/Core/et.json +++ b/Emby.Server.Implementations/Localization/Core/et.json @@ -17,7 +17,7 @@ "TaskCleanLogsDescription": "Kustutab logifailid, mis on vanemad kui {0} päeva.", "TaskCleanLogs": "Puhasta logikataloog", "TaskRefreshLibraryDescription": "Otsib meedikogust uusi faile ja värskendab metaandmeid.", - "Collections": "Kollektsioonid", + "Collections": "Kogumikud", "TaskRefreshLibrary": "Skaneeri meediakogu", "TaskRefreshChapterImagesDescription": "Loob peatükkidega videote jaoks pisipildid.", "TaskRefreshChapterImages": "Eralda peatükipildid", @@ -32,9 +32,9 @@ "ValueSpecialEpisodeName": "Eriepisood - {0}", "ValueHasBeenAddedToLibrary": "{0} lisati meediakogusse", "UserStartedPlayingItemWithValues": "{0} taasesitab {1} serveris {2}", - "UserPasswordChangedWithName": "Kasutaja {0} parooli on muudetud", - "UserLockedOutWithName": "Kasutaja {0} on lukustatud", - "UserDeletedWithName": "Kasutaja {0} on kustutatud", + "UserPasswordChangedWithName": "Kasutaja {0} parool muudeti", + "UserLockedOutWithName": "Kasutaja {0} lukustati", + "UserDeletedWithName": "Kasutaja {0} kustutati", "UserCreatedWithName": "Kasutaja {0} on loodud", "ScheduledTaskStartedWithName": "{0} käivitati", "ProviderValue": "Allikas: {0}", @@ -54,9 +54,9 @@ "Plugin": "Plugin", "Playlists": "Pleilistid", "Photos": "Fotod", - "NotificationOptionVideoPlaybackStopped": "Video taasesitus on peatatud", + "NotificationOptionVideoPlaybackStopped": "Video taasesitus lõppes", "NotificationOptionVideoPlayback": "Video taasesitus algas", - "NotificationOptionUserLockedOut": "Kasutaja on lukustatud", + "NotificationOptionUserLockedOut": "Kasutaja lukustati", "NotificationOptionTaskFailed": "Ajastatud ülesanne nurjus", "NotificationOptionServerRestartRequired": "Vajalik on serveri taaskäivitamine", "NotificationOptionPluginUpdateInstalled": "Paigaldati plugina uuendus", @@ -66,7 +66,7 @@ "NotificationOptionNewLibraryContent": "Lisati uut sisu", "NotificationOptionInstallationFailed": "Paigaldamine nurjus", "NotificationOptionCameraImageUploaded": "Kaamera pilt on üles laaditud", - "NotificationOptionAudioPlaybackStopped": "Heli taasesitus peatati", + "NotificationOptionAudioPlaybackStopped": "Heli taasesitus lõppes", "NotificationOptionAudioPlayback": "Heli taasesitus algas", "NotificationOptionApplicationUpdateInstalled": "Rakenduse uuendus paigaldati", "NotificationOptionApplicationUpdateAvailable": "Rakenduse uuendus on saadaval", @@ -97,12 +97,12 @@ "HeaderFavoriteArtists": "Lemmikesitajad", "HeaderFavoriteAlbums": "Lemmikalbumid", "HeaderContinueWatching": "Jätka vaatamist", - "HeaderAlbumArtists": "Albumi esitaja", + "HeaderAlbumArtists": "Albumi esitajad", "Genres": "Žanrid", "Forced": "Sunnitud", "Folders": "Kaustad", "Favorites": "Lemmikud", - "FailedLoginAttemptWithUserName": "Ebaõnnestunud sisselogimiskatse kasutajalt {0}", + "FailedLoginAttemptWithUserName": "{0} - sisselogimine nurjus", "DeviceOnlineWithName": "{0} on ühendatud", "DeviceOfflineWithName": "{0} katkestas ühenduse", "Default": "Vaikimisi", @@ -114,5 +114,10 @@ "Artists": "Esitajad", "Application": "Rakendus", "AppDeviceValues": "Rakendus: {0}, seade: {1}", - "Albums": "Albumid" + "Albums": "Albumid", + "UserOfflineFromDevice": "{0} katkestas ühenduse seadmega {1}", + "SubtitleDownloadFailureFromForItem": "Subtiitrite allalaadimine {0} > {1} nurjus", + "UserPolicyUpdatedWithName": "Kasutaja {0} õigusi värskendati", + "UserStoppedPlayingItemWithValues": "{0} lõpetas {1} taasesituse seadmes {2}", + "UserOnlineFromDevice": "{0} on ühendatud seadmest {1}" } diff --git a/Emby.Server.Implementations/Localization/Core/fa.json b/Emby.Server.Implementations/Localization/Core/fa.json index 8ab657e5b..3d3b3533f 100644 --- a/Emby.Server.Implementations/Localization/Core/fa.json +++ b/Emby.Server.Implementations/Localization/Core/fa.json @@ -6,7 +6,7 @@ "AuthenticationSucceededWithUserName": "{0} با موفقیت تایید اعتبار شد", "Books": "کتابها", "CameraImageUploadedFrom": "یک عکس جدید از دوربین ارسال شده است {0}", - "Channels": "کانالها", + "Channels": "کانالها", "ChapterNameValue": "قسمت {0}", "Collections": "مجموعهها", "DeviceOfflineWithName": "ارتباط {0} قطع شد", @@ -37,7 +37,7 @@ "MessageNamedServerConfigurationUpdatedWithValue": "پکربندی بخش {0} سرور بروزرسانی شد", "MessageServerConfigurationUpdated": "پیکربندی سرور بروزرسانی شد", "MixedContent": "محتوای مخلوط", - "Movies": "فیلمها", + "Movies": "فیلم ها", "Music": "موسیقی", "MusicVideos": "موزیک ویدیوها", "NameInstallFailed": "{0} نصب با مشکل مواجه شد", diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 1265b6ef5..d60955d5f 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -15,7 +15,7 @@ "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes de l'album", + "HeaderAlbumArtists": "Artistes d'album", "HeaderContinueWatching": "Continuer à regarder", "HeaderFavoriteAlbums": "Albums favoris", "HeaderFavoriteArtists": "Artistes préférés", diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index 85ab1511a..acde84aaf 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -11,11 +11,11 @@ "Collections": "Gyűjtemények", "DeviceOfflineWithName": "{0} kijelentkezett", "DeviceOnlineWithName": "{0} belépett", - "FailedLoginAttemptWithUserName": "Sikertelen bejelentkezési kísérlet tőle: {0}", + "FailedLoginAttemptWithUserName": "Sikertelen bejelentkezési kísérlet innen: {0}", "Favorites": "Kedvencek", "Folders": "Könyvtárak", "Genres": "Műfajok", - "HeaderAlbumArtists": "Előadó albumai", + "HeaderAlbumArtists": "Album előadó(k)", "HeaderContinueWatching": "Megtekintés folytatása", "HeaderFavoriteAlbums": "Kedvenc albumok", "HeaderFavoriteArtists": "Kedvenc előadók", diff --git a/Emby.Server.Implementations/Localization/Core/id.json b/Emby.Server.Implementations/Localization/Core/id.json index ba3513870..37d59abd9 100644 --- a/Emby.Server.Implementations/Localization/Core/id.json +++ b/Emby.Server.Implementations/Localization/Core/id.json @@ -7,10 +7,10 @@ "MessageApplicationUpdated": "Jellyfin Server sudah diperbarui", "Latest": "Terbaru", "LabelIpAddressValue": "Alamat IP: {0}", - "ItemRemovedWithName": "{0} sudah dikeluarkan dari pustaka", + "ItemRemovedWithName": "{0} sudah dihapus dari pustaka", "ItemAddedWithName": "{0} telah dimasukkan ke dalam pustaka", - "Inherit": "Warisan", - "HomeVideos": "Video Rumah", + "Inherit": "Warisi", + "HomeVideos": "Video Rumahan", "HeaderRecordingGroups": "Grup Rekaman", "HeaderNextUp": "Selanjutnya", "HeaderLiveTV": "TV Live", @@ -73,7 +73,7 @@ "NotificationOptionCameraImageUploaded": "Gambar kamera terunggah", "NotificationOptionApplicationUpdateInstalled": "Pembaruan aplikasi terpasang", "NotificationOptionApplicationUpdateAvailable": "Pembaruan aplikasi tersedia", - "NewVersionIsAvailable": "Versi baru dari Jellyfin Server tersedia untuk diunduh.", + "NewVersionIsAvailable": "Versi baru dari Jellyfin Server sudah tersedia untuk diunduh.", "NameSeasonUnknown": "Musim tak diketahui", "NameSeasonNumber": "Musim {0}", "NameInstallFailed": "{0} penginstalan gagal", @@ -117,5 +117,7 @@ "TaskCleanActivityLog": "Bersihkan Log Aktivitas", "Undefined": "Tidak terdefinisi", "Forced": "Dipaksa", - "Default": "Bawaan" + "Default": "Bawaan", + "TaskOptimizeDatabaseDescription": "Rapihkan basis data dan membersihkan ruang kosong. Menjalankan tugas ini setelah memindai pustaka atau melakukan perubahan lain yang menyiratkan modifikasi basis data dapat meningkatkan kinerja.", + "TaskOptimizeDatabase": "Optimalkan basis data" } diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 5e28cf09f..4c4de4999 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -15,7 +15,7 @@ "Favorites": "Preferiti", "Folders": "Cartelle", "Genres": "Generi", - "HeaderAlbumArtists": "Artisti dell'Album", + "HeaderAlbumArtists": "Artisti dell'album", "HeaderContinueWatching": "Continua a guardare", "HeaderFavoriteAlbums": "Album Preferiti", "HeaderFavoriteArtists": "Artisti Preferiti", diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index d28564a7c..1b4a18deb 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -15,7 +15,7 @@ "Favorites": "Tañdaulylar", "Folders": "Qaltalar", "Genres": "Janrlar", - "HeaderAlbumArtists": "Oryndauşynyñ älbomy", + "HeaderAlbumArtists": "Älbom oryndauşylary", "HeaderContinueWatching": "Qaraudy jalğastyru", "HeaderFavoriteAlbums": "Tañdauly älbomdar", "HeaderFavoriteArtists": "Tañdauly oryndauşylar", diff --git a/Emby.Server.Implementations/Localization/Core/mk.json b/Emby.Server.Implementations/Localization/Core/mk.json index b780ef498..6baedcb2d 100644 --- a/Emby.Server.Implementations/Localization/Core/mk.json +++ b/Emby.Server.Implementations/Localization/Core/mk.json @@ -50,7 +50,7 @@ "HeaderFavoriteEpisodes": "Омилени Епизоди", "HeaderFavoriteArtists": "Омилени Изведувачи", "HeaderFavoriteAlbums": "Омилени Албуми", - "HeaderContinueWatching": "Продолжи со гледање", + "HeaderContinueWatching": "Продолжи со Гледање", "HeaderAlbumArtists": "Изведувачи од Албуми", "Genres": "Жанрови", "Folders": "Папки", diff --git a/Emby.Server.Implementations/Localization/Core/mn.json b/Emby.Server.Implementations/Localization/Core/mn.json new file mode 100644 index 000000000..7421d42fb --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/mn.json @@ -0,0 +1,14 @@ +{ + "Books": "Номууд", + "HeaderNextUp": "Дараах", + "HeaderContinueWatching": "Үргэлжлүүлэн үзэх", + "Songs": "Дуунууд", + "Playlists": "Тоглуулах жагсаалт", + "Movies": "Кино", + "Latest": "Сүүлийн үеийн", + "Genres": "Төрөл зүйл", + "Favorites": "Дуртай", + "Collections": "Багц", + "Artists": "Зураачуд", + "Albums": "Цомгууд" +} diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index b2dcf270c..4dcb99293 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -39,7 +39,7 @@ "MixedContent": "Kandungan campuran", "Movies": "Filem", "Music": "Muzik", - "MusicVideos": "Muzik video", + "MusicVideos": "", "NameInstallFailed": "{0} pemasangan gagal", "NameSeasonNumber": "Musim {0}", "NameSeasonUnknown": "Musim Tidak Diketahui", diff --git a/Emby.Server.Implementations/Localization/Core/pl.json b/Emby.Server.Implementations/Localization/Core/pl.json index e8a32a13e..4fa8d2bb4 100644 --- a/Emby.Server.Implementations/Localization/Core/pl.json +++ b/Emby.Server.Implementations/Localization/Core/pl.json @@ -15,7 +15,7 @@ "Favorites": "Ulubione", "Folders": "Foldery", "Genres": "Gatunki", - "HeaderAlbumArtists": "Album artysty", + "HeaderAlbumArtists": "Wykonawcy albumów", "HeaderContinueWatching": "Kontynuuj odtwarzanie", "HeaderFavoriteAlbums": "Ulubione albumy", "HeaderFavoriteArtists": "Ulubieni wykonawcy", @@ -47,7 +47,7 @@ "NotificationOptionApplicationUpdateAvailable": "Dostępna aktualizacja aplikacji", "NotificationOptionApplicationUpdateInstalled": "Zaktualizowano aplikację", "NotificationOptionAudioPlayback": "Rozpoczęto odtwarzanie muzyki", - "NotificationOptionAudioPlaybackStopped": "Odtwarzane dźwięku zatrzymane", + "NotificationOptionAudioPlaybackStopped": "Odtwarzanie dźwięku zatrzymane", "NotificationOptionCameraImageUploaded": "Przekazano obraz z urządzenia przenośnego", "NotificationOptionInstallationFailed": "Nieudana instalacja", "NotificationOptionNewLibraryContent": "Dodano nową zawartość", @@ -98,7 +98,7 @@ "TaskRefreshChannels": "Odśwież kanały", "TaskCleanTranscodeDescription": "Usuwa transkodowane pliki starsze niż 1 dzień.", "TaskCleanTranscode": "Wyczyść folder transkodowania", - "TaskUpdatePluginsDescription": "Pobiera i instaluje aktualizacje dla pluginów które są skonfigurowane do automatycznej aktualizacji.", + "TaskUpdatePluginsDescription": "Pobiera i instaluje aktualizacje dla pluginów, które są skonfigurowane do automatycznej aktualizacji.", "TaskUpdatePlugins": "Aktualizuj pluginy", "TaskRefreshPeopleDescription": "Odświeża metadane o aktorów i reżyserów w Twojej bibliotece mediów.", "TaskRefreshPeople": "Odśwież obsadę", diff --git a/Emby.Server.Implementations/Localization/Core/pr.json b/Emby.Server.Implementations/Localization/Core/pr.json index e3a3bfaf1..81aa996d9 100644 --- a/Emby.Server.Implementations/Localization/Core/pr.json +++ b/Emby.Server.Implementations/Localization/Core/pr.json @@ -1,5 +1,7 @@ { "Books": "Libros", "AuthenticationSucceededWithUserName": "{0} autentificado correctamente", - "Artists": "Artistas" + "Artists": "Artistas", + "Songs": "Shantees", + "Albums": "Ships" } diff --git a/Emby.Server.Implementations/Localization/Core/pt-PT.json b/Emby.Server.Implementations/Localization/Core/pt-PT.json index 8c41edf96..8870de168 100644 --- a/Emby.Server.Implementations/Localization/Core/pt-PT.json +++ b/Emby.Server.Implementations/Localization/Core/pt-PT.json @@ -15,7 +15,7 @@ "Favorites": "Favoritos", "Folders": "Pastas", "Genres": "Géneros", - "HeaderAlbumArtists": "Artistas do Álbum", + "HeaderAlbumArtists": "Álbum do Artista", "HeaderContinueWatching": "Continuar a Ver", "HeaderFavoriteAlbums": "Álbuns Favoritos", "HeaderFavoriteArtists": "Artistas Favoritos", @@ -39,7 +39,7 @@ "MixedContent": "Conteúdo Misto", "Movies": "Filmes", "Music": "Música", - "MusicVideos": "Videoclips", + "MusicVideos": "Videoclipes", "NameInstallFailed": "{0} falha na instalação", "NameSeasonNumber": "Temporada {0}", "NameSeasonUnknown": "Temporada Desconhecida", @@ -118,5 +118,7 @@ "TaskCleanActivityLog": "Limpar registo de atividade", "Undefined": "Indefinido", "Forced": "Forçado", - "Default": "Padrão" + "Default": "Padrão", + "TaskOptimizeDatabaseDescription": "Base de dados compacta e corta espaço livre. A execução desta tarefa depois de digitalizar a biblioteca ou de fazer outras alterações que impliquem modificações na base de dados pode melhorar o desempenho.", + "TaskOptimizeDatabase": "Otimizar base de dados" } diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index cd016b51b..2d7163275 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -31,7 +31,7 @@ "ItemRemovedWithName": "{0} - изъято из медиатеки", "LabelIpAddressValue": "IP-адрес: {0}", "LabelRunningTimeValue": "Длительность: {0}", - "Latest": "Последнее", + "Latest": "Крайнее", "MessageApplicationUpdated": "Jellyfin Server был обновлён", "MessageApplicationUpdatedTo": "Jellyfin Server был обновлён до {0}", "MessageNamedServerConfigurationUpdatedWithValue": "Конфигурация сервера (раздел {0}) была обновлена", @@ -119,6 +119,6 @@ "Undefined": "Не определено", "Forced": "Форсир-ые", "Default": "По умолчанию", - "TaskOptimizeDatabaseDescription": "Сжимает базу данных и обрезает свободное место. Выполнение этой задачи после сканирования библиотеки или внесения других изменений, предполагающих модификации базы данных, может повысить производительность.", + "TaskOptimizeDatabaseDescription": "Сжимает базу данных и вырезает свободные места. Выполнение этой задачи после сканирования библиотеки или внесения других изменений, предполагающих модификации базы данных, может повысить производительность.", "TaskOptimizeDatabase": "Оптимизировать базу данных" } diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index ad90bd813..37da7d5ab 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -39,7 +39,7 @@ "MixedContent": "Zmiešaný obsah", "Movies": "Filmy", "Music": "Hudba", - "MusicVideos": "Hudobné videá", + "MusicVideos": "Hudobné videoklipy", "NameInstallFailed": "Inštalácia {0} zlyhala", "NameSeasonNumber": "Séria {0}", "NameSeasonUnknown": "Neznáma séria", diff --git a/Emby.Server.Implementations/Localization/Core/sq.json b/Emby.Server.Implementations/Localization/Core/sq.json index 066ef5587..2766dab06 100644 --- a/Emby.Server.Implementations/Localization/Core/sq.json +++ b/Emby.Server.Implementations/Localization/Core/sq.json @@ -74,7 +74,7 @@ "NameSeasonUnknown": "Sezon i panjohur", "NameSeasonNumber": "Sezoni {0}", "NameInstallFailed": "Instalimi i {0} dështoi", - "MusicVideos": "Video muzikore", + "MusicVideos": "Video Muzikore", "Music": "Muzikë", "Movies": "Filmat", "MixedContent": "Përmbajtje e përzier", @@ -96,7 +96,7 @@ "HeaderFavoriteArtists": "Artistët e preferuar", "HeaderFavoriteAlbums": "Albumet e preferuar", "HeaderContinueWatching": "Vazhdo të shikosh", - "HeaderAlbumArtists": "Artistët e Albumeve", + "HeaderAlbumArtists": "Artistët e albumeve", "Genres": "Zhanret", "Folders": "Skedarët", "Favorites": "Të preferuarat", diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 15fb34186..2d6f3d53d 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -50,7 +50,7 @@ "NameSeasonUnknown": "Непозната сезона", "NameSeasonNumber": "Сезона {0}", "NameInstallFailed": "Инсталација {0} није успела", - "MusicVideos": "Музички спотови", + "MusicVideos": "Музички видео", "Music": "Музика", "Movies": "Филмови", "MixedContent": "Мешовит садржај", diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json index 6c772c6a2..1cef30b6c 100644 --- a/Emby.Server.Implementations/Localization/Core/sv.json +++ b/Emby.Server.Implementations/Localization/Core/sv.json @@ -15,7 +15,7 @@ "Favorites": "Favoriter", "Folders": "Mappar", "Genres": "Genrer", - "HeaderAlbumArtists": "Artistens album", + "HeaderAlbumArtists": "Albumsartister", "HeaderContinueWatching": "Fortsätt kolla", "HeaderFavoriteAlbums": "Favoritalbum", "HeaderFavoriteArtists": "Favoritartister", diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index d6e9aa8e5..e3a993625 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -85,7 +85,7 @@ "HeaderFavoriteArtists": "பிடித்த கலைஞர்கள்", "HeaderFavoriteAlbums": "பிடித்த ஆல்பங்கள்", "HeaderContinueWatching": "தொடர்ந்து பார்", - "HeaderAlbumArtists": "இசைக் கலைஞர்கள்", + "HeaderAlbumArtists": "கலைஞரின் ஆல்பம்", "Genres": "வகைகள்", "Favorites": "பிடித்தவை", "ChapterNameValue": "அத்தியாயம் {0}", diff --git a/Emby.Server.Implementations/Localization/Core/te.json b/Emby.Server.Implementations/Localization/Core/te.json new file mode 100644 index 000000000..a9a8ceae0 --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/te.json @@ -0,0 +1,23 @@ +{ + "ValueSpecialEpisodeName": "ప్రత్యేక - {0}", + "Sync": "సమకాలీకరించు", + "Songs": "పాటలు", + "Shows": "ప్రదర్శనలు", + "Playlists": "ప్లేజాబితాలు", + "Photos": "ఫోటోలు", + "MusicVideos": "మ్యూజిక్ వీడియోలు", + "Music": "సంగీతం", + "Movies": "సినిమాలు", + "HeaderContinueWatching": "చూడటం కొనసాగించండి", + "HeaderAlbumArtists": "ఆల్బమ్ కళాకారులు", + "Genres": "శైలులు", + "Forced": "బలవంతంగా", + "Folders": "ఫోల్డర్లు", + "Favorites": "ఇష్టమైనవి", + "Default": "డిఫాల్ట్", + "Collections": "సేకరణలు", + "Channels": "ఛానెల్లు", + "Books": "పుస్తకాలు", + "Artists": "కళాకారులు", + "Albums": "ఆల్బమ్లు" +} diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index e661299c4..8fadb88ac 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -8,7 +8,7 @@ "CameraImageUploadedFrom": "{0} 'den yeni bir kamera resmi yüklendi", "Channels": "Kanallar", "ChapterNameValue": "Bölüm {0}", - "Collections": "Koleksiyon", + "Collections": "Koleksiyonlar", "DeviceOfflineWithName": "{0} bağlantısı kesildi", "DeviceOnlineWithName": "{0} bağlı", "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu", diff --git a/Emby.Server.Implementations/Localization/Core/uk.json b/Emby.Server.Implementations/Localization/Core/uk.json index e99ed6f0b..1c7d73615 100644 --- a/Emby.Server.Implementations/Localization/Core/uk.json +++ b/Emby.Server.Implementations/Localization/Core/uk.json @@ -16,7 +16,7 @@ "HeaderFavoriteArtists": "Улюблені виконавці", "HeaderFavoriteAlbums": "Улюблені альбоми", "HeaderContinueWatching": "Продовжити перегляд", - "HeaderAlbumArtists": "Виконавці альбомів", + "HeaderAlbumArtists": "Виконавці альбому", "Genres": "Жанри", "Folders": "Каталоги", "Favorites": "Улюблені", diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index 33aa0eea0..b7ece8d5f 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -3,7 +3,7 @@ "Favorites": "Yêu Thích", "Folders": "Thư Mục", "Genres": "Thể Loại", - "HeaderAlbumArtists": "Album Nghệ sĩ", + "HeaderAlbumArtists": "Album nghệ sĩ", "HeaderContinueWatching": "Xem Tiếp", "HeaderLiveTV": "TV Trực Tiếp", "Movies": "Phim", @@ -62,11 +62,11 @@ "PluginUninstalledWithName": "{0} đã được gỡ bỏ", "PluginInstalledWithName": "{0} đã được cài đặt", "Plugin": "Plugin", - "NotificationOptionVideoPlaybackStopped": "Phát lại video đã dừng", + "NotificationOptionVideoPlaybackStopped": "Đã dừng phát lại video", "NotificationOptionVideoPlayback": "Đã bắt đầu phát lại video", "NotificationOptionUserLockedOut": "Người dùng bị khóa", "NotificationOptionTaskFailed": "Lỗi tác vụ đã lên lịch", - "NotificationOptionServerRestartRequired": "Yêu cầu khởi động lại Server", + "NotificationOptionServerRestartRequired": "Yêu cầu khởi động lại máy chủ", "NotificationOptionPluginUpdateInstalled": "Cập nhật Plugin đã được cài đặt", "NotificationOptionPluginUninstalled": "Đã gỡ bỏ Plugin", "NotificationOptionPluginInstalled": "Đã cài đặt Plugin", @@ -75,7 +75,7 @@ "NotificationOptionInstallationFailed": "Cài đặt thất bại", "NotificationOptionCameraImageUploaded": "Đã tải lên hình ảnh máy ảnh", "NotificationOptionAudioPlaybackStopped": "Phát lại âm thanh đã dừng", - "NotificationOptionAudioPlayback": "Phát lại âm thanh đã bắt đầu", + "NotificationOptionAudioPlayback": "Đã bắt đầu phát lại âm thanh", "NotificationOptionApplicationUpdateInstalled": "Bản cập nhật ứng dụng đã được cài đặt", "NotificationOptionApplicationUpdateAvailable": "Bản cập nhật ứng dụng hiện sẵn có", "NewVersionIsAvailable": "Một phiên bản mới của Jellyfin Server sẵn có để tải.", @@ -95,7 +95,7 @@ "ItemRemovedWithName": "{0} đã xóa khỏi thư viện", "ItemAddedWithName": "{0} được thêm vào thư viện", "Inherit": "Thừa hưởng", - "HomeVideos": "Video nhà", + "HomeVideos": "Video Nhà", "HeaderRecordingGroups": "Nhóm Ghi Video", "HeaderNextUp": "Tiếp Theo", "HeaderFavoriteSongs": "Bài Hát Yêu Thích", @@ -103,7 +103,7 @@ "HeaderFavoriteEpisodes": "Tập Phim Yêu Thích", "HeaderFavoriteArtists": "Nghệ Sĩ Yêu Thích", "HeaderFavoriteAlbums": "Album Ưa Thích", - "FailedLoginAttemptWithUserName": "Nỗ lực đăng nhập thất bại từ {0}", + "FailedLoginAttemptWithUserName": "Đăng nhập không thành công thử từ {0}", "DeviceOnlineWithName": "{0} đã kết nối", "DeviceOfflineWithName": "{0} đã ngắt kết nối", "ChapterNameValue": "Phân Cảnh {0}", diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index f9df62724..ac4eb644b 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -11,7 +11,7 @@ "Collections": "合集", "DeviceOfflineWithName": "{0} 已断开", "DeviceOnlineWithName": "{0} 已连接", - "FailedLoginAttemptWithUserName": "来自 {0} 的失败登入", + "FailedLoginAttemptWithUserName": "从 {0} 尝试登录失败", "Favorites": "我的最爱", "Folders": "文件夹", "Genres": "风格", diff --git a/Emby.Server.Implementations/Localization/Core/zu.json b/Emby.Server.Implementations/Localization/Core/zu.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/zu.json @@ -0,0 +1 @@ +{} diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 03919197e..9cdbbb6a3 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -372,43 +372,76 @@ namespace Emby.Server.Implementations.Localization /// <inheritdoc /> public IEnumerable<LocalizationOption> GetLocalizationOptions() { - yield return new LocalizationOption("Arabic", "ar"); - yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG"); - yield return new LocalizationOption("Catalan", "ca"); - yield return new LocalizationOption("Chinese Simplified", "zh-CN"); - yield return new LocalizationOption("Chinese Traditional", "zh-TW"); - yield return new LocalizationOption("Croatian", "hr"); - yield return new LocalizationOption("Czech", "cs"); - yield return new LocalizationOption("Danish", "da"); - yield return new LocalizationOption("Dutch", "nl"); + yield return new LocalizationOption("Afrikaans", "af"); + yield return new LocalizationOption("العربية", "ar"); + yield return new LocalizationOption("Беларуская", "be"); + yield return new LocalizationOption("Български", "bg-BG"); + yield return new LocalizationOption("বাংলা (বাংলাদেশ)", "bn"); + yield return new LocalizationOption("Català", "ca"); + yield return new LocalizationOption("Čeština", "cs"); + yield return new LocalizationOption("Cymraeg", "cy"); + yield return new LocalizationOption("Dansk", "da"); + yield return new LocalizationOption("Deutsch", "de"); yield return new LocalizationOption("English (United Kingdom)", "en-GB"); - yield return new LocalizationOption("English (United States)", "en-US"); - yield return new LocalizationOption("French", "fr"); - yield return new LocalizationOption("French (Canada)", "fr-CA"); - yield return new LocalizationOption("German", "de"); - yield return new LocalizationOption("Greek", "el"); - yield return new LocalizationOption("Hebrew", "he"); - yield return new LocalizationOption("Hungarian", "hu"); - yield return new LocalizationOption("Italian", "it"); - yield return new LocalizationOption("Kazakh", "kk"); - yield return new LocalizationOption("Korean", "ko"); - yield return new LocalizationOption("Lithuanian", "lt-LT"); - yield return new LocalizationOption("Malay", "ms"); - yield return new LocalizationOption("Norwegian Bokmål", "nb"); - yield return new LocalizationOption("Persian", "fa"); - yield return new LocalizationOption("Polish", "pl"); - yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR"); - yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT"); - yield return new LocalizationOption("Russian", "ru"); - yield return new LocalizationOption("Slovak", "sk"); - yield return new LocalizationOption("Slovenian (Slovenia)", "sl-SI"); - yield return new LocalizationOption("Spanish", "es"); - yield return new LocalizationOption("Spanish (Argentina)", "es-AR"); - yield return new LocalizationOption("Spanish (Mexico)", "es-MX"); - yield return new LocalizationOption("Swedish", "sv"); - yield return new LocalizationOption("Swiss German", "gsw"); - yield return new LocalizationOption("Turkish", "tr"); + yield return new LocalizationOption("English", "en-US"); + yield return new LocalizationOption("Ελληνικά", "el"); + yield return new LocalizationOption("Esperanto", "eo"); + yield return new LocalizationOption("Español", "es"); + yield return new LocalizationOption("Español americano", "es_419"); + yield return new LocalizationOption("Español (Argentina)", "es-AR"); + yield return new LocalizationOption("Español (Dominicana)", "es_DO"); + yield return new LocalizationOption("Español (México)", "es-MX"); + yield return new LocalizationOption("Eesti", "et"); + yield return new LocalizationOption("فارسی", "fa"); + yield return new LocalizationOption("Suomi", "fi"); + yield return new LocalizationOption("Filipino", "fil"); + yield return new LocalizationOption("Français", "fr"); + yield return new LocalizationOption("Français (Canada)", "fr-CA"); + yield return new LocalizationOption("Galego", "gl"); + yield return new LocalizationOption("Schwiizerdütsch", "gsw"); + yield return new LocalizationOption("עִבְרִית", "he"); + yield return new LocalizationOption("हिन्दी", "hi"); + yield return new LocalizationOption("Hrvatski", "hr"); + yield return new LocalizationOption("Magyar", "hu"); + yield return new LocalizationOption("Bahasa Indonesia", "id"); + yield return new LocalizationOption("Íslenska", "is"); + yield return new LocalizationOption("Italiano", "it"); + yield return new LocalizationOption("日本語", "ja"); + yield return new LocalizationOption("Qazaqşa", "kk"); + yield return new LocalizationOption("한국어", "ko"); + yield return new LocalizationOption("Lietuvių", "lt"); + yield return new LocalizationOption("Latviešu", "lv"); + yield return new LocalizationOption("Македонски", "mk"); + yield return new LocalizationOption("മലയാളം", "ml"); + yield return new LocalizationOption("मराठी", "mr"); + yield return new LocalizationOption("Bahasa Melayu", "ms"); + yield return new LocalizationOption("Norsk bokmål", "nb"); + yield return new LocalizationOption("नेपाली", "ne"); + yield return new LocalizationOption("Nederlands", "nl"); + yield return new LocalizationOption("Norsk nynorsk", "nn"); + yield return new LocalizationOption("ਪੰਜਾਬੀ", "pa"); + yield return new LocalizationOption("Polski", "pl"); + yield return new LocalizationOption("Pirate", "pr"); + yield return new LocalizationOption("Português", "pt"); + yield return new LocalizationOption("Português (Brasil)", "pt-BR"); + yield return new LocalizationOption("Português (Portugal)", "pt-PT"); + yield return new LocalizationOption("Românește", "ro"); + yield return new LocalizationOption("Русский", "ru"); + yield return new LocalizationOption("Slovenčina", "sk"); + yield return new LocalizationOption("Slovenščina", "sl-SI"); + yield return new LocalizationOption("Shqip", "sq"); + yield return new LocalizationOption("Српски", "sr"); + yield return new LocalizationOption("Svenska", "sv"); + yield return new LocalizationOption("தமிழ்", "ta"); + yield return new LocalizationOption("తెలుగు", "te"); + yield return new LocalizationOption("ภาษาไทย", "th"); + yield return new LocalizationOption("Türkçe", "tr"); + yield return new LocalizationOption("Українська", "uk"); + yield return new LocalizationOption("اُردُو", "ur_PK"); yield return new LocalizationOption("Tiếng Việt", "vi"); + yield return new LocalizationOption("汉语 (简化字)", "zh-CN"); + yield return new LocalizationOption("漢語 (繁体字)", "zh-TW"); + yield return new LocalizationOption("廣東話 (香港)", "zh-HK"); } } } diff --git a/Emby.Server.Implementations/Localization/countries.json b/Emby.Server.Implementations/Localization/countries.json index b08a3ae79..22ffc5e09 100644 --- a/Emby.Server.Implementations/Localization/countries.json +++ b/Emby.Server.Implementations/Localization/countries.json @@ -630,7 +630,7 @@ "TwoLetterISORegionName": "MD" }, { - "DisplayName": "Réunion", + "DisplayName": "Réunion", "Name": "RE", "ThreeLetterISORegionName": "REU", "TwoLetterISORegionName": "RE" diff --git a/Emby.Server.Implementations/Localization/iso6392.txt b/Emby.Server.Implementations/Localization/iso6392.txt index 488901822..66fba3330 100644 --- a/Emby.Server.Implementations/Localization/iso6392.txt +++ b/Emby.Server.Implementations/Localization/iso6392.txt @@ -349,7 +349,8 @@ pli||pi|Pali|pali pol||pl|Polish|polonais pon|||Pohnpeian|pohnpei por||pt|Portuguese|portugais -pob||pt-br|Portuguese (Brazil)|portugais +pop||pt-pt|Portuguese (Portugal)|portugais (pt-pt) +pob||pt-br|Portuguese (Brazil)|portugais (pt-br) pra|||Prakrit languages|prâkrit, langues pro|||Provençal, Old (to 1500)|provençal ancien (jusqu'à 1500) pus||ps|Pushto; Pashto|pachto diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index b07798fa4..9481e26f7 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -527,7 +527,7 @@ namespace Emby.Server.Implementations.Playlists var relativeUri = folderUri.MakeRelativeUri(fileAbsoluteUri); string relativePath = Uri.UnescapeDataString(relativeUri.ToString()); - if (fileAbsoluteUri.Scheme.Equals("file", StringComparison.CurrentCultureIgnoreCase)) + if (fileAbsoluteUri.Scheme.Equals("file", StringComparison.OrdinalIgnoreCase)) { relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index d52c0b2a1..d70a15dbc 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -126,7 +126,8 @@ namespace Emby.Server.Implementations.Plugins { assembly = Assembly.LoadFrom(file); - assembly.GetExportedTypes(); + // Load all required types to verify that the plugin will load + assembly.GetTypes(); } catch (FileLoadException ex) { @@ -134,7 +135,7 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.Malfunctioned); continue; } - catch (TypeLoadException ex) // Undocumented exception + catch (SystemException ex) when (ex is TypeLoadException or ReflectionTypeLoadException) // Undocumented exception { _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin.", file); ChangePluginState(plugin, PluginStatus.NotSupported); diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index f2cdfeb16..21a7f4f5f 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -638,7 +638,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - _logger.LogInformation(Name + ": Cancelling"); + _logger.LogInformation("{Name}: Cancelling", Name); token.Cancel(); } catch (Exception ex) @@ -652,16 +652,16 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - _logger.LogInformation(Name + ": Waiting on Task"); + _logger.LogInformation("{Name}: Waiting on Task", Name); var exited = task.Wait(2000); if (exited) { - _logger.LogInformation(Name + ": Task exited"); + _logger.LogInformation("{Name}: Task exited", Name); } else { - _logger.LogInformation(Name + ": Timed out waiting for task to stop"); + _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name); } } catch (Exception ex) @@ -674,7 +674,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - _logger.LogDebug(Name + ": Disposing CancellationToken"); + _logger.LogDebug("{Name}: Disposing CancellationToken", Name); token.Dispose(); } catch (Exception ex) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index a575b260c..0941902fc 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -161,11 +161,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError(ex, "Error deleting directory {path}", directory); + _logger.LogError(ex, "Error deleting directory {Path}", directory); } catch (IOException ex) { - _logger.LogError(ex, "Error deleting directory {path}", directory); + _logger.LogError(ex, "Error deleting directory {Path}", directory); } } } @@ -179,11 +179,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError(ex, "Error deleting file {path}", path); + _logger.LogError(ex, "Error deleting file {Path}", path); } catch (IOException ex) { - _logger.LogError(ex, "Error deleting file {path}", path); + _logger.LogError(ex, "Error deleting file {Path}", path); } } } diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs index b13fc7fc6..099d781cd 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs @@ -141,11 +141,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError(ex, "Error deleting directory {path}", directory); + _logger.LogError(ex, "Error deleting directory {Path}", directory); } catch (IOException ex) { - _logger.LogError(ex, "Error deleting directory {path}", directory); + _logger.LogError(ex, "Error deleting directory {Path}", directory); } } } @@ -159,11 +159,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError(ex, "Error deleting file {path}", path); + _logger.LogError(ex, "Error deleting file {Path}", path); } catch (IOException ex) { - _logger.LogError(ex, "Error deleting file {path}", path); + _logger.LogError(ex, "Error deleting file {Path}", path); } } } diff --git a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs index bd1966623..67a9fbd3b 100644 --- a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs +++ b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs @@ -26,7 +26,7 @@ namespace Emby.Server.Implementations.Sorting /// <returns>System.Int32.</returns> public int Compare(BaseItem? x, BaseItem? y) { - return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); + return string.Compare(GetValue(x), GetValue(y), StringComparison.OrdinalIgnoreCase); } /// <summary> diff --git a/Emby.Server.Implementations/Sorting/AlbumComparer.cs b/Emby.Server.Implementations/Sorting/AlbumComparer.cs index fe7dc84cb..4d09dda84 100644 --- a/Emby.Server.Implementations/Sorting/AlbumComparer.cs +++ b/Emby.Server.Implementations/Sorting/AlbumComparer.cs @@ -25,7 +25,7 @@ namespace Emby.Server.Implementations.Sorting /// <returns>System.Int32.</returns> public int Compare(BaseItem? x, BaseItem? y) { - return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); + return string.Compare(GetValue(x), GetValue(y), StringComparison.OrdinalIgnoreCase); } /// <summary> @@ -35,9 +35,7 @@ namespace Emby.Server.Implementations.Sorting /// <returns>System.String.</returns> private static string? GetValue(BaseItem? x) { - var audio = x as Audio; - - return audio == null ? string.Empty : audio.Album; + return x is Audio audio ? audio.Album : string.Empty; } } } diff --git a/Emby.Server.Implementations/Sorting/ArtistComparer.cs b/Emby.Server.Implementations/Sorting/ArtistComparer.cs index 7b7ba5753..a8bb55e2b 100644 --- a/Emby.Server.Implementations/Sorting/ArtistComparer.cs +++ b/Emby.Server.Implementations/Sorting/ArtistComparer.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.Sorting /// <inheritdoc /> public int Compare(BaseItem? x, BaseItem? y) { - return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); + return string.Compare(GetValue(x), GetValue(y), StringComparison.OrdinalIgnoreCase); } /// <summary> diff --git a/Emby.Server.Implementations/Sorting/NameComparer.cs b/Emby.Server.Implementations/Sorting/NameComparer.cs index 8f87717f4..c2875eeb9 100644 --- a/Emby.Server.Implementations/Sorting/NameComparer.cs +++ b/Emby.Server.Implementations/Sorting/NameComparer.cs @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Sorting throw new ArgumentNullException(nameof(y)); } - return string.Compare(x.Name, y.Name, StringComparison.CurrentCultureIgnoreCase); + return string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase); } } } diff --git a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs index 4123a59f8..0bd9600b9 100644 --- a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs +++ b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs @@ -25,7 +25,7 @@ namespace Emby.Server.Implementations.Sorting /// <returns>System.Int32.</returns> public int Compare(BaseItem x, BaseItem y) { - return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); + return string.Compare(GetValue(x), GetValue(y), StringComparison.OrdinalIgnoreCase); } private static string GetValue(BaseItem item) diff --git a/Emby.Server.Implementations/Sorting/SortNameComparer.cs b/Emby.Server.Implementations/Sorting/SortNameComparer.cs index fb97a0349..79be9a89a 100644 --- a/Emby.Server.Implementations/Sorting/SortNameComparer.cs +++ b/Emby.Server.Implementations/Sorting/SortNameComparer.cs @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Sorting throw new ArgumentNullException(nameof(y)); } - return string.Compare(x.SortName, y.SortName, StringComparison.CurrentCultureIgnoreCase); + return string.Compare(x.SortName, y.SortName, StringComparison.OrdinalIgnoreCase); } } } diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index bf51c3968..33e4e5651 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Udp _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } - private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken) + private async Task RespondToV2Message(EndPoint endpoint, CancellationToken cancellationToken) { string? localUrl = _config[AddressOverrideConfigKey]; if (string.IsNullOrEmpty(localUrl)) @@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Udp try { - await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false); + await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint, cancellationToken).ConfigureAwait(false); } catch (SocketException ex) { @@ -115,7 +115,7 @@ namespace Emby.Server.Implementations.Udp var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes); if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase)) { - await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false); + await RespondToV2Message(result.RemoteEndPoint, cancellationToken).ConfigureAwait(false); } } catch (SocketException ex) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 4a022c5db..ef95ebf94 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -571,7 +571,7 @@ namespace Emby.Server.Implementations.Updates ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version)); await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false); - _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version); + _logger.LogInformation("Plugin {Action}: {PluginName} {PluginVersion}", plugin == null ? "installed" : "updated", package.Name, package.Version); return plugin != null; } diff --git a/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs index 49b6689cd..58552d847 100644 --- a/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs +++ b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs @@ -1,4 +1,6 @@ -using System; +#pragma warning disable CA1813 // Avoid unsealed attributes + +using System; namespace Jellyfin.Api.Attributes { diff --git a/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs index 001f27409..244a29da4 100644 --- a/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs +++ b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs @@ -3,7 +3,7 @@ /// <summary> /// Produces file attribute of "image/*". /// </summary> - public class AcceptsImageFileAttribute : AcceptsFileAttribute + public sealed class AcceptsImageFileAttribute : AcceptsFileAttribute { private const string ContentType = "image/*"; diff --git a/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs b/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs index 2fdd1e489..af8727552 100644 --- a/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs +++ b/Jellyfin.Api/Attributes/HttpSubscribeAttribute.cs @@ -7,7 +7,7 @@ namespace Jellyfin.Api.Attributes /// <summary> /// Identifies an action that supports the HTTP GET method. /// </summary> - public class HttpSubscribeAttribute : HttpMethodAttribute + public sealed class HttpSubscribeAttribute : HttpMethodAttribute { private static readonly IEnumerable<string> _supportedMethods = new[] { "SUBSCRIBE" }; diff --git a/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs b/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs index d6d7e4563..1c0b70e71 100644 --- a/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs +++ b/Jellyfin.Api/Attributes/HttpUnsubscribeAttribute.cs @@ -7,7 +7,7 @@ namespace Jellyfin.Api.Attributes /// <summary> /// Identifies an action that supports the HTTP GET method. /// </summary> - public class HttpUnsubscribeAttribute : HttpMethodAttribute + public sealed class HttpUnsubscribeAttribute : HttpMethodAttribute { private static readonly IEnumerable<string> _supportedMethods = new[] { "UNSUBSCRIBE" }; diff --git a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs index 56c9772b6..514e7ce97 100644 --- a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs +++ b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs @@ -6,7 +6,7 @@ namespace Jellyfin.Api.Attributes /// Attribute to mark a parameter as obsolete. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] - public class ParameterObsoleteAttribute : Attribute + public sealed class ParameterObsoleteAttribute : Attribute { } } diff --git a/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs index 3adb700eb..9fc25f192 100644 --- a/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs +++ b/Jellyfin.Api/Attributes/ProducesAudioFileAttribute.cs @@ -3,7 +3,7 @@ /// <summary> /// Produces file attribute of "image/*". /// </summary> - public class ProducesAudioFileAttribute : ProducesFileAttribute + public sealed class ProducesAudioFileAttribute : ProducesFileAttribute { private const string ContentType = "audio/*"; diff --git a/Jellyfin.Api/Attributes/ProducesFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesFileAttribute.cs index 62a576ede..2bf77d729 100644 --- a/Jellyfin.Api/Attributes/ProducesFileAttribute.cs +++ b/Jellyfin.Api/Attributes/ProducesFileAttribute.cs @@ -1,4 +1,6 @@ -using System; +#pragma warning disable CA1813 // Avoid unsealed attributes + +using System; namespace Jellyfin.Api.Attributes { diff --git a/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs index e15813676..1e5b542e2 100644 --- a/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs +++ b/Jellyfin.Api/Attributes/ProducesImageFileAttribute.cs @@ -3,7 +3,7 @@ /// <summary> /// Produces file attribute of "image/*". /// </summary> - public class ProducesImageFileAttribute : ProducesFileAttribute + public sealed class ProducesImageFileAttribute : ProducesFileAttribute { private const string ContentType = "image/*"; diff --git a/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs index 5d928ab91..5b15cb1a5 100644 --- a/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs +++ b/Jellyfin.Api/Attributes/ProducesPlaylistFileAttribute.cs @@ -3,7 +3,7 @@ /// <summary> /// Produces file attribute of "image/*". /// </summary> - public class ProducesPlaylistFileAttribute : ProducesFileAttribute + public sealed class ProducesPlaylistFileAttribute : ProducesFileAttribute { private const string ContentType = "application/x-mpegURL"; diff --git a/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs b/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs index d8b2856dc..6857d45ec 100644 --- a/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs +++ b/Jellyfin.Api/Attributes/ProducesVideoFileAttribute.cs @@ -3,7 +3,7 @@ /// <summary> /// Produces file attribute of "video/*". /// </summary> - public class ProducesVideoFileAttribute : ProducesFileAttribute + public sealed class ProducesVideoFileAttribute : ProducesFileAttribute { private const string ContentType = "video/*"; diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index 369e846ae..bd3e7d9e3 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -45,6 +45,11 @@ namespace Jellyfin.Api.Auth try { var authorizationInfo = await _authService.Authenticate(Request).ConfigureAwait(false); + if (!authorizationInfo.HasToken) + { + return AuthenticateResult.NoResult(); + } + var role = UserRoles.User; if (authorizationInfo.IsApiKey || authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator)) { diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs new file mode 100644 index 000000000..98fd22430 --- /dev/null +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -0,0 +1,80 @@ +using System.Net.Mime; +using System.Threading.Tasks; +using Jellyfin.Api.Attributes; +using Jellyfin.Api.Constants; +using Jellyfin.Api.Helpers; +using Jellyfin.Api.Models.ClientLogDtos; +using MediaBrowser.Controller.ClientEvent; +using MediaBrowser.Controller.Configuration; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api.Controllers +{ + /// <summary> + /// Client log controller. + /// </summary> + [Authorize(Policy = Policies.DefaultAuthorization)] + public class ClientLogController : BaseJellyfinApiController + { + private const int MaxDocumentSize = 1_000_000; + private readonly IClientEventLogger _clientEventLogger; + private readonly IServerConfigurationManager _serverConfigurationManager; + + /// <summary> + /// Initializes a new instance of the <see cref="ClientLogController"/> class. + /// </summary> + /// <param name="clientEventLogger">Instance of the <see cref="IClientEventLogger"/> interface.</param> + /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> + public ClientLogController( + IClientEventLogger clientEventLogger, + IServerConfigurationManager serverConfigurationManager) + { + _clientEventLogger = clientEventLogger; + _serverConfigurationManager = serverConfigurationManager; + } + + /// <summary> + /// Upload a document. + /// </summary> + /// <response code="200">Document saved.</response> + /// <response code="403">Event logging disabled.</response> + /// <response code="413">Upload size too large.</response> + /// <returns>Create response.</returns> + [HttpPost("Document")] + [ProducesResponseType(typeof(ClientLogDocumentResponseDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] + [AcceptsFile(MediaTypeNames.Text.Plain)] + [RequestSizeLimit(MaxDocumentSize)] + public async Task<ActionResult<ClientLogDocumentResponseDto>> LogFile() + { + if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) + { + return Forbid(); + } + + if (Request.ContentLength > MaxDocumentSize) + { + // Manually validate to return proper status code. + return StatusCode(StatusCodes.Status413PayloadTooLarge, $"Payload must be less than {MaxDocumentSize:N0} bytes"); + } + + var (clientName, clientVersion) = GetRequestInformation(); + var fileName = await _clientEventLogger.WriteDocumentAsync(clientName, clientVersion, Request.Body) + .ConfigureAwait(false); + return Ok(new ClientLogDocumentResponseDto(fileName)); + } + + private (string ClientName, string ClientVersion) GetRequestInformation() + { + var clientName = ClaimHelpers.GetClient(HttpContext.User) ?? "unknown-client"; + var clientVersion = ClaimHelpers.GetIsApiKey(HttpContext.User) + ? "apikey" + : ClaimHelpers.GetVersion(HttpContext.User) ?? "unknown-version"; + + return (clientName, clientVersion); + } + } +} diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 2079476d0..0b2604640 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -8,7 +8,7 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; -using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Dto; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -143,21 +143,24 @@ namespace Jellyfin.Api.Controllers existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection; existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion) + && !string.IsNullOrEmpty(chromecastVersion) ? Enum.Parse<ChromecastVersion>(chromecastVersion, true) : ChromecastVersion.Stable; displayPreferences.CustomPrefs.Remove("chromecastVersion"); - existingDisplayPreferences.EnableNextVideoInfoOverlay = displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay) - ? bool.Parse(enableNextVideoInfoOverlay) - : true; + existingDisplayPreferences.EnableNextVideoInfoOverlay = !displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay) + || string.IsNullOrEmpty(enableNextVideoInfoOverlay) + || bool.Parse(enableNextVideoInfoOverlay); displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay"); existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength) + && !string.IsNullOrEmpty(skipBackLength) ? int.Parse(skipBackLength, CultureInfo.InvariantCulture) : 10000; displayPreferences.CustomPrefs.Remove("skipBackLength"); existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength) + && !string.IsNullOrEmpty(skipForwardLength) ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture) : 30000; displayPreferences.CustomPrefs.Remove("skipForwardLength"); @@ -196,7 +199,7 @@ namespace Jellyfin.Api.Controllers } var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client); - itemPrefs.SortBy = displayPreferences.SortBy; + itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName"; itemPrefs.SortOrder = displayPreferences.SortOrder; itemPrefs.RememberIndexing = displayPreferences.RememberIndexing; itemPrefs.RememberSorting = displayPreferences.RememberSorting; diff --git a/Jellyfin.Api/Controllers/DlnaController.cs b/Jellyfin.Api/Controllers/DlnaController.cs index 052a6aff2..35c3a3d92 100644 --- a/Jellyfin.Api/Controllers/DlnaController.cs +++ b/Jellyfin.Api/Controllers/DlnaController.cs @@ -126,7 +126,7 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - _dlnaManager.UpdateProfile(deviceProfile); + _dlnaManager.UpdateProfile(profileId, deviceProfile); return NoContent(); } } diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 42e82dd5b..caa3d2368 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1391,7 +1391,7 @@ namespace Jellyfin.Api.Controllers } else { - _logger.LogError("Invalid HLS segment container: " + segmentFormat); + _logger.LogError("Invalid HLS segment container: {SegmentFormat}", segmentFormat); } var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128 @@ -1794,7 +1794,7 @@ namespace Jellyfin.Api.Controllers return; } - _logger.LogDebug("Deleting partial HLS file {path}", path); + _logger.LogDebug("Deleting partial HLS file {Path}", path); try { @@ -1802,15 +1802,15 @@ namespace Jellyfin.Api.Controllers } catch (IOException ex) { - _logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); + _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path); var task = Task.Delay(100); - Task.WaitAll(task); + task.Wait(); DeleteFile(path, retryCount + 1); } catch (Exception ex) { - _logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); + _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path); } } diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 71caa0fe0..7325dca0a 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -64,7 +64,7 @@ namespace Jellyfin.Api.Controllers var transcodePath = _serverConfigurationManager.GetTranscodePath(); file = Path.GetFullPath(Path.Combine(transcodePath, file)); var fileDir = Path.GetDirectoryName(file); - if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath)) + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture)) { return BadRequest("Invalid segment."); } @@ -90,7 +90,7 @@ namespace Jellyfin.Api.Controllers var transcodePath = _serverConfigurationManager.GetTranscodePath(); file = Path.GetFullPath(Path.Combine(transcodePath, file)); var fileDir = Path.GetDirectoryName(file); - if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath) || Path.GetExtension(file) != ".m3u8") + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture) || Path.GetExtension(file) != ".m3u8") { return BadRequest("Invalid segment."); } @@ -144,7 +144,7 @@ namespace Jellyfin.Api.Controllers file = Path.GetFullPath(Path.Combine(transcodeFolderPath, file)); var fileDir = Path.GetDirectoryName(file); - if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath)) + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath, StringComparison.InvariantCulture)) { return BadRequest("Invalid segment."); } diff --git a/Jellyfin.Api/Controllers/ImageByNameController.cs b/Jellyfin.Api/Controllers/ImageByNameController.cs index 99ab7f232..89bbf22c9 100644 --- a/Jellyfin.Api/Controllers/ImageByNameController.cs +++ b/Jellyfin.Api/Controllers/ImageByNameController.cs @@ -82,7 +82,7 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - if (!path.StartsWith(_applicationPaths.GeneralPath)) + if (!path.StartsWith(_applicationPaths.GeneralPath, StringComparison.InvariantCulture)) { return BadRequest("Invalid image path."); } @@ -177,7 +177,7 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path)) { - if (!path.StartsWith(basePath)) + if (!path.StartsWith(basePath, StringComparison.InvariantCulture)) { return BadRequest("Invalid image path."); } @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path)) { - if (!path.StartsWith(basePath)) + if (!path.StartsWith(basePath, StringComparison.InvariantCulture)) { return BadRequest("Invalid image path."); } diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index 448510c06..8a6f9b8c7 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -5,8 +5,6 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Constants; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; @@ -30,7 +28,6 @@ namespace Jellyfin.Api.Controllers public class ItemLookupController : BaseJellyfinApiController { private readonly IProviderManager _providerManager; - private readonly IServerApplicationPaths _appPaths; private readonly IFileSystem _fileSystem; private readonly ILibraryManager _libraryManager; private readonly ILogger<ItemLookupController> _logger; @@ -39,19 +36,16 @@ namespace Jellyfin.Api.Controllers /// Initializes a new instance of the <see cref="ItemLookupController"/> class. /// </summary> /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param> - /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> /// <param name="logger">Instance of the <see cref="ILogger{ItemLookupController}"/> interface.</param> public ItemLookupController( IProviderManager providerManager, - IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILogger<ItemLookupController> logger) { _providerManager = providerManager; - _appPaths = serverConfigurationManager.ApplicationPaths; _fileSystem = fileSystem; _libraryManager = libraryManager; _logger = logger; diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index f0d44e5cc..45a36c8fe 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; @@ -33,6 +34,7 @@ namespace Jellyfin.Api.Controllers private readonly ILocalizationManager _localization; private readonly IDtoService _dtoService; private readonly ILogger<ItemsController> _logger; + private readonly ISessionManager _sessionManager; /// <summary> /// Initializes a new instance of the <see cref="ItemsController"/> class. @@ -42,18 +44,21 @@ namespace Jellyfin.Api.Controllers /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param> /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param> /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> + /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param> public ItemsController( IUserManager userManager, ILibraryManager libraryManager, ILocalizationManager localization, IDtoService dtoService, - ILogger<ItemsController> logger) + ILogger<ItemsController> logger, + ISessionManager sessionManager) { _userManager = userManager; _libraryManager = libraryManager; _localization = localization; _dtoService = dtoService; _logger = logger; + _sessionManager = sessionManager; } /// <summary> @@ -763,6 +768,7 @@ namespace Jellyfin.Api.Controllers /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param> /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param> /// <param name="enableImages">Optional. Include image information in output.</param> + /// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param> /// <response code="200">Items returned.</response> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns> [HttpGet("Users/{userId}/Items/Resume")] @@ -781,7 +787,8 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool enableTotalRecordCount = true, - [FromQuery] bool? enableImages = true) + [FromQuery] bool? enableImages = true, + [FromQuery] bool excludeActiveSessions = false) { var user = _userManager.GetUserById(userId); var parentIdGuid = parentId ?? Guid.Empty; @@ -801,6 +808,15 @@ namespace Jellyfin.Api.Controllers .ToArray(); } + var excludeItemIds = Array.Empty<Guid>(); + if (excludeActiveSessions) + { + excludeItemIds = _sessionManager.Sessions + .Where(s => s.UserId == userId && s.NowPlayingItem != null) + .Select(s => s.NowPlayingItem.Id) + .ToArray(); + } + var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user) { OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) }, @@ -817,7 +833,8 @@ namespace Jellyfin.Api.Controllers AncestorIds = ancestorIds, IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), - SearchTerm = searchTerm + SearchTerm = searchTerm, + ExcludeItemIds = excludeItemIds }); var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user); diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index b98307f87..cb4894d77 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -26,7 +26,6 @@ namespace Jellyfin.Api.Controllers private readonly ILibraryManager _libraryManager; private readonly IDtoService _dtoService; private readonly IUserManager _userManager; - private readonly IUserDataManager _userDataManager; /// <summary> /// Initializes a new instance of the <see cref="PersonsController"/> class. @@ -34,17 +33,14 @@ namespace Jellyfin.Api.Controllers /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param> /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> - /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param> public PersonsController( ILibraryManager libraryManager, IDtoService dtoService, - IUserManager userManager, - IUserDataManager userDataManager) + IUserManager userManager) { _libraryManager = libraryManager; _dtoService = dtoService; _userManager = userManager; - _userDataManager = userDataManager; } /// <summary> diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 0ae6109bc..0778ea3fc 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -28,7 +28,6 @@ namespace Jellyfin.Api.Controllers { private readonly IInstallationManager _installationManager; private readonly IPluginManager _pluginManager; - private readonly IConfigurationManager _config; private readonly JsonSerializerOptions _serializerOptions; /// <summary> @@ -36,16 +35,13 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param> /// <param name="pluginManager">Instance of the <see cref="IPluginManager"/> interface.</param> - /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param> public PluginsController( IInstallationManager installationManager, - IPluginManager pluginManager, - IConfigurationManager config) + IPluginManager pluginManager) { _installationManager = installationManager; _pluginManager = pluginManager; _serializerOptions = JsonDefaults.Options; - _config = config; } /// <summary> diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index 35921ede8..773cff1ac 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -30,7 +30,6 @@ namespace Jellyfin.Api.Controllers { private readonly IProviderManager _providerManager; private readonly IServerApplicationPaths _applicationPaths; - private readonly IHttpClientFactory _httpClientFactory; private readonly ILibraryManager _libraryManager; /// <summary> @@ -38,17 +37,14 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param> /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param> - /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param> /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> public RemoteImageController( IProviderManager providerManager, IServerApplicationPaths applicationPaths, - IHttpClientFactory httpClientFactory, ILibraryManager libraryManager) { _providerManager = providerManager; _applicationPaths = applicationPaths; - _httpClientFactory = httpClientFactory; _libraryManager = libraryManager; } diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index db8307f28..16acedcf3 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -528,7 +528,7 @@ namespace Jellyfin.Api.Controllers if (fontFile != null && fileSize != null && fileSize > 0) { - _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); + _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize); return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName)); } else diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 904738bb4..2ff85fd2a 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -212,10 +212,13 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="IEnumerable{WakeOnLanInfo}"/> with the WakeOnLan infos.</returns> [HttpGet("WakeOnLanInfo")] [Authorize(Policy = Policies.DefaultAuthorization)] + [Obsolete("This endpoint is obsolete.")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<IEnumerable<WakeOnLanInfo>> GetWakeOnLanInfo() { - var result = _appHost.GetWakeOnLanInfo(); + var result = _network.GetMacAddresses() + .Select(i => new WakeOnLanInfo(i)) + .ToList(); return Ok(result); } } diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index e1cbc6f33..3c079a71d 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -451,7 +451,7 @@ namespace Jellyfin.Api.Controllers if (@static.HasValue && @static.Value && state.DirectStreamProvider != null) { - StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager); + StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, state.Request.StartTimeTicks, Request, _dlnaManager); var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId); if (liveStreamInfo == null) @@ -467,7 +467,7 @@ namespace Jellyfin.Api.Controllers // Static remote stream if (@static.HasValue && @static.Value && state.InputProtocol == MediaProtocol.Http) { - StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager); + StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, state.Request.StartTimeTicks, Request, _dlnaManager); var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); return await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, HttpContext).ConfigureAwait(false); @@ -484,7 +484,7 @@ namespace Jellyfin.Api.Controllers var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive); var isTranscodeCached = outputPathExists && transcodingJob != null; - StreamingHelpers.AddDlnaHeaders(state, Response.Headers, (@static.HasValue && @static.Value) || isTranscodeCached, startTimeTicks, Request, _dlnaManager); + StreamingHelpers.AddDlnaHeaders(state, Response.Headers, (@static.HasValue && @static.Value) || isTranscodeCached, state.Request.StartTimeTicks, Request, _dlnaManager); // Static stream if (@static.HasValue && @static.Value) diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs index a911a3324..76fb27bcc 100644 --- a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs +++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs @@ -19,7 +19,7 @@ namespace Jellyfin.Api.Helpers // If any this null throw an exception. if (source == null || destination == null) { - throw new Exception("Source or/and Destination Objects are null"); + throw new ArgumentException("Source or/and Destination Objects are null"); } // Getting the Types of the objects. diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs index 61e18220a..3fa07720a 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs @@ -17,7 +17,6 @@ namespace Jellyfin.Api.Helpers private readonly TranscodingJobDto? _job; private readonly TranscodingJobHelper? _transcodingJobHelper; private readonly int _timeoutMs; - private int _bytesWritten; private bool _disposed; /// <summary> @@ -71,53 +70,58 @@ namespace Jellyfin.Api.Helpers /// <inheritdoc /> public override void Flush() { - _stream.Flush(); + // Not supported } /// <inheritdoc /> public override int Read(byte[] buffer, int offset, int count) + => Read(buffer.AsSpan(offset, count)); + + /// <inheritdoc /> + public override int Read(Span<byte> buffer) { - return _stream.Read(buffer, offset, count); + int totalBytesRead = 0; + var stopwatch = Stopwatch.StartNew(); + + while (KeepReading(stopwatch.ElapsedMilliseconds)) + { + totalBytesRead += _stream.Read(buffer); + if (totalBytesRead > 0) + { + break; + } + + Thread.Sleep(50); + } + + UpdateBytesWritten(totalBytesRead); + + return totalBytesRead; } /// <inheritdoc /> public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false); + + /// <inheritdoc /> + public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { int totalBytesRead = 0; - int remainingBytesToRead = count; var stopwatch = Stopwatch.StartNew(); - int newOffset = offset; - while (remainingBytesToRead > 0) + while (KeepReading(stopwatch.ElapsedMilliseconds)) { - cancellationToken.ThrowIfCancellationRequested(); - int bytesRead = await _stream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false); - - remainingBytesToRead -= bytesRead; - newOffset += bytesRead; - - if (bytesRead > 0) + totalBytesRead += await _stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + if (totalBytesRead > 0) { - _bytesWritten += bytesRead; - totalBytesRead += bytesRead; - - if (_job != null) - { - _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten); - } + break; } - else - { - // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely - if (_job?.HasExited ?? stopwatch.ElapsedMilliseconds > _timeoutMs) - { - break; - } - await Task.Delay(50, cancellationToken).ConfigureAwait(false); - } + await Task.Delay(50, cancellationToken).ConfigureAwait(false); } + UpdateBytesWritten(totalBytesRead); + return totalBytesRead; } @@ -159,5 +163,19 @@ namespace Jellyfin.Api.Helpers base.Dispose(disposing); } } + + private void UpdateBytesWritten(int totalBytesRead) + { + if (_job != null) + { + _job.BytesDownloaded += totalBytesRead; + } + } + + private bool KeepReading(long elapsed) + { + // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely + return !_job?.HasExited ?? elapsed < _timeoutMs; + } } } diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 4fc791665..1b8f24c27 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -148,7 +148,7 @@ namespace Jellyfin.Api.Helpers mediaSource = string.IsNullOrEmpty(streamingRequest.MediaSourceId) ? mediaSources[0] - : mediaSources.Find(i => string.Equals(i.Id, streamingRequest.MediaSourceId, StringComparison.InvariantCulture)); + : mediaSources.Find(i => string.Equals(i.Id, streamingRequest.MediaSourceId, StringComparison.Ordinal)); if (mediaSource == null && Guid.Parse(streamingRequest.MediaSourceId) == streamingRequest.Id) { diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 07d0b5543..9d80070eb 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -283,6 +283,7 @@ namespace Jellyfin.Api.Helpers lock (job.ProcessLock!) { + #pragma warning disable CA1849 // Can't await in lock block job.TranscodingThrottler?.Stop().GetAwaiter().GetResult(); var process = job.Process; @@ -308,6 +309,7 @@ namespace Jellyfin.Api.Helpers { } } + #pragma warning restore CA1849 } if (delete(job.Path!)) @@ -541,8 +543,7 @@ namespace Jellyfin.Api.Helpers state, cancellationTokenSource); - var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - _logger.LogInformation(commandLineLogMessage); + _logger.LogInformation("{Filename} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); var logFilePrefix = "FFmpeg.Transcode-"; if (state.VideoRequest != null @@ -560,8 +561,9 @@ namespace Jellyfin.Api.Helpers // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); + var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); - await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false); + await logStream.WriteAsync(commandLineLogMessageBytes, cancellationTokenSource.Token).ConfigureAwait(false); process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state); diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 57480b2f3..a3598edfa 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -13,8 +13,8 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" /> + <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> <PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="6.2.3" /> </ItemGroup> diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs new file mode 100644 index 000000000..44509a9c0 --- /dev/null +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs @@ -0,0 +1,22 @@ +namespace Jellyfin.Api.Models.ClientLogDtos +{ + /// <summary> + /// Client log document response dto. + /// </summary> + public class ClientLogDocumentResponseDto + { + /// <summary> + /// Initializes a new instance of the <see cref="ClientLogDocumentResponseDto"/> class. + /// </summary> + /// <param name="fileName">The file name.</param> + public ClientLogDocumentResponseDto(string fileName) + { + FileName = fileName; + } + + /// <summary> + /// Gets the resulting filename. + /// </summary> + public string FileName { get; } + } +} diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs index fed837b85..ab67c8732 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs @@ -134,7 +134,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos /// <summary> /// Gets or sets bytes downloaded. /// </summary> - public long? BytesDownloaded { get; set; } + public long BytesDownloaded { get; set; } /// <summary> /// Gets or sets bytes transcoded. diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs index 7b32d76ba..7a1ca252c 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs @@ -141,7 +141,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos private bool IsThrottleAllowed(TranscodingJobDto job, int thresholdSeconds) { - var bytesDownloaded = job.BytesDownloaded ?? 0; + var bytesDownloaded = job.BytesDownloaded; var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0; var downloadPositionTicks = job.DownloadPositionTicks ?? 0; @@ -197,7 +197,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos } } - _logger.LogDebug("No throttle data for " + path); + _logger.LogDebug("No throttle data for {Path}", path); return false; } diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 2de53e7c8..87233d907 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -24,7 +24,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> </ItemGroup> <!-- Code analysers--> @@ -35,7 +35,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0-rc.2*" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> </ItemGroup> <ItemGroup> diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 4078fd126..cf002dc73 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -455,10 +455,10 @@ namespace Jellyfin.Networking.Manager } // No bind address, so return all internal interfaces. - return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + return CreateCollection(_internalInterfaces); } - return new Collection<IPObject>(_bindAddresses); + return new Collection<IPObject>(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray()); } /// <inheritdoc/> @@ -481,7 +481,7 @@ namespace Jellyfin.Networking.Manager } // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address); + return address.IsLoopback() || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address)); } /// <inheritdoc/> @@ -647,16 +647,6 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses.AddItem(address, false); _interfaceNames[parts[2]] = Math.Abs(index); } - - if (IsIP4Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); - } - - if (IsIP6Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); - } } InitialiseLAN(config); @@ -1037,17 +1027,14 @@ namespace Jellyfin.Networking.Manager // Subnets are the same as the calculated internal interface. _lanSubnets = new Collection<IPObject>(); - // We must listen on loopback for LiveTV to function regardless of the settings. if (IsIP6Enabled) { - _lanSubnets.AddItem(IPNetAddress.IP6Loopback); _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local } if (IsIP4Enabled) { - _lanSubnets.AddItem(IPNetAddress.IP4Loopback); _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8")); _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12")); _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16")); @@ -1055,17 +1042,6 @@ namespace Jellyfin.Networking.Manager } else { - // We must listen on loopback for LiveTV to function regardless of the settings. - if (IsIP6Enabled) - { - _lanSubnets.AddItem(IPNetAddress.IP6Loopback); - } - - if (IsIP4Enabled) - { - _lanSubnets.AddItem(IPNetAddress.IP4Loopback); - } - // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork)); } diff --git a/Jellyfin.Server.Implementations/Events/EventManager.cs b/Jellyfin.Server.Implementations/Events/EventManager.cs index 8c5d8f2ce..7f7c4750d 100644 --- a/Jellyfin.Server.Implementations/Events/EventManager.cs +++ b/Jellyfin.Server.Implementations/Events/EventManager.cs @@ -57,7 +57,7 @@ namespace Jellyfin.Server.Implementations.Events } catch (Exception e) { - _logger.LogError(e, "Uncaught exception in EventConsumer {type}: ", service.GetType()); + _logger.LogError(e, "Uncaught exception in EventConsumer {Type}: ", service.GetType()); } } } diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index e26cf093b..73ee69424 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -19,13 +19,13 @@ <ItemGroup> <PackageReference Include="System.Linq.Async" Version="5.0.0" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0-rc.2*"> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0-rc.2*"> + <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> diff --git a/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs b/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs index 3ab043c64..d59d36e88 100644 --- a/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs +++ b/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs @@ -185,9 +185,21 @@ namespace Jellyfin.Server.Implementations.Security authInfo.IsAuthenticated = true; authInfo.Client = key.Name; authInfo.Token = key.AccessToken; - authInfo.DeviceId = string.Empty; - authInfo.Device = string.Empty; - authInfo.Version = string.Empty; + if (string.IsNullOrWhiteSpace(authInfo.DeviceId)) + { + authInfo.DeviceId = string.Empty; + } + + if (string.IsNullOrWhiteSpace(authInfo.Device)) + { + authInfo.Device = string.Empty; + } + + if (string.IsNullOrWhiteSpace(authInfo.Version)) + { + authInfo.Version = string.Empty; + } + authInfo.IsApiKey = true; } } diff --git a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs index 6a78e7ee6..7480a05c2 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs @@ -1,9 +1,6 @@ using System; -using System.Linq; -using System.Text; using System.Threading.Tasks; using Jellyfin.Data.Entities; -using MediaBrowser.Common.Cryptography; using MediaBrowser.Controller.Authentication; using MediaBrowser.Model.Cryptography; @@ -61,35 +58,25 @@ namespace Jellyfin.Server.Implementations.Users } // Handle the case when the stored password is null, but the user tried to login with a password - if (resolvedUser.Password != null) + if (resolvedUser.Password == null) { - byte[] passwordBytes = Encoding.UTF8.GetBytes(password); - - PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password); - if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id) - || _cryptographyProvider.DefaultHashMethod == readyHash.Id) - { - byte[] calculatedHash = _cryptographyProvider.ComputeHash( - readyHash.Id, - passwordBytes, - readyHash.Salt.ToArray()); - - if (readyHash.Hash.SequenceEqual(calculatedHash)) - { - success = true; - } - } - else - { - throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}"); - } + throw new AuthenticationException("Invalid username or password"); } + PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password); + success = _cryptographyProvider.Verify(readyHash, password); + if (!success) { throw new AuthenticationException("Invalid username or password"); } + // Migrate old hashes to the new default + if (!string.Equals(readyHash.Id, _cryptographyProvider.DefaultHashMethod, StringComparison.Ordinal)) + { + ChangePassword(resolvedUser, password); + } + return Task.FromResult(new ProviderAuthenticationResult { Username = username diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 8ca6e8d21..3d0a51ff6 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -5,7 +5,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Jellyfin.Data.Entities; @@ -13,7 +12,6 @@ using Jellyfin.Data.Enums; using Jellyfin.Data.Events; using Jellyfin.Data.Events.Users; using MediaBrowser.Common; -using MediaBrowser.Common.Cryptography; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; @@ -818,11 +816,7 @@ namespace Jellyfin.Server.Implementations.Users { // Check easy password var passwordHash = PasswordHash.Parse(user.EasyPassword); - var hash = _cryptoProvider.ComputeHash( - passwordHash.Id, - Encoding.UTF8.GetBytes(password), - passwordHash.Salt.ToArray()); - success = passwordHash.Hash.SequenceEqual(hash); + success = _cryptoProvider.Verify(passwordHash, password); } return (authenticationProvider, username, success); diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 21bd9ba01..67e50b92d 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -22,7 +22,6 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; using MediaBrowser.Model.Activity; -using MediaBrowser.Model.IO; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -42,67 +41,61 @@ namespace Jellyfin.Server /// <param name="loggerFactory">The <see cref="ILoggerFactory" /> to be used by the <see cref="CoreAppHost" />.</param> /// <param name="options">The <see cref="StartupOptions" /> to be used by the <see cref="CoreAppHost" />.</param> /// <param name="startupConfig">The <see cref="IConfiguration" /> to be used by the <see cref="CoreAppHost" />.</param> - /// <param name="fileSystem">The <see cref="IFileSystem" /> to be used by the <see cref="CoreAppHost" />.</param> - /// <param name="collection">The <see cref="IServiceCollection"/> to be used by the <see cref="CoreAppHost"/>.</param> public CoreAppHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, - IConfiguration startupConfig, - IFileSystem fileSystem, - IServiceCollection collection) + IConfiguration startupConfig) : base( applicationPaths, loggerFactory, options, - startupConfig, - fileSystem, - collection) + startupConfig) { } /// <inheritdoc/> - protected override void RegisterServices() + protected override void RegisterServices(IServiceCollection serviceCollection) { // Register an image encoder bool useSkiaEncoder = SkiaEncoder.IsNativeLibAvailable(); Type imageEncoderType = useSkiaEncoder ? typeof(SkiaEncoder) : typeof(NullImageEncoder); - ServiceCollection.AddSingleton(typeof(IImageEncoder), imageEncoderType); + serviceCollection.AddSingleton(typeof(IImageEncoder), imageEncoderType); // Log a warning if the Skia encoder could not be used if (!useSkiaEncoder) { - Logger.LogWarning($"Skia not available. Will fallback to {nameof(NullImageEncoder)}."); + Logger.LogWarning("Skia not available. Will fallback to {ImageEncoder}.", nameof(NullImageEncoder)); } - ServiceCollection.AddDbContextPool<JellyfinDb>( + serviceCollection.AddDbContextPool<JellyfinDb>( options => options .UseLoggerFactory(LoggerFactory) .UseSqlite($"Filename={Path.Combine(ApplicationPaths.DataPath, "jellyfin.db")}")); - ServiceCollection.AddEventServices(); - ServiceCollection.AddSingleton<IBaseItemManager, BaseItemManager>(); - ServiceCollection.AddSingleton<IEventManager, EventManager>(); - ServiceCollection.AddSingleton<JellyfinDbProvider>(); + serviceCollection.AddEventServices(); + serviceCollection.AddSingleton<IBaseItemManager, BaseItemManager>(); + serviceCollection.AddSingleton<IEventManager, EventManager>(); + serviceCollection.AddSingleton<JellyfinDbProvider>(); - ServiceCollection.AddSingleton<IActivityManager, ActivityManager>(); - ServiceCollection.AddSingleton<IUserManager, UserManager>(); - ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); - ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>(); + serviceCollection.AddSingleton<IActivityManager, ActivityManager>(); + serviceCollection.AddSingleton<IUserManager, UserManager>(); + serviceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); + serviceCollection.AddSingleton<IDeviceManager, DeviceManager>(); // TODO search the assemblies instead of adding them manually? - ServiceCollection.AddSingleton<IWebSocketListener, SessionWebSocketListener>(); - ServiceCollection.AddSingleton<IWebSocketListener, ActivityLogWebSocketListener>(); - ServiceCollection.AddSingleton<IWebSocketListener, ScheduledTasksWebSocketListener>(); - ServiceCollection.AddSingleton<IWebSocketListener, SessionInfoWebSocketListener>(); + serviceCollection.AddSingleton<IWebSocketListener, SessionWebSocketListener>(); + serviceCollection.AddSingleton<IWebSocketListener, ActivityLogWebSocketListener>(); + serviceCollection.AddSingleton<IWebSocketListener, ScheduledTasksWebSocketListener>(); + serviceCollection.AddSingleton<IWebSocketListener, SessionInfoWebSocketListener>(); - ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>(); + serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>(); - ServiceCollection.AddScoped<IAuthenticationManager, AuthenticationManager>(); + serviceCollection.AddScoped<IAuthenticationManager, AuthenticationManager>(); - base.RegisterServices(); + base.RegisterServices(serviceCollection); } /// <inheritdoc /> diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index e853609d6..fa98fda69 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -416,6 +416,18 @@ namespace Jellyfin.Server.Extensions } }) }); + + // Support dictionary with nullable string value. + options.MapType<Dictionary<string, string?>>(() => + new OpenApiSchema + { + Type = "object", + AdditionalProperties = new OpenApiSchema + { + Type = "string", + Nullable = true + } + }); } } } diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 8983eb50f..bfe8e82e8 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -31,20 +31,20 @@ <ItemGroup> <PackageReference Include="CommandLineParser" Version="2.8.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="6.0.0-rc.2*" /> - <PackageReference Include="prometheus-net" Version="5.0.1" /> - <PackageReference Include="prometheus-net.AspNetCore" Version="5.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="6.0.0" /> + <PackageReference Include="prometheus-net" Version="5.0.2" /> + <PackageReference Include="prometheus-net.AspNetCore" Version="5.0.2" /> <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" /> <PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" /> - <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0" /> + <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" /> <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.Graylog" Version="2.2.2" /> - <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.0.6" /> + <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.0.7" /> </ItemGroup> <ItemGroup> diff --git a/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs index 74874da1b..da9b69136 100644 --- a/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs +++ b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs @@ -68,7 +68,7 @@ namespace Jellyfin.Server.Middleware if (_enableWarning && watch.ElapsedMilliseconds > _warningThreshold) { _logger.LogWarning( - "Slow HTTP Response from {url} to {remoteIp} in {elapsed:g} with Status Code {statusCode}", + "Slow HTTP Response from {Url} to {RemoteIp} in {Elapsed:g} with Status Code {StatusCode}", context.Request.GetDisplayUrl(), context.GetNormalizedRemoteIp(), watch.Elapsed, diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index e4d2937e7..2f1d79157 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -51,7 +51,7 @@ namespace Jellyfin.Server.Middleware return; } - if (!key.Contains('=')) + if (!key.Contains('=', StringComparison.Ordinal)) { _store = value; return; diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 40f871759..74f2349f5 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -9,7 +9,7 @@ using Jellyfin.Data.Enums; using Jellyfin.Server.Implementations; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Dto; using Microsoft.Extensions.Logging; using SQLitePCL.pretty; @@ -114,6 +114,7 @@ namespace Jellyfin.Server.Migrations.Routines } var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version) + && !string.IsNullOrEmpty(version) ? chromecastDict[version] : ChromecastVersion.Stable; dto.CustomPrefs.Remove("chromecastVersion"); diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 45699f3af..7f158aebb 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -10,7 +10,6 @@ using System.Threading; using System.Threading.Tasks; using CommandLine; using Emby.Server.Implementations; -using Emby.Server.Implementations.IO; using Jellyfin.Server.Implementations; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; @@ -157,34 +156,36 @@ namespace Jellyfin.Server ApplicationHost.LogEnvironmentInfo(_logger, appPaths); + // If hosting the web client, validate the client content path + if (startupConfig.HostWebClient()) + { + string? webContentPath = appPaths.WebPath; + if (!Directory.Exists(webContentPath) || !Directory.EnumerateFiles(webContentPath).Any()) + { + _logger.LogError( + "The server is expected to host the web client, but the provided content directory is either " + + "invalid or empty: {WebContentPath}. If you do not want to host the web client with the " + + "server, you may set the '--nowebclient' command line flag, or set" + + "'{ConfigKey}=false' in your config settings.", + webContentPath, + ConfigurationExtensions.HostWebClientKey); + Environment.ExitCode = 1; + return; + } + } + PerformStaticInitialization(); - var serviceCollection = new ServiceCollection(); var appHost = new CoreAppHost( appPaths, _loggerFactory, options, - startupConfig, - new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths), - serviceCollection); + startupConfig); try { - // If hosting the web client, validate the client content path - if (startupConfig.HostWebClient()) - { - string? webContentPath = appHost.ConfigurationManager.ApplicationPaths.WebPath; - if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0) - { - throw new InvalidOperationException( - "The server is expected to host the web client, but the provided content directory is either " + - $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " + - "server, you may set the '--nowebclient' command line flag, or set" + - $"'{ConfigurationExtensions.HostWebClientKey}=false' in your config settings."); - } - } - - appHost.Init(); + var serviceCollection = new ServiceCollection(); + appHost.Init(serviceCollection); var webHost = new WebHostBuilder().ConfigureWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build(); @@ -648,7 +649,7 @@ namespace Jellyfin.Server private static string NormalizeCommandLineArgument(string arg) { - if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase)) + if (!arg.Contains(' ', StringComparison.Ordinal)) { return arg; } diff --git a/MediaBrowser.Common/Cryptography/CryptoExtensions.cs b/MediaBrowser.Common/Cryptography/CryptoExtensions.cs deleted file mode 100644 index 157b0ed10..000000000 --- a/MediaBrowser.Common/Cryptography/CryptoExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using MediaBrowser.Model.Cryptography; -using static MediaBrowser.Common.Cryptography.Constants; - -namespace MediaBrowser.Common.Cryptography -{ - /// <summary> - /// Class containing extension methods for working with Jellyfin cryptography objects. - /// </summary> - public static class CryptoExtensions - { - /// <summary> - /// Creates a new <see cref="PasswordHash" /> instance. - /// </summary> - /// <param name="cryptoProvider">The <see cref="ICryptoProvider" /> instance used.</param> - /// <param name="password">The password that will be hashed.</param> - /// <returns>A <see cref="PasswordHash" /> instance with the hash method, hash, salt and number of iterations.</returns> - public static PasswordHash CreatePasswordHash(this ICryptoProvider cryptoProvider, string password) - { - byte[] salt = cryptoProvider.GenerateSalt(); - return new PasswordHash( - cryptoProvider.DefaultHashMethod, - cryptoProvider.ComputeHashWithDefaultMethod( - Encoding.UTF8.GetBytes(password), - salt), - salt, - new Dictionary<string, string> - { - { "iterations", DefaultIterations.ToString(CultureInfo.InvariantCulture) } - }); - } - } -} diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 192a77611..53683cdbd 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common { @@ -137,13 +138,7 @@ namespace MediaBrowser.Common /// <summary> /// Initializes this instance. /// </summary> - void Init(); - - /// <summary> - /// Creates the instance. - /// </summary> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - object CreateInstance(Type type); + /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param> + void Init(IServiceCollection serviceCollection); } } diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 9c8ce4ac5..4ed44baef 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -19,9 +19,9 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> </ItemGroup> <ItemGroup> diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index abfdb41d8..ba2f419a2 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -60,7 +60,7 @@ namespace MediaBrowser.Controller.BaseItemManager return false; } - var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); + var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, baseItem.GetType().Name, StringComparison.OrdinalIgnoreCase)); return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.BaseItemManager return false; } - var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); + var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, baseItem.GetType().Name, StringComparison.OrdinalIgnoreCase)); return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs new file mode 100644 index 000000000..dea1c2f32 --- /dev/null +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.ClientEvent +{ + /// <inheritdoc /> + public class ClientEventLogger : IClientEventLogger + { + private readonly IServerApplicationPaths _applicationPaths; + + /// <summary> + /// Initializes a new instance of the <see cref="ClientEventLogger"/> class. + /// </summary> + /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param> + public ClientEventLogger(IServerApplicationPaths applicationPaths) + { + _applicationPaths = applicationPaths; + } + + /// <inheritdoc /> + public async Task<string> WriteDocumentAsync(string clientName, string clientVersion, Stream fileContents) + { + var fileName = $"upload_{clientName}_{clientVersion}_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}.log"; + var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); + await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); + return fileName; + } + } +} diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs new file mode 100644 index 000000000..ad8a1bd24 --- /dev/null +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -0,0 +1,23 @@ +using System.IO; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.ClientEvent +{ + /// <summary> + /// The client event logger. + /// </summary> + public interface IClientEventLogger + { + /// <summary> + /// Writes a file to the log directory. + /// </summary> + /// <param name="clientName">The client name writing the document.</param> + /// <param name="clientVersion">The client version writing the document.</param> + /// <param name="fileContents">The file contents to write.</param> + /// <returns>The created file name.</returns> + Task<string> WriteDocumentAsync( + string clientName, + string clientVersion, + Stream fileContents); + } +} diff --git a/MediaBrowser.Controller/Dlna/IDlnaManager.cs b/MediaBrowser.Controller/Dlna/IDlnaManager.cs index cc0a107a8..06da5ea09 100644 --- a/MediaBrowser.Controller/Dlna/IDlnaManager.cs +++ b/MediaBrowser.Controller/Dlna/IDlnaManager.cs @@ -37,8 +37,9 @@ namespace MediaBrowser.Controller.Dlna /// <summary> /// Updates the profile. /// </summary> + /// <param name="profileId">The profile id.</param> /// <param name="profile">The profile.</param> - void UpdateProfile(DeviceProfile profile); + void UpdateProfile(string profileId, DeviceProfile profile); /// <summary> /// Deletes the profile. diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index 536668e50..e90a2f56a 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -126,15 +126,6 @@ namespace MediaBrowser.Controller.Entities.Audio return base.GetBlockUnratedType(); } - public List<MediaStream> GetMediaStreams(MediaStreamType type) - { - return MediaSourceManager.GetMediaStreams(new MediaStreamQuery - { - ItemId = Id, - Type = type - }); - } - public SongInfo GetLookupInfo() { var info = GetItemLookupInfo<SongInfo>(); @@ -146,11 +137,7 @@ namespace MediaBrowser.Controller.Entities.Audio return info; } - protected override List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources() - { - var list = new List<Tuple<BaseItem, MediaSourceType>>(); - list.Add(new Tuple<BaseItem, MediaSourceType>(this, MediaSourceType.Default)); - return list; - } + protected override IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources() + => new[] { ((BaseItem)this, MediaSourceType.Default) }; } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 838a9f2f8..b1ac2fe8e 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Text; using System.Text.Json.Serialization; @@ -84,8 +83,6 @@ namespace MediaBrowser.Controller.Entities Model.Entities.ExtraType.Scene }; - public static readonly char[] SlugReplaceChars = { '?', '/', '&' }; - /// <summary> /// The supported extra folder names and types. See <see cref="Emby.Naming.Common.NamingOptions" />. /// </summary> @@ -335,13 +332,6 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public string ExternalSeriesId { get; set; } - /// <summary> - /// Gets or sets the etag. - /// </summary> - /// <value>The etag.</value> - [JsonIgnore] - public string ExternalEtag { get; set; } - [JsonIgnore] public virtual bool IsHidden => false; @@ -354,11 +344,6 @@ namespace MediaBrowser.Controller.Entities { get { - // if (IsOffline) - // { - // return LocationType.Offline; - // } - var path = Path; if (string.IsNullOrEmpty(path)) { @@ -391,7 +376,7 @@ namespace MediaBrowser.Controller.Entities } [JsonIgnore] - public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File); + public bool IsFileProtocol => PathProtocol == MediaProtocol.File; [JsonIgnore] public bool HasPathProtocol => PathProtocol.HasValue; @@ -583,14 +568,7 @@ namespace MediaBrowser.Controller.Entities } [JsonIgnore] - public virtual Guid DisplayParentId - { - get - { - var parentId = ParentId; - return parentId; - } - } + public virtual Guid DisplayParentId => ParentId; [JsonIgnore] public BaseItem DisplayParent @@ -853,13 +831,6 @@ namespace MediaBrowser.Controller.Entities return Id.ToString("N", CultureInfo.InvariantCulture); } - public bool IsPathProtocol(MediaProtocol protocol) - { - var current = PathProtocol; - - return current.HasValue && current.Value == protocol; - } - private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1) { var list = new List<Tuple<StringBuilder, bool>>(); @@ -987,7 +958,7 @@ namespace MediaBrowser.Controller.Entities ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture); - return System.IO.Path.Join(basePath, "library", idString.Slice(0, 2), idString); + return System.IO.Path.Join(basePath, "library", idString[..2], idString); } /// <summary> @@ -1182,9 +1153,9 @@ namespace MediaBrowser.Controller.Entities .ToList(); } - protected virtual List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources() + protected virtual IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources() { - return new List<Tuple<BaseItem, MediaSourceType>>(); + return Enumerable.Empty<(BaseItem, MediaSourceType)>(); } private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type) @@ -1302,8 +1273,7 @@ namespace MediaBrowser.Controller.Entities terms.Add(item.Name); } - var video = item as Video; - if (video != null) + if (item is Video video) { if (video.Video3DFormat.HasValue) { @@ -1338,7 +1308,7 @@ namespace MediaBrowser.Controller.Entities } } - return string.Join('/', terms.ToArray()); + return string.Join('/', terms); } /// <summary> @@ -1361,9 +1331,7 @@ namespace MediaBrowser.Controller.Entities .Select(audio => { // Try to retrieve it from the db. If we don't find it, use the resolved version - var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio; - - if (dbItem != null) + if (LibraryManager.GetItemById(audio.Id) is Audio.Audio dbItem) { audio = dbItem; } @@ -1476,7 +1444,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name); + Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name); } } @@ -1570,8 +1538,7 @@ namespace MediaBrowser.Controller.Entities } } - var hasTrailers = this as IHasTrailers; - if (hasTrailers != null) + if (this is IHasTrailers hasTrailers) { localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false); } @@ -2268,7 +2235,11 @@ namespace MediaBrowser.Controller.Entities var existingImage = GetImageInfo(image.Type, index); - if (existingImage != null) + if (existingImage == null) + { + AddImage(image); + } + else { existingImage.Path = image.Path; existingImage.DateModified = image.DateModified; @@ -2276,15 +2247,6 @@ namespace MediaBrowser.Controller.Entities existingImage.Height = image.Height; existingImage.BlurHash = image.BlurHash; } - else - { - var current = ImageInfos; - var currentCount = current.Length; - var newArr = new ItemImageInfo[currentCount + 1]; - current.CopyTo(newArr, 0); - newArr[currentCount] = image; - ImageInfos = newArr; - } } public void SetImagePath(ImageType type, int index, FileSystemMetadata file) @@ -2298,7 +2260,7 @@ namespace MediaBrowser.Controller.Entities if (image == null) { - ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray(); + AddImage(GetImageInfo(file, type)); } else { @@ -2342,14 +2304,24 @@ namespace MediaBrowser.Controller.Entities public void RemoveImage(ItemImageInfo image) { - RemoveImages(new List<ItemImageInfo> { image }); + RemoveImages(new[] { image }); } - public void RemoveImages(List<ItemImageInfo> deletedImages) + public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages) { ImageInfos = ImageInfos.Except(deletedImages).ToArray(); } + public void AddImage(ItemImageInfo image) + { + var current = ImageInfos; + var currentCount = current.Length; + var newArr = new ItemImageInfo[currentCount + 1]; + current.CopyTo(newArr, 0); + newArr[currentCount] = image; + ImageInfos = newArr; + } + public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken) => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken); @@ -2373,7 +2345,7 @@ namespace MediaBrowser.Controller.Entities if (deletedImages.Count > 0) { - ImageInfos = ImageInfos.Except(deletedImages).ToArray(); + RemoveImages(deletedImages); } return deletedImages.Count > 0; @@ -2495,11 +2467,11 @@ namespace MediaBrowser.Controller.Entities } /// <summary> - /// Adds the images. + /// Adds the images, updating metadata if they already are part of this item. /// </summary> /// <param name="imageType">Type of the image.</param> /// <param name="images">The images.</param> - /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> + /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns> /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception> public bool AddImages(ImageType imageType, List<FileSystemMetadata> images) { @@ -2512,7 +2484,6 @@ namespace MediaBrowser.Controller.Entities .ToList(); var newImageList = new List<FileSystemMetadata>(); - var imageAdded = false; var imageUpdated = false; foreach (var newImage in images) @@ -2528,7 +2499,6 @@ namespace MediaBrowser.Controller.Entities if (existing == null) { newImageList.Add(newImage); - imageAdded = true; } else { @@ -2549,19 +2519,6 @@ namespace MediaBrowser.Controller.Entities } } - if (imageAdded || images.Count != existingImages.Count) - { - var newImagePaths = images.Select(i => i.FullName).ToList(); - - var deleted = existingImages - .FindAll(i => i.IsLocalFile && !newImagePaths.Contains(i.Path.AsSpan(), StringComparison.OrdinalIgnoreCase) && !File.Exists(i.Path)); - - if (deleted.Count > 0) - { - ImageInfos = ImageInfos.Except(deleted).ToArray(); - } - } - if (newImageList.Count > 0) { ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray(); @@ -2612,7 +2569,7 @@ namespace MediaBrowser.Controller.Entities public bool AllowsMultipleImages(ImageType type) { - return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter; + return type == ImageType.Backdrop || type == ImageType.Chapter; } public Task SwapImagesAsync(ImageType type, int index1, int index2) @@ -2730,7 +2687,7 @@ namespace MediaBrowser.Controller.Entities protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol) { - if (protocol.HasValue && protocol.Value == MediaProtocol.File) + if (protocol == MediaProtocol.File) { return LibraryManager.GetPathAfterNetworkSubstitution(path, item); } @@ -2758,8 +2715,10 @@ namespace MediaBrowser.Controller.Entities protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken) { - var newOptions = new MetadataRefreshOptions(options); - newOptions.SearchResult = null; + var newOptions = new MetadataRefreshOptions(options) + { + SearchResult = null + }; var item = this; @@ -2820,8 +2779,10 @@ namespace MediaBrowser.Controller.Entities protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken) { - var newOptions = new MetadataRefreshOptions(options); - newOptions.SearchResult = null; + var newOptions = new MetadataRefreshOptions(options) + { + SearchResult = null + }; var id = LibraryManager.GetNewItemId(path, typeof(Video)); @@ -2835,14 +2796,6 @@ namespace MediaBrowser.Controller.Entities newOptions.ForceSave = true; } - // var parentId = Id; - // if (!video.IsOwnedItem || video.ParentId != parentId) - // { - // video.IsOwnedItem = true; - // video.ParentId = parentId; - // newOptions.ForceSave = true; - // } - if (video == null) { return Task.FromResult(true); @@ -2926,7 +2879,7 @@ namespace MediaBrowser.Controller.Entities .Select(i => i.OfficialRating) .Where(i => !string.IsNullOrEmpty(i)) .Distinct(StringComparer.OrdinalIgnoreCase) - .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i))) + .Select(i => (i, LocalizationManager.GetRatingLevel(i))) .OrderBy(i => i.Item2 ?? 1000) .Select(i => i.Item1); @@ -2973,18 +2926,6 @@ namespace MediaBrowser.Controller.Entities .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value)); } - public IEnumerable<BaseItem> GetTrailers() - { - if (this is IHasTrailers) - { - return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName); - } - else - { - return Array.Empty<BaseItem>(); - } - } - public virtual long GetRunTimeTicksForPlayState() { return RunTimeTicks ?? 0; diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 18b4ec3c6..ec1ebaabe 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -303,7 +303,7 @@ namespace MediaBrowser.Controller.Entities if (dictionary.ContainsKey(id)) { Logger.LogError( - "Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}", + "Found folder containing items with duplicate id. Path: {Path}, Child Name: {ChildName}", Path ?? Name, child.Path ?? child.Name); } @@ -425,7 +425,7 @@ namespace MediaBrowser.Controller.Entities { if (item.IsFileProtocol) { - Logger.LogDebug("Removed item: " + item.Path); + Logger.LogDebug("Removed item: {Path}", item.Path); item.SetParent(null); LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false); @@ -807,7 +807,7 @@ namespace MediaBrowser.Controller.Entities { if (this is not ICollectionFolder) { - Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name); + Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name); return true; } } @@ -1013,6 +1013,7 @@ namespace MediaBrowser.Controller.Entities items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager); } + #pragma warning disable CA1309 if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater)) { items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.InvariantCultureIgnoreCase) < 1); @@ -1027,6 +1028,7 @@ namespace MediaBrowser.Controller.Entities { items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultureIgnoreCase) == 1); } + #pragma warning restore CA1309 // This must be the last filter if (!string.IsNullOrEmpty(query.AdjacentTo)) diff --git a/MediaBrowser.Controller/Entities/IHasScreenshots.cs b/MediaBrowser.Controller/Entities/IHasScreenshots.cs deleted file mode 100644 index ae01c223e..000000000 --- a/MediaBrowser.Controller/Entities/IHasScreenshots.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace MediaBrowser.Controller.Entities -{ - /// <summary> - /// The item has screenshots. - /// </summary> - public interface IHasScreenshots - { - } -} diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 62f3c4b55..a6f107849 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -102,7 +102,7 @@ namespace MediaBrowser.Controller.Entities parent = LibraryManager.GetItemById(ParentId) as Folder ?? parent; } - return new UserViewBuilder(UserViewManager, LibraryManager, Logger, UserDataManager, TVSeriesManager, ConfigurationManager) + return new UserViewBuilder(UserViewManager, LibraryManager, Logger, UserDataManager, TVSeriesManager) .GetUserItems(parent, this, CollectionType, query); } diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 266fda767..1cff72037 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -8,7 +8,6 @@ using System.Globalization; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.TV; @@ -30,22 +29,19 @@ namespace MediaBrowser.Controller.Entities private readonly ILogger<BaseItem> _logger; private readonly IUserDataManager _userDataManager; private readonly ITVSeriesManager _tvSeriesManager; - private readonly IServerConfigurationManager _config; public UserViewBuilder( IUserViewManager userViewManager, ILibraryManager libraryManager, ILogger<BaseItem> logger, IUserDataManager userDataManager, - ITVSeriesManager tvSeriesManager, - IServerConfigurationManager config) + ITVSeriesManager tvSeriesManager) { _userViewManager = userViewManager; _libraryManager = libraryManager; _logger = logger; _userDataManager = userDataManager; _tvSeriesManager = tvSeriesManager; - _config = config; } public QueryResult<BaseItem> GetUserItems(Folder queryParent, Folder displayParent, string viewType, InternalItemsQuery query) diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 7dd95b85c..de42c67d3 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -509,35 +509,35 @@ namespace MediaBrowser.Controller.Entities }).FirstOrDefault(); } - protected override List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources() + protected override IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources() { - var list = new List<Tuple<BaseItem, MediaSourceType>>(); + var list = new List<(BaseItem, MediaSourceType)> + { + (this, MediaSourceType.Default) + }; - list.Add(new Tuple<BaseItem, MediaSourceType>(this, MediaSourceType.Default)); - list.AddRange(GetLinkedAlternateVersions().Select(i => new Tuple<BaseItem, MediaSourceType>(i, MediaSourceType.Grouping))); + list.AddRange(GetLinkedAlternateVersions().Select(i => ((BaseItem)i, MediaSourceType.Grouping))); if (!string.IsNullOrEmpty(PrimaryVersionId)) { - var primary = LibraryManager.GetItemById(PrimaryVersionId) as Video; - if (primary != null) + if (LibraryManager.GetItemById(PrimaryVersionId) is Video primary) { var existingIds = list.Select(i => i.Item1.Id).ToList(); - list.Add(new Tuple<BaseItem, MediaSourceType>(primary, MediaSourceType.Grouping)); - list.AddRange(primary.GetLinkedAlternateVersions().Where(i => !existingIds.Contains(i.Id)).Select(i => new Tuple<BaseItem, MediaSourceType>(i, MediaSourceType.Grouping))); + list.Add((primary, MediaSourceType.Grouping)); + list.AddRange(primary.GetLinkedAlternateVersions().Where(i => !existingIds.Contains(i.Id)).Select(i => ((BaseItem)i, MediaSourceType.Grouping))); } } var localAlternates = list .SelectMany(i => { - var video = i.Item1 as Video; - return video == null ? new List<Guid>() : video.GetLocalAlternateVersionIds(); + return i.Item1 is Video video ? video.GetLocalAlternateVersionIds() : Enumerable.Empty<Guid>(); }) .Select(LibraryManager.GetItemById) .Where(i => i != null) .ToList(); - list.AddRange(localAlternates.Select(i => new Tuple<BaseItem, MediaSourceType>(i, MediaSourceType.Default))); + list.AddRange(localAlternates.Select(i => (i, MediaSourceType.Default))); return list; } diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs index b8a0bf331..2429ac42d 100644 --- a/MediaBrowser.Controller/IO/FileData.cs +++ b/MediaBrowser.Controller/IO/FileData.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Controller.IO if (string.IsNullOrEmpty(newPath)) { // invalid shortcut - could be old or target could just be unavailable - logger.LogWarning("Encountered invalid shortcut: " + fullName); + logger.LogWarning("Encountered invalid shortcut: {Path}", fullName); continue; } @@ -83,7 +83,7 @@ namespace MediaBrowser.Controller.IO } catch (Exception ex) { - logger.LogError(ex, "Error resolving shortcut from {path}", fullName); + logger.LogError(ex, "Error resolving shortcut from {Path}", fullName); } } else if (flattenFolderDepth > 0 && isDirectory) diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 7e5e742f5..8f8cf75a6 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -43,11 +43,6 @@ namespace MediaBrowser.Controller string FriendlyName { get; } /// <summary> - /// Gets the configured published server url. - /// </summary> - string PublishedServerUrl { get; } - - /// <summary> /// Gets the system info. /// </summary> /// <param name="request">The HTTP request.</param> @@ -60,32 +55,29 @@ namespace MediaBrowser.Controller /// Gets a URL specific for the request. /// </summary> /// <param name="request">The <see cref="HttpRequest"/> instance.</param> - /// <param name="port">Optional port number.</param> /// <returns>An accessible URL.</returns> - string GetSmartApiUrl(HttpRequest request, int? port = null); + string GetSmartApiUrl(HttpRequest request); /// <summary> /// Gets a URL specific for the request. /// </summary> /// <param name="remoteAddr">The remote <see cref="IPAddress"/> of the connection.</param> - /// <param name="port">Optional port number.</param> /// <returns>An accessible URL.</returns> - string GetSmartApiUrl(IPAddress remoteAddr, int? port = null); + string GetSmartApiUrl(IPAddress remoteAddr); /// <summary> /// Gets a URL specific for the request. /// </summary> /// <param name="hostname">The hostname used in the connection.</param> - /// <param name="port">Optional port number.</param> /// <returns>An accessible URL.</returns> - string GetSmartApiUrl(string hostname, int? port = null); + string GetSmartApiUrl(string hostname); /// <summary> - /// Gets a localhost URL that can be used to access the API using the loop-back IP address. - /// over HTTP (not HTTPS). + /// Gets an URL that can be used to access the API over LAN. /// </summary> + /// <param name="allowHttps">A value indicating whether to allow HTTPS.</param> /// <returns>The API URL.</returns> - string GetLoopbackHttpApiUrl(); + string GetApiUrlForLocalAccess(bool allowHttps = true); /// <summary> /// Gets a local (LAN) URL that can be used to access the API. @@ -103,8 +95,6 @@ namespace MediaBrowser.Controller /// <returns>The API URL.</returns> string GetLocalApiUrl(string hostname, string scheme = null, int? port = null); - IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo(); - string ExpandVirtualPath(string path); string ReverseVirtualPath(string path); diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index d40e56c7d..1e1e2adb8 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -397,20 +397,6 @@ namespace MediaBrowser.Controller.Library string sortName); /// <summary> - /// Determines whether [is video file] [the specified path]. - /// </summary> - /// <param name="path">The path.</param> - /// <returns><c>true</c> if [is video file] [the specified path]; otherwise, <c>false</c>.</returns> - bool IsVideoFile(string path); - - /// <summary> - /// Determines whether [is audio file] [the specified path]. - /// </summary> - /// <param name="path">The path.</param> - /// <returns><c>true</c> if [is audio file] [the specified path]; otherwise, <c>false</c>.</returns> - bool IsAudioFile(string path); - - /// <summary> /// Gets the season number from path. /// </summary> /// <param name="path">The path.</param> @@ -625,11 +611,5 @@ namespace MediaBrowser.Controller.Library BaseItem GetParentItem(string parentId, Guid? userId); BaseItem GetParentItem(Guid? parentId, Guid? userId); - - /// <summary> - /// Gets or creates a static instance of <see cref="NamingOptions"/>. - /// </summary> - /// <returns>An instance of the <see cref="NamingOptions"/> class.</returns> - NamingOptions GetNamingOptions(); } } diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs index e802796d3..f1758a9d8 100644 --- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs +++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs @@ -33,13 +33,6 @@ namespace MediaBrowser.Controller.Library /// <summary> /// Gets the media streams. /// </summary> - /// <param name="mediaSourceId">The media source identifier.</param> - /// <returns>IEnumerable<MediaStream>.</returns> - List<MediaStream> GetMediaStreams(string mediaSourceId); - - /// <summary> - /// Gets the media streams. - /// </summary> /// <param name="query">The query.</param> /// <returns>IEnumerable<MediaStream>.</returns> List<MediaStream> GetMediaStreams(MediaStreamQuery query); diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index bfc1e4857..91d162b41 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -36,6 +36,7 @@ namespace MediaBrowser.Controller.Library DirectoryService = directoryService; } + // TODO remove dependencies as properties, they should be injected where it makes sense public IDirectoryService DirectoryService { get; } /// <summary> @@ -237,6 +238,40 @@ namespace MediaBrowser.Controller.Library } /// <summary> + /// Gets the configured content type for the path. + /// </summary> + /// <remarks> + /// This is subject to future refactoring as it relies on a static property in BaseItem. + /// </remarks> + /// <returns>The configured content type.</returns> + public string GetConfiguredContentType() + { + return BaseItem.LibraryManager.GetConfiguredContentType(Path); + } + + /// <summary> + /// Gets the file system children that do not hit the ignore file check. + /// </summary> + /// <remarks> + /// This is subject to future refactoring as it relies on a static property in BaseItem. + /// </remarks> + /// <returns>The file system children that are not ignored.</returns> + public IEnumerable<FileSystemMetadata> GetActualFileSystemChildren() + { + var numberOfChildren = FileSystemChildren.Length; + for (var i = 0; i < numberOfChildren; i++) + { + var child = FileSystemChildren[i]; + if (BaseItem.LibraryManager.IgnoreFile(child, Parent)) + { + continue; + } + + yield return child; + } + } + + /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index d37880865..cf3b7bc7a 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -14,11 +14,11 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Diacritics" Version="3.3.4" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> - <PackageReference Include="System.Threading.Tasks.Dataflow" Version="6.0.0-rc.2*" /> + <PackageReference Include="Diacritics" Version="3.3.10" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> + <PackageReference Include="System.Threading.Tasks.Dataflow" Version="6.0.0" /> </ItemGroup> <ItemGroup> diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index e6511ca8d..1418e583e 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.MediaInfo; @@ -95,36 +96,10 @@ namespace MediaBrowser.Controller.MediaEncoding /// <param name="mediaSource">Media source information.</param> /// <param name="imageStream">Media stream information.</param> /// <param name="imageStreamIndex">Index of the stream to extract from.</param> - /// <param name="outputExtension">The extension of the file to write, including the '.'.</param> + /// <param name="targetFormat">The format of the file to write.</param> /// <param name="cancellationToken">CancellationToken to use for operation.</param> /// <returns>Location of video image.</returns> - Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken); - - /// <summary> - /// Extracts the video images on interval. - /// </summary> - /// <param name="inputFile">Input file.</param> - /// <param name="container">Video container type.</param> - /// <param name="videoStream">Media stream information.</param> - /// <param name="mediaSource">Media source information.</param> - /// <param name="threedFormat">Video 3D format.</param> - /// <param name="interval">Time interval.</param> - /// <param name="targetDirectory">Directory to write images.</param> - /// <param name="filenamePrefix">Filename prefix to use.</param> - /// <param name="maxWidth">Maximum width of image.</param> - /// <param name="cancellationToken">CancellationToken to use for operation.</param> - /// <returns>A task.</returns> - Task ExtractVideoImagesOnInterval( - string inputFile, - string container, - MediaStream videoStream, - MediaSourceInfo mediaSource, - Video3DFormat? threedFormat, - TimeSpan interval, - string targetDirectory, - string filenamePrefix, - int? maxWidth, - CancellationToken cancellationToken); + Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, ImageFormat? targetFormat, CancellationToken cancellationToken); /// <summary> /// Gets the media info. diff --git a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs index 2ac4c728b..08d129a82 100644 --- a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs @@ -1,5 +1,3 @@ -#nullable disable - #pragma warning disable CA1819, CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/ItemInfo.cs b/MediaBrowser.Controller/Providers/ItemInfo.cs index b8dd416a2..3a97127ea 100644 --- a/MediaBrowser.Controller/Providers/ItemInfo.cs +++ b/MediaBrowser.Controller/Providers/ItemInfo.cs @@ -1,5 +1,3 @@ -#nullable disable - #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index b9786ddb0..2523ec709 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -18,18 +18,12 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public class PausedGroupState : AbstractGroupState { /// <summary> - /// The logger. - /// </summary> - private readonly ILogger<PausedGroupState> _logger; - - /// <summary> /// Initializes a new instance of the <see cref="PausedGroupState"/> class. /// </summary> /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> public PausedGroupState(ILoggerFactory loggerFactory) : base(loggerFactory) { - _logger = LoggerFactory.CreateLogger<PausedGroupState>(); } /// <inheritdoc /> diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index cb1cadf0b..4f29ca1c6 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -18,18 +18,12 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public class PlayingGroupState : AbstractGroupState { /// <summary> - /// The logger. - /// </summary> - private readonly ILogger<PlayingGroupState> _logger; - - /// <summary> /// Initializes a new instance of the <see cref="PlayingGroupState"/> class. /// </summary> /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> public PlayingGroupState(ILoggerFactory loggerFactory) : base(loggerFactory) { - _logger = LoggerFactory.CreateLogger<PlayingGroupState>(); } /// <inheritdoc /> diff --git a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs index 10d691b3e..6d076ba27 100644 --- a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs @@ -15,22 +15,18 @@ namespace MediaBrowser.LocalMetadata.Images /// </summary> public class InternalMetadataFolderImageProvider : ILocalImageProvider, IHasOrder { - private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly ILogger<InternalMetadataFolderImageProvider> _logger; /// <summary> /// Initializes a new instance of the <see cref="InternalMetadataFolderImageProvider"/> class. /// </summary> - /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> /// <param name="logger">Instance of the <see cref="ILogger{InternalMetadataFolderImageProvider}"/> interface.</param> public InternalMetadataFolderImageProvider( - IServerConfigurationManager config, IFileSystem fileSystem, ILogger<InternalMetadataFolderImageProvider> logger) { - _config = config; _fileSystem = fileSystem; _logger = logger; } diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs index 988581df9..f79147803 100644 --- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs @@ -256,11 +256,6 @@ namespace MediaBrowser.LocalMetadata.Images { PopulateBackdrops(item, images, files, imagePrefix, isInMixedFolder); } - - if (item is IHasScreenshots) - { - PopulateScreenshots(images, files, imagePrefix, isInMixedFolder); - } } private void PopulatePrimaryImages(BaseItem item, List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder) @@ -363,11 +358,6 @@ namespace MediaBrowser.LocalMetadata.Images })); } - private void PopulateScreenshots(List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder) - { - PopulateBackdrops(images, files, imagePrefix, "screenshot", "screenshot", isInMixedFolder, ImageType.Screenshot); - } - private void PopulateBackdrops(List<LocalImageInfo> images, List<FileSystemMetadata> files, string imagePrefix, string firstFileName, string subsequentFileNamePrefix, bool isInMixedFolder, ImageType type) { AddImage(files, images, imagePrefix + firstFileName, type); diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 5a36c1663..777fe6774 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -149,7 +149,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } else { - Logger.LogWarning("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: {Value}", val); } } @@ -412,7 +412,7 @@ namespace MediaBrowser.LocalMetadata.Parsers { var actors = reader.ReadInnerXml(); - if (actors.Contains("<", StringComparison.Ordinal)) + if (actors.Contains('<', StringComparison.Ordinal)) { // This is one of the mis-named "Actors" full nodes created by MB2 // Create a reader and pass it to the persons node processor diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 5e7af23fc..1a8b5bb4e 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -144,7 +144,7 @@ namespace MediaBrowser.LocalMetadata.Savers } catch (Exception ex) { - Logger.LogError(ex, "Error setting hidden attribute on {path}", path); + Logger.LogError(ex, "Error setting hidden attribute on {Path}", path); } } diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index a524aeaa9..9ebc0d0cf 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -223,11 +223,10 @@ namespace MediaBrowser.MediaEncoding.Attachments if (failed) { - var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}"; + _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath); - _logger.LogError(msg); - - throw new InvalidOperationException(msg); + throw new InvalidOperationException( + string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath)); } else { diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index fbc7ba72f..1c97a1982 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -19,6 +19,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.MediaEncoding.Probing; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; @@ -478,17 +479,17 @@ namespace MediaBrowser.MediaEncoding.Encoder Protocol = MediaProtocol.File }; - return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, ".jpg", cancellationToken); + return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, ImageFormat.Jpg, cancellationToken); } public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) { - return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, ".jpg", cancellationToken); + return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, ImageFormat.Jpg, cancellationToken); } - public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken) + public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, ImageFormat? targetFormat, CancellationToken cancellationToken) { - return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, outputExtension, cancellationToken); + return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, targetFormat, cancellationToken); } private async Task<string> ExtractImage( @@ -500,7 +501,7 @@ namespace MediaBrowser.MediaEncoding.Encoder bool isAudio, Video3DFormat? threedFormat, TimeSpan? offset, - string outputExtension, + ImageFormat? targetFormat, CancellationToken cancellationToken) { var inputArgument = GetInputArgument(inputFile, mediaSource); @@ -510,7 +511,7 @@ namespace MediaBrowser.MediaEncoding.Encoder // The failure of HDR extraction usually occurs when using custom ffmpeg that does not contain the zscale filter. try { - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, true, outputExtension, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, true, targetFormat, cancellationToken).ConfigureAwait(false); } catch (ArgumentException) { @@ -523,7 +524,7 @@ namespace MediaBrowser.MediaEncoding.Encoder try { - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, true, outputExtension, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, true, targetFormat, cancellationToken).ConfigureAwait(false); } catch (ArgumentException) { @@ -536,7 +537,7 @@ namespace MediaBrowser.MediaEncoding.Encoder try { - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, false, outputExtension, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, false, targetFormat, cancellationToken).ConfigureAwait(false); } catch (ArgumentException) { @@ -548,24 +549,25 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, false, outputExtension, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, false, targetFormat, cancellationToken).ConfigureAwait(false); } - private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, bool allowTonemap, string outputExtension, CancellationToken cancellationToken) + private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, bool allowTonemap, ImageFormat? targetFormat, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(inputPath)) { throw new ArgumentNullException(nameof(inputPath)); } - if (string.IsNullOrEmpty(outputExtension)) + var outputExtension = targetFormat switch { - outputExtension = ".jpg"; - } - else if (outputExtension[0] != '.') - { - outputExtension = "." + outputExtension; - } + ImageFormat.Bmp => ".bmp", + ImageFormat.Gif => ".gif", + ImageFormat.Jpg => ".jpg", + ImageFormat.Png => ".png", + ImageFormat.Webp => ".webp", + _ => ".jpg" + }; var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + outputExtension); Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath)); @@ -682,11 +684,9 @@ namespace MediaBrowser.MediaEncoding.Encoder if (exitCode == -1 || !file.Exists || file.Length == 0) { - var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputPath); - - _logger.LogError(msg); + _logger.LogError("ffmpeg image extraction failed for {Path}", inputPath); - throw new FfmpegException(msg); + throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputPath)); } return tempExtractPath; @@ -705,117 +705,6 @@ namespace MediaBrowser.MediaEncoding.Encoder return time.ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture); } - public async Task ExtractVideoImagesOnInterval( - string inputFile, - string container, - MediaStream videoStream, - MediaSourceInfo mediaSource, - Video3DFormat? threedFormat, - TimeSpan interval, - string targetDirectory, - string filenamePrefix, - int? maxWidth, - CancellationToken cancellationToken) - { - var inputArgument = GetInputArgument(inputFile, mediaSource); - - var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(CultureInfo.InvariantCulture); - - if (maxWidth.HasValue) - { - var maxWidthParam = maxWidth.Value.ToString(CultureInfo.InvariantCulture); - - vf += string.Format(CultureInfo.InvariantCulture, ",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam); - } - - Directory.CreateDirectory(targetDirectory); - var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg"); - - var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet {2} -f image2 \"{1}\"", inputArgument, outputPath, vf, _threads); - - if (!string.IsNullOrWhiteSpace(container)) - { - var inputFormat = EncodingHelper.GetInputFormat(container); - if (!string.IsNullOrWhiteSpace(inputFormat)) - { - args = "-f " + inputFormat + " " + args; - } - } - - var processStartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _ffmpegPath, - Arguments = args, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }; - - _logger.LogInformation(processStartInfo.FileName + " " + processStartInfo.Arguments); - - await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - bool ranToCompletion = false; - - var process = new Process - { - StartInfo = processStartInfo, - EnableRaisingEvents = true - }; - using (var processWrapper = new ProcessWrapper(process, this)) - { - try - { - StartProcess(processWrapper); - - // Need to give ffmpeg enough time to make all the thumbnails, which could be a while, - // but we still need to detect if the process hangs. - // Making the assumption that as long as new jpegs are showing up, everything is good. - - bool isResponsive = true; - int lastCount = 0; - - while (isResponsive) - { - if (await process.WaitForExitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false)) - { - ranToCompletion = true; - break; - } - - cancellationToken.ThrowIfCancellationRequested(); - - var jpegCount = _fileSystem.GetFilePaths(targetDirectory) - .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase)); - - isResponsive = jpegCount > lastCount; - lastCount = jpegCount; - } - - if (!ranToCompletion) - { - StopProcess(processWrapper, 1000); - } - } - finally - { - _thumbnailResourcePool.Release(); - } - - var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1; - - if (exitCode == -1) - { - var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputArgument); - - _logger.LogError(msg); - - throw new FfmpegException(msg); - } - } - } - private void StartProcess(ProcessWrapper process) { process.Process.Start(); diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index a6caca8db..6bb8bcdab 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -24,9 +24,9 @@ <ItemGroup> <PackageReference Include="BDInfo" Version="0.7.6.1" /> <PackageReference Include="libse" Version="3.6.2" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" /> - <PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0-rc.2*" /> - <PackageReference Include="UTF.Unknown" Version="2.4.0" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> + <PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" /> + <PackageReference Include="UTF.Unknown" Version="2.5.0" /> </ItemGroup> <!-- Code Analyzers--> diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index eb8850cd2..dcfbd2a32 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -716,10 +716,6 @@ namespace MediaBrowser.MediaEncoding.Probing } else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)) { - stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase) - ? MediaStreamType.EmbeddedImage - : MediaStreamType.Video; - stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate); stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate); @@ -740,8 +736,10 @@ namespace MediaBrowser.MediaEncoding.Probing stream.IsInterlaced = true; } - if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || - string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)) + if (isAudio + || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) + || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) + || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)) { stream.Type = MediaStreamType.EmbeddedImage; } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 2b2de2ff6..89365a516 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -636,17 +636,14 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (failed) { - var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}"; + _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath); - _logger.LogError(msg); - - throw new FfmpegException(msg); + throw new FfmpegException( + string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath)); } else { - var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}"; - - _logger.LogInformation(msg); + _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath); } if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase)) diff --git a/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs b/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs index 6d56dda91..38ef57dee 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs @@ -19,12 +19,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { writer.WriteLine("WEBVTT"); writer.WriteLine(); - writer.WriteLine("REGION"); - writer.WriteLine("id:subtitle"); - writer.WriteLine("width:80%"); - writer.WriteLine("lines:3"); - writer.WriteLine("regionanchor:50%,100%"); - writer.WriteLine("viewportanchor:50%,90%"); + writer.WriteLine("Region: id:subtitle width:80% lines:3 regionanchor:50%,100% viewportanchor:50%,90%"); writer.WriteLine(); foreach (var trackEvent in info.TrackEvents) { @@ -39,7 +34,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles endTime = startTime.Add(TimeSpan.FromMilliseconds(1)); } - writer.WriteLine(@"{0:hh\:mm\:ss\.fff} --> {1:hh\:mm\:ss\.fff} region:subtitle", startTime, endTime); + writer.WriteLine(@"{0:hh\:mm\:ss\.fff} --> {1:hh\:mm\:ss\.fff} region:subtitle line:90%", startTime, endTime); var text = trackEvent.Text; diff --git a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs new file mode 100644 index 000000000..21087b564 --- /dev/null +++ b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs @@ -0,0 +1,75 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Model.ClientLog +{ + /// <summary> + /// The client log event. + /// </summary> + public class ClientLogEvent + { + /// <summary> + /// Initializes a new instance of the <see cref="ClientLogEvent"/> class. + /// </summary> + /// <param name="timestamp">The log timestamp.</param> + /// <param name="level">The log level.</param> + /// <param name="userId">The user id.</param> + /// <param name="clientName">The client name.</param> + /// <param name="clientVersion">The client version.</param> + /// <param name="deviceId">The device id.</param> + /// <param name="message">The message.</param> + public ClientLogEvent( + DateTime timestamp, + LogLevel level, + Guid? userId, + string clientName, + string clientVersion, + string deviceId, + string message) + { + Timestamp = timestamp; + UserId = userId; + ClientName = clientName; + ClientVersion = clientVersion; + DeviceId = deviceId; + Message = message; + Level = level; + } + + /// <summary> + /// Gets the event timestamp. + /// </summary> + public DateTime Timestamp { get; } + + /// <summary> + /// Gets the log level. + /// </summary> + public LogLevel Level { get; } + + /// <summary> + /// Gets the user id. + /// </summary> + public Guid? UserId { get; } + + /// <summary> + /// Gets the client name. + /// </summary> + public string ClientName { get; } + + /// <summary> + /// Gets the client version. + /// </summary> + public string ClientVersion { get; } + + /// + /// <summary> + /// Gets the device id. + /// </summary> + public string DeviceId { get; } + + /// <summary> + /// Gets the log message. + /// </summary> + public string Message { get; } + } +} diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs index aae5359b1..90cf8f43b 100644 --- a/MediaBrowser.Model/Configuration/LibraryOptions.cs +++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs @@ -16,6 +16,7 @@ namespace MediaBrowser.Model.Configuration SkipSubtitlesIfAudioTrackMatches = true; RequirePerfectSubtitleMatch = true; + AutomaticallyAddToCollection = true; EnablePhotos = true; SaveSubtitlesWithMedia = true; EnableRealtimeMonitor = true; @@ -80,6 +81,7 @@ namespace MediaBrowser.Model.Configuration public bool RequirePerfectSubtitleMatch { get; set; } public bool SaveSubtitlesWithMedia { get; set; } + public bool AutomaticallyAddToCollection { get; set; } public TypeOptions[] TypeOptions { get; set; } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index d1e999666..0ab721b77 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -402,8 +402,6 @@ namespace MediaBrowser.Model.Configuration /// </summary> public bool RequireHttps { get; set; } = false; - public bool EnableNewOmdbSupport { get; set; } = true; - /// <summary> /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>. /// </summary> @@ -459,5 +457,10 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets a value indicating whether older plugins should automatically be deleted from the plugin folder. /// </summary> public bool RemoveOldPlugins { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether clients should be allowed to upload logs. + /// </summary> + public bool AllowClientLogUpload { get; set; } = true; } } diff --git a/MediaBrowser.Common/Cryptography/Constants.cs b/MediaBrowser.Model/Cryptography/Constants.cs index 354114232..f2ebb5d3d 100644 --- a/MediaBrowser.Common/Cryptography/Constants.cs +++ b/MediaBrowser.Model/Cryptography/Constants.cs @@ -1,4 +1,4 @@ -namespace MediaBrowser.Common.Cryptography +namespace MediaBrowser.Model.Cryptography { /// <summary> /// Class containing global constants for Jellyfin Cryptography. @@ -8,11 +8,16 @@ namespace MediaBrowser.Common.Cryptography /// <summary> /// The default length for new salts. /// </summary> - public const int DefaultSaltLength = 64; + public const int DefaultSaltLength = 128 / 8; + + /// <summary> + /// The default output length. + /// </summary> + public const int DefaultOutputLength = 512 / 8; /// <summary> /// The default amount of iterations for hashing passwords. /// </summary> - public const int DefaultIterations = 1000; + public const int DefaultIterations = 120000; } } diff --git a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs index d8b7d848a..6c521578c 100644 --- a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs +++ b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs @@ -1,6 +1,6 @@ #pragma warning disable CS1591 -using System.Collections.Generic; +using System; namespace MediaBrowser.Model.Cryptography { @@ -8,11 +8,14 @@ namespace MediaBrowser.Model.Cryptography { string DefaultHashMethod { get; } - IEnumerable<string> GetSupportedHashMethods(); + /// <summary> + /// Creates a new <see cref="PasswordHash" /> instance. + /// </summary> + /// <param name="password">The password that will be hashed.</param> + /// <returns>A <see cref="PasswordHash" /> instance with the hash method, hash, salt and number of iterations.</returns> + PasswordHash CreatePasswordHash(ReadOnlySpan<char> password); - byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt); - - byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt); + bool Verify(PasswordHash hash, ReadOnlySpan<char> password); byte[] GenerateSalt(); diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Model/Cryptography/PasswordHash.cs index 0e2065302..eec541041 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Model/Cryptography/PasswordHash.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace MediaBrowser.Common.Cryptography +namespace MediaBrowser.Model.Cryptography { // Defined from this hash storage spec // https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index e8fd18ae4..58b06ca1d 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -151,10 +151,12 @@ namespace MediaBrowser.Model.Dlna DlnaFlags.InteractiveTransferMode | DlnaFlags.DlnaV15; - // if (isDirectStream) - // { - // flagValue = flagValue | DlnaFlags.ByteBasedSeek; - // } + if (isDirectStream) + { + flagValue |= DlnaFlags.ByteBasedSeek; + } + + // Time based seek is curently disabled when streaming. On LG CX3 adding DlnaFlags.TimeBasedSeek and orgPn causes the DLNA playback to fail (format not supported). Further investigations are needed before enabling the remaining code paths. // else if (runtimeTicks.HasValue) // { // flagValue = flagValue | DlnaFlags.TimeBasedSeek; @@ -209,6 +211,11 @@ namespace MediaBrowser.Model.Dlna { contentFeatureList.Add(orgOp.TrimStart(';') + orgCi + dlnaflags); } + else if (isDirectStream) + { + // orgOp should be added all the time once the time based seek is resolved for transcoded streams + contentFeatureList.Add("DLNA.ORG_PN=" + orgPn + orgOp + orgCi + dlnaflags); + } else { contentFeatureList.Add("DLNA.ORG_PN=" + orgPn + orgCi + dlnaflags); diff --git a/MediaBrowser.Model/Dlna/DlnaMaps.cs b/MediaBrowser.Model/Dlna/DlnaMaps.cs index 95cd0ac27..4613bc542 100644 --- a/MediaBrowser.Model/Dlna/DlnaMaps.cs +++ b/MediaBrowser.Model/Dlna/DlnaMaps.cs @@ -6,20 +6,6 @@ namespace MediaBrowser.Model.Dlna { public static class DlnaMaps { - private static readonly string DefaultStreaming = - FlagsToString(DlnaFlags.StreamingTransferMode | - DlnaFlags.BackgroundTransferMode | - DlnaFlags.ConnectionStall | - DlnaFlags.ByteBasedSeek | - DlnaFlags.DlnaV15); - - private static readonly string DefaultInteractive = - FlagsToString(DlnaFlags.InteractiveTransferMode | - DlnaFlags.BackgroundTransferMode | - DlnaFlags.ConnectionStall | - DlnaFlags.ByteBasedSeek | - DlnaFlags.DlnaV15); - public static string FlagsToString(DlnaFlags flags) { return string.Format(CultureInfo.InvariantCulture, "{0:X8}{1:D24}", (ulong)flags, 0); diff --git a/MediaBrowser.Model/Dlna/SortCriteria.cs b/MediaBrowser.Model/Dlna/SortCriteria.cs index 7769d0bd3..7fef16e53 100644 --- a/MediaBrowser.Model/Dlna/SortCriteria.cs +++ b/MediaBrowser.Model/Dlna/SortCriteria.cs @@ -1,15 +1,24 @@ #pragma warning disable CS1591 +using System; using Jellyfin.Data.Enums; namespace MediaBrowser.Model.Dlna { public class SortCriteria { - public SortCriteria(string value) + public SortCriteria(string sortOrder) { + if (!string.IsNullOrEmpty(sortOrder) && Enum.TryParse<SortOrder>(sortOrder, true, out var sortOrderValue)) + { + SortOrder = sortOrderValue; + } + else + { + SortOrder = SortOrder.Ascending; + } } - public SortOrder SortOrder => SortOrder.Ascending; + public SortOrder SortOrder { get; } } } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 84d99d550..322cc367b 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -455,7 +455,7 @@ namespace MediaBrowser.Model.Dlna if (directPlayProfile == null) { - _logger.LogInformation( + _logger.LogDebug( "Profile: {0}, No audio direct play profiles found for {1} with codec {2}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path", @@ -682,7 +682,7 @@ namespace MediaBrowser.Model.Dlna bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1); bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1); - _logger.LogInformation( + _logger.LogDebug( "Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path", @@ -1033,7 +1033,7 @@ namespace MediaBrowser.Model.Dlna if (directPlay == null) { - _logger.LogInformation( + _logger.LogDebug( "Container: {Container}, Video: {Video}, Audio: {Audio} cannot be direct played by profile: {Profile} for path: {Path}", container, videoStream?.Codec ?? "no video", @@ -1198,7 +1198,7 @@ namespace MediaBrowser.Model.Dlna private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource) { - _logger.LogInformation( + _logger.LogDebug( "Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}", type, profile.Name ?? "Unknown Profile", @@ -1222,7 +1222,7 @@ namespace MediaBrowser.Model.Dlna if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed) { - _logger.LogInformation("Not eligible for {0} due to unsupported subtitles", playMethod); + _logger.LogDebug("Not eligible for {0} due to unsupported subtitles", playMethod); return (false, TranscodeReason.SubtitleCodecNotSupported); } } @@ -1404,7 +1404,7 @@ namespace MediaBrowser.Model.Dlna if (itemBitrate > requestedMaxBitrate) { - _logger.LogInformation( + _logger.LogDebug( "Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}", playMethod, itemBitrate, diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 4414415a2..cf8465067 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -794,7 +794,7 @@ namespace MediaBrowser.Model.Dlna } // strip spaces to avoid having to encode h264 profile names - list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty))); + list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty, StringComparison.Ordinal))); } if (!item.IsDirectStream) diff --git a/Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs b/MediaBrowser.Model/Dto/DisplayPreferencesDto.cs index 249d828d3..90163ae91 100644 --- a/Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs +++ b/MediaBrowser.Model/Dto/DisplayPreferencesDto.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Jellyfin.Data.Enums; -namespace Jellyfin.Api.Models.DisplayPreferencesDtos +namespace MediaBrowser.Model.Dto { /// <summary> /// Defines the display preferences for any item that supports them (usually Folders). @@ -17,7 +17,7 @@ namespace Jellyfin.Api.Models.DisplayPreferencesDtos PrimaryImageHeight = 250; PrimaryImageWidth = 250; ShowBackdrop = true; - CustomPrefs = new Dictionary<string, string>(); + CustomPrefs = new Dictionary<string, string?>(); } /// <summary> @@ -63,10 +63,10 @@ namespace Jellyfin.Api.Models.DisplayPreferencesDtos public int PrimaryImageWidth { get; set; } /// <summary> - /// Gets the custom prefs. + /// Gets or sets the custom prefs. /// </summary> /// <value>The custom prefs.</value> - public Dictionary<string, string> CustomPrefs { get; } + public Dictionary<string, string?> CustomPrefs { get; set; } /// <summary> /// Gets or sets the scroll direction. diff --git a/MediaBrowser.Model/Entities/DisplayPreferencesDto.cs b/MediaBrowser.Model/Entities/DisplayPreferencesDto.cs deleted file mode 100644 index 1f7fe3030..000000000 --- a/MediaBrowser.Model/Entities/DisplayPreferencesDto.cs +++ /dev/null @@ -1,107 +0,0 @@ -#nullable disable -using System.Collections.Generic; -using Jellyfin.Data.Enums; - -namespace MediaBrowser.Model.Entities -{ - /// <summary> - /// Defines the display preferences for any item that supports them (usually Folders). - /// </summary> - public class DisplayPreferencesDto - { - /// <summary> - /// Initializes a new instance of the <see cref="DisplayPreferencesDto" /> class. - /// </summary> - public DisplayPreferencesDto() - { - RememberIndexing = false; - PrimaryImageHeight = 250; - PrimaryImageWidth = 250; - ShowBackdrop = true; - CustomPrefs = new Dictionary<string, string>(); - } - - /// <summary> - /// Gets or sets the user id. - /// </summary> - /// <value>The user id.</value> - public string Id { get; set; } - - /// <summary> - /// Gets or sets the type of the view. - /// </summary> - /// <value>The type of the view.</value> - public string ViewType { get; set; } - - /// <summary> - /// Gets or sets the sort by. - /// </summary> - /// <value>The sort by.</value> - public string SortBy { get; set; } - - /// <summary> - /// Gets or sets the index by. - /// </summary> - /// <value>The index by.</value> - public string IndexBy { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether [remember indexing]. - /// </summary> - /// <value><c>true</c> if [remember indexing]; otherwise, <c>false</c>.</value> - public bool RememberIndexing { get; set; } - - /// <summary> - /// Gets or sets the height of the primary image. - /// </summary> - /// <value>The height of the primary image.</value> - public int PrimaryImageHeight { get; set; } - - /// <summary> - /// Gets or sets the width of the primary image. - /// </summary> - /// <value>The width of the primary image.</value> - public int PrimaryImageWidth { get; set; } - - /// <summary> - /// Gets or sets the custom prefs. - /// </summary> - /// <value>The custom prefs.</value> - public Dictionary<string, string> CustomPrefs { get; set; } - - /// <summary> - /// Gets or sets the scroll direction. - /// </summary> - /// <value>The scroll direction.</value> - public ScrollDirection ScrollDirection { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether to show backdrops on this item. - /// </summary> - /// <value><c>true</c> if showing backdrops; otherwise, <c>false</c>.</value> - public bool ShowBackdrop { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether [remember sorting]. - /// </summary> - /// <value><c>true</c> if [remember sorting]; otherwise, <c>false</c>.</value> - public bool RememberSorting { get; set; } - - /// <summary> - /// Gets or sets the sort order. - /// </summary> - /// <value>The sort order.</value> - public SortOrder SortOrder { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether [show sidebar]. - /// </summary> - /// <value><c>true</c> if [show sidebar]; otherwise, <c>false</c>.</value> - public bool ShowSidebar { get; set; } - - /// <summary> - /// Gets or sets the client. - /// </summary> - public string Client { get; set; } - } -} diff --git a/MediaBrowser.Model/Entities/ImageType.cs b/MediaBrowser.Model/Entities/ImageType.cs index 6ea9ee419..684b7390a 100644 --- a/MediaBrowser.Model/Entities/ImageType.cs +++ b/MediaBrowser.Model/Entities/ImageType.cs @@ -1,3 +1,5 @@ +using System; + namespace MediaBrowser.Model.Entities { /// <summary> @@ -48,6 +50,10 @@ namespace MediaBrowser.Model.Entities /// <summary> /// The screenshot. /// </summary> + /// <remarks> + /// This enum value is obsolete. + /// XmlSerializer does not serialize/deserialize objects that are marked as [Obsolete]. + /// </remarks> Screenshot = 8, /// <summary> diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 16bc4adf8..70fef5d66 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -29,10 +29,10 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> - <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0-rc.2*" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> + <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" /> <PackageReference Include="System.Globalization" Version="4.3.0" /> - <PackageReference Include="System.Text.Json" Version="6.0.0-rc.2*" /> + <PackageReference Include="System.Text.Json" Version="6.0.0" /> </ItemGroup> <ItemGroup> diff --git a/MediaBrowser.Model/MediaInfo/AudioCodec.cs b/MediaBrowser.Model/MediaInfo/AudioCodec.cs index 8b17757b8..7b83b1b9d 100644 --- a/MediaBrowser.Model/MediaInfo/AudioCodec.cs +++ b/MediaBrowser.Model/MediaInfo/AudioCodec.cs @@ -1,13 +1,11 @@ #pragma warning disable CS1591 +using System; + namespace MediaBrowser.Model.MediaInfo { public static class AudioCodec { - public const string AAC = "aac"; - public const string MP3 = "mp3"; - public const string AC3 = "ac3"; - public static string GetFriendlyName(string codec) { if (codec.Length == 0) @@ -15,17 +13,20 @@ namespace MediaBrowser.Model.MediaInfo return codec; } - switch (codec.ToLowerInvariant()) + if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase)) + { + return "Dolby Digital"; + } + else if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase)) { - case "ac3": - return "Dolby Digital"; - case "eac3": - return "Dolby Digital+"; - case "dca": - return "DTS"; - default: - return codec.ToUpperInvariant(); + return "Dolby Digital+"; } + else if (string.Equals(codec, "dca", StringComparison.OrdinalIgnoreCase)) + { + return "DTS"; + } + + return codec.ToUpperInvariant(); } } } diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs index 36a240706..24eab1a74 100644 --- a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs +++ b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs @@ -16,22 +16,6 @@ namespace MediaBrowser.Model.MediaInfo DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; } - public LiveStreamRequest(AudioOptions options) - { - MaxStreamingBitrate = options.MaxBitrate; - ItemId = options.ItemId; - DeviceProfile = options.Profile; - MaxAudioChannels = options.MaxAudioChannels; - - DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; - - if (options is VideoOptions videoOptions) - { - AudioStreamIndex = videoOptions.AudioStreamIndex; - SubtitleStreamIndex = videoOptions.SubtitleStreamIndex; - } - } - public string OpenToken { get; set; } public Guid UserId { get; set; } diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs deleted file mode 100644 index ecd9b8834..000000000 --- a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs +++ /dev/null @@ -1,58 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; -using MediaBrowser.Model.Dlna; - -namespace MediaBrowser.Model.MediaInfo -{ - public class PlaybackInfoRequest - { - public PlaybackInfoRequest() - { - EnableDirectPlay = true; - EnableDirectStream = true; - EnableTranscoding = true; - AllowVideoStreamCopy = true; - AllowAudioStreamCopy = true; - IsPlayback = true; - DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; - } - - public Guid Id { get; set; } - - public Guid UserId { get; set; } - - public long? MaxStreamingBitrate { get; set; } - - public long? StartTimeTicks { get; set; } - - public int? AudioStreamIndex { get; set; } - - public int? SubtitleStreamIndex { get; set; } - - public int? MaxAudioChannels { get; set; } - - public string MediaSourceId { get; set; } - - public string LiveStreamId { get; set; } - - public DeviceProfile DeviceProfile { get; set; } - - public bool EnableDirectPlay { get; set; } - - public bool EnableDirectStream { get; set; } - - public bool EnableTranscoding { get; set; } - - public bool AllowVideoStreamCopy { get; set; } - - public bool AllowAudioStreamCopy { get; set; } - - public bool IsPlayback { get; set; } - - public bool AutoOpenLiveStream { get; set; } - - public MediaProtocol[] DirectPlayProtocols { get; set; } - } -} diff --git a/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs b/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs index 2bd45695a..9bc5c31f6 100644 --- a/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs +++ b/MediaBrowser.Model/MediaInfo/SubtitleFormat.cs @@ -8,8 +8,6 @@ namespace MediaBrowser.Model.MediaInfo public const string SSA = "ssa"; public const string ASS = "ass"; public const string VTT = "vtt"; - public const string SUB = "sub"; - public const string SMI = "smi"; public const string TTML = "ttml"; } } diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs index 748170a0e..043cee2a2 100644 --- a/MediaBrowser.Model/Net/MimeTypes.cs +++ b/MediaBrowser.Model/Net/MimeTypes.cs @@ -191,7 +191,7 @@ namespace MediaBrowser.Model.Net // Catch-all for all video types that don't require specific mime types if (_videoFileExtensions.Contains(ext)) { - return "video/" + ext.Substring(1); + return string.Concat("video/", ext.AsSpan(1)); } // Type text diff --git a/MediaBrowser.Model/Net/NetworkShareType.cs b/MediaBrowser.Model/Net/NetworkShareType.cs deleted file mode 100644 index 5d985f85d..000000000 --- a/MediaBrowser.Model/Net/NetworkShareType.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MediaBrowser.Model.Net -{ - /// <summary> - /// Enum NetworkShareType. - /// </summary> - public enum NetworkShareType - { - /// <summary> - /// Disk share. - /// </summary> - Disk, - - /// <summary> - /// Printer share. - /// </summary> - Printer, - - /// <summary> - /// Device share. - /// </summary> - Device, - - /// <summary> - /// IPC share. - /// </summary> - Ipc, - - /// <summary> - /// Special share. - /// </summary> - Special - } -} diff --git a/MediaBrowser.Model/Querying/ItemFields.cs b/MediaBrowser.Model/Querying/ItemFields.cs index ef4698f3f..e6c3a6c26 100644 --- a/MediaBrowser.Model/Querying/ItemFields.cs +++ b/MediaBrowser.Model/Querying/ItemFields.cs @@ -1,5 +1,7 @@ #pragma warning disable CS1591 +using System; + namespace MediaBrowser.Model.Querying { /// <summary> @@ -143,6 +145,7 @@ namespace MediaBrowser.Model.Querying /// <summary> /// The screenshot image tags. /// </summary> + [Obsolete("Screenshot image type is no longer used.")] ScreenshotImageTags, SeriesPrimaryImage, diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index 8ded2d144..d2a3344be 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -439,9 +439,6 @@ namespace MediaBrowser.Providers.Manager case ImageType.Backdrop: filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex); break; - case ImageType.Screenshot: - filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex); - break; default: filename = type.ToString().ToLowerInvariant(); break; diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index 39372acb9..b1d73c4c4 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -1,7 +1,5 @@ #nullable disable -#pragma warning disable CA1002, CS1591 - using System; using System.Collections.Generic; using System.IO; @@ -25,6 +23,9 @@ using Microsoft.Extensions.Logging; namespace MediaBrowser.Providers.Manager { + /// <summary> + /// Utilities for managing images attached to items. + /// </summary> public class ItemImageProvider { private readonly ILogger _logger; @@ -47,6 +48,12 @@ namespace MediaBrowser.Providers.Manager ImageType.Thumb }; + /// <summary> + /// Initializes a new instance of the <see cref="ItemImageProvider"/> class. + /// </summary> + /// <param name="logger">The logger.</param> + /// <param name="providerManager">The provider manager for interacting with provider image references.</param> + /// <param name="fileSystem">The filesystem.</param> public ItemImageProvider(ILogger logger, IProviderManager providerManager, IFileSystem fileSystem) { _logger = logger; @@ -54,6 +61,13 @@ namespace MediaBrowser.Providers.Manager _fileSystem = fileSystem; } + /// <summary> + /// Verifies existing images have valid paths and adds any new local images provided. + /// </summary> + /// <param name="item">The <see cref="BaseItem"/> to validate images for.</param> + /// <param name="providers">The providers to use, must include <see cref="ILocalImageProvider"/>(s) for local scanning.</param> + /// <param name="directoryService">The directory service for <see cref="ILocalImageProvider"/>s to use.</param> + /// <returns><c>true</c> if changes were made to the item; otherwise <c>false</c>.</returns> public bool ValidateImages(BaseItem item, IEnumerable<IImageProvider> providers, IDirectoryService directoryService) { var hasChanges = false; @@ -73,6 +87,15 @@ namespace MediaBrowser.Providers.Manager return hasChanges; } + /// <summary> + /// Refreshes from the providers according to the given options. + /// </summary> + /// <param name="item">The <see cref="BaseItem"/> to gather images for.</param> + /// <param name="libraryOptions">The library options.</param> + /// <param name="providers">The providers to query for images.</param> + /// <param name="refreshOptions">The refresh options.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The refresh result.</returns> public async Task<RefreshResult> RefreshImages( BaseItem item, LibraryOptions libraryOptions, @@ -80,14 +103,10 @@ namespace MediaBrowser.Providers.Manager ImageRefreshOptions refreshOptions, CancellationToken cancellationToken) { + var oldBackdropImages = Array.Empty<ItemImageInfo>(); if (refreshOptions.IsReplacingImage(ImageType.Backdrop)) { - ClearImages(item, ImageType.Backdrop); - } - - if (refreshOptions.IsReplacingImage(ImageType.Screenshot)) - { - ClearImages(item, ImageType.Screenshot); + oldBackdropImages = item.GetImages(ImageType.Backdrop).ToArray(); } var result = new RefreshResult { UpdateType = ItemUpdateType.None }; @@ -95,16 +114,15 @@ namespace MediaBrowser.Providers.Manager var typeName = item.GetType().Name; var typeOptions = libraryOptions.GetTypeOptions(typeName) ?? new TypeOptions { Type = typeName }; - // In order to avoid duplicates, only download these if there are none already - var backdropLimit = typeOptions.GetLimit(ImageType.Backdrop); - var screenshotLimit = typeOptions.GetLimit(ImageType.Screenshot); + // track library limits, adding buffer to allow lazy replacing of current images + var backdropLimit = typeOptions.GetLimit(ImageType.Backdrop) + oldBackdropImages.Length; var downloadedImages = new List<ImageType>(); foreach (var provider in providers) { if (provider is IRemoteImageProvider remoteProvider) { - await RefreshFromProvider(item, remoteProvider, refreshOptions, typeOptions, backdropLimit, screenshotLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false); + await RefreshFromProvider(item, remoteProvider, refreshOptions, typeOptions, backdropLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false); continue; } @@ -114,11 +132,17 @@ namespace MediaBrowser.Providers.Manager } } + // only delete existing multi-images if new ones were added + if (oldBackdropImages.Length > 0 && oldBackdropImages.Length < item.GetImages(ImageType.Backdrop).Count()) + { + PruneImages(item, oldBackdropImages); + } + return result; } /// <summary> - /// Refreshes from provider. + /// Refreshes from a dynamic provider. /// </summary> private async Task RefreshFromProvider( BaseItem item, @@ -153,13 +177,14 @@ namespace MediaBrowser.Providers.Manager if (response.Protocol == MediaProtocol.Http) { _logger.LogDebug("Setting image url into item {0}", item.Id); + var index = item.AllowsMultipleImages(imageType) ? item.GetImages(imageType).Count() : 0; item.SetImage( new ItemImageInfo { Path = response.Path, Type = imageType }, - 0); + index); } else { @@ -190,7 +215,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.LogError(ex, "Error in {provider}", provider.Name); + _logger.LogError(ex, "Error in {Provider}", provider.Name); } } @@ -206,9 +231,8 @@ namespace MediaBrowser.Providers.Manager /// <param name="images">The images.</param> /// <param name="savedOptions">The saved options.</param> /// <param name="backdropLimit">The backdrop limit.</param> - /// <param name="screenshotLimit">The screenshot limit.</param> /// <returns><c>true</c> if the specified item contains images; otherwise, <c>false</c>.</returns> - private bool ContainsImages(BaseItem item, List<ImageType> images, TypeOptions savedOptions, int backdropLimit, int screenshotLimit) + private bool ContainsImages(BaseItem item, List<ImageType> images, TypeOptions savedOptions, int backdropLimit) { // Using .Any causes the creation of a DisplayClass aka. variable capture for (var i = 0; i < _singularImages.Length; i++) @@ -225,23 +249,17 @@ namespace MediaBrowser.Providers.Manager return false; } - if (images.Contains(ImageType.Screenshot) && item.GetImages(ImageType.Screenshot).Count() < screenshotLimit) - { - return false; - } - return true; } /// <summary> - /// Refreshes from provider. + /// Refreshes from a remote provider. /// </summary> /// <param name="item">The item.</param> /// <param name="provider">The provider.</param> /// <param name="refreshOptions">The refresh options.</param> /// <param name="savedOptions">The saved options.</param> /// <param name="backdropLimit">The backdrop limit.</param> - /// <param name="screenshotLimit">The screenshot limit.</param> /// <param name="downloadedImages">The downloaded images.</param> /// <param name="result">The result.</param> /// <param name="cancellationToken">The cancellation token.</param> @@ -252,7 +270,6 @@ namespace MediaBrowser.Providers.Manager ImageRefreshOptions refreshOptions, TypeOptions savedOptions, int backdropLimit, - int screenshotLimit, ICollection<ImageType> downloadedImages, RefreshResult result, CancellationToken cancellationToken) @@ -266,7 +283,7 @@ namespace MediaBrowser.Providers.Manager if (!refreshOptions.ReplaceAllImages && refreshOptions.ReplaceImages.Length == 0 && - ContainsImages(item, provider.GetSupportedImages(item).ToList(), savedOptions, backdropLimit, screenshotLimit)) + ContainsImages(item, provider.GetSupportedImages(item).ToList(), savedOptions, backdropLimit)) { return; } @@ -305,13 +322,7 @@ namespace MediaBrowser.Providers.Manager } minWidth = savedOptions.GetMinWidth(ImageType.Backdrop); - await DownloadBackdrops(item, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false); - - if (item is IHasScreenshots hasScreenshots) - { - minWidth = savedOptions.GetMinWidth(ImageType.Screenshot); - await DownloadBackdrops(item, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false); - } + await DownloadMultiImages(item, ImageType.Backdrop, refreshOptions, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -320,7 +331,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.LogError(ex, "Error in {provider}", provider.Name); + _logger.LogError(ex, "Error in {Provider}", provider.Name); } } @@ -329,40 +340,36 @@ namespace MediaBrowser.Providers.Manager return options.IsEnabled(type); } - private void ClearImages(BaseItem item, ImageType type) + private void PruneImages(BaseItem item, ItemImageInfo[] images) { - var deleted = false; - var deletedImages = new List<ItemImageInfo>(); - - foreach (var image in item.GetImages(type)) + for (var i = 0; i < images.Length; i++) { - if (!image.IsLocalFile) - { - deletedImages.Add(image); - continue; - } + var image = images[i]; - try - { - _fileSystem.DeleteFile(image.Path); - deleted = true; - } - catch (FileNotFoundException) + if (image.IsLocalFile) { + try + { + _fileSystem.DeleteFile(image.Path); + } + catch (FileNotFoundException) + { + } } } - item.RemoveImages(deletedImages); - - if (deleted) - { - item.ValidateImages(new DirectoryService(_fileSystem)); - } + item.RemoveImages(images); } + /// <summary> + /// Merges a list of images into the provided item, validating existing images and replacing them or adding new images as necessary. + /// </summary> + /// <param name="item">The <see cref="BaseItem"/> to modify.</param> + /// <param name="images">The new images to place in <c>item</c>.</param> + /// <returns><c>true</c> if changes were made to the item; otherwise <c>false</c>.</returns> public bool MergeImages(BaseItem item, IReadOnlyList<LocalImageInfo> images) { - var changed = false; + var changed = item.ValidateImages(new DirectoryService(_fileSystem)); for (var i = 0; i < _singularImages.Length; i++) { @@ -398,18 +405,6 @@ namespace MediaBrowser.Providers.Manager currentImage.DateModified = newDateModified; } } - else - { - var existing = item.GetImageInfo(type, 0); - if (existing != null) - { - if (existing.IsLocalFile && !File.Exists(existing.Path)) - { - item.RemoveImage(existing); - changed = true; - } - } - } } if (UpdateMultiImages(item, images, ImageType.Backdrop)) @@ -417,15 +412,6 @@ namespace MediaBrowser.Providers.Manager changed = true; } - var hasScreenshots = item as IHasScreenshots; - if (hasScreenshots != null) - { - if (UpdateMultiImages(item, images, ImageType.Screenshot)) - { - changed = true; - } - } - return changed; } @@ -471,7 +457,7 @@ namespace MediaBrowser.Providers.Manager CancellationToken cancellationToken) { var eligibleImages = images - .Where(i => i.Type == type && i.Width >= minWidth) + .Where(i => i.Type == type && (i.Width == null || i.Width >= minWidth)) .ToList(); if (EnableImageStub(item) && eligibleImages.Count > 0) @@ -536,7 +522,7 @@ namespace MediaBrowser.Providers.Manager return true; } - if (item is IItemByName && item is not MusicArtist) + if (item is IItemByName and not MusicArtist) { var hasDualAccess = item as IHasDualAccess; if (hasDualAccess == null || hasDualAccess.IsAccessedByName) @@ -569,7 +555,7 @@ namespace MediaBrowser.Providers.Manager newIndex); } - private async Task DownloadBackdrops(BaseItem item, ImageType imageType, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken) + private async Task DownloadMultiImages(BaseItem item, ImageType imageType, ImageRefreshOptions refreshOptions, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken) { foreach (var image in images.Where(i => i.Type == imageType)) { @@ -609,8 +595,8 @@ namespace MediaBrowser.Providers.Manager break; } - // If there's already an image of the same size, skip it - if (response.Content.Headers.ContentLength.HasValue) + // If there's already an image of the same file size, skip it unless doing a full refresh + if (response.Content.Headers.ContentLength.HasValue && !refreshOptions.IsReplacingImage(imageType)) { try { diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index ffb3baeb1..90d14a973 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -713,7 +713,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.LogError(ex, "Error in {provider}", provider.Name); + Logger.LogError(ex, "Error in {Provider}", provider.Name); // If a local provider fails, consider that a failure refreshResult.ErrorMessage = ex.Message; @@ -785,7 +785,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { refreshResult.ErrorMessage = ex.Message; - Logger.LogError(ex, "Error in {provider}", provider.Name); + Logger.LogError(ex, "Error in {Provider}", provider.Name); } } @@ -837,7 +837,7 @@ namespace MediaBrowser.Providers.Manager { refreshResult.Failures++; refreshResult.ErrorMessage = ex.Message; - Logger.LogError(ex, "Error in {provider}", provider.Name); + Logger.LogError(ex, "Error in {Provider}", provider.Name); } } diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 9d0a6944b..b42112111 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -16,9 +16,9 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-rc.2*" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" /> <PackageReference Include="PlaylistsNET" Version="1.1.3" /> diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs index 8c81b08db..b4b1895f5 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs @@ -1,7 +1,5 @@ #nullable disable -#pragma warning disable CA1002, CS1591 - using System; using System.Collections.Generic; using System.Globalization; @@ -13,7 +11,9 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; @@ -21,38 +21,49 @@ using MediaBrowser.Model.IO; namespace MediaBrowser.Providers.MediaInfo { /// <summary> - /// Uses ffmpeg to create video images. + /// Uses <see cref="IMediaEncoder"/> to extract embedded images. /// </summary> public class AudioImageProvider : IDynamicImageProvider { + private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaEncoder _mediaEncoder; private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; - public AudioImageProvider(IMediaEncoder mediaEncoder, IServerConfigurationManager config, IFileSystem fileSystem) + /// <summary> + /// Initializes a new instance of the <see cref="AudioImageProvider"/> class. + /// </summary> + /// <param name="mediaSourceManager">The media source manager for fetching item streams.</param> + /// <param name="mediaEncoder">The media encoder for extracting embedded images.</param> + /// <param name="config">The server configuration manager for getting image paths.</param> + /// <param name="fileSystem">The filesystem.</param> + public AudioImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerConfigurationManager config, IFileSystem fileSystem) { + _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; _config = config; _fileSystem = fileSystem; } - public string AudioImagesPath => Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images"); + private string AudioImagesPath => Path.Combine(_config.ApplicationPaths.CachePath, "extracted-audio-images"); + /// <inheritdoc /> public string Name => "Image Extractor"; + /// <inheritdoc /> public IEnumerable<ImageType> GetSupportedImages(BaseItem item) { - return new List<ImageType> { ImageType.Primary }; + return new[] { ImageType.Primary }; } + /// <inheritdoc /> public Task<DynamicImageResponse> GetImage(BaseItem item, ImageType type, CancellationToken cancellationToken) { - var audio = (Audio)item; - - var imageStreams = - audio.GetMediaStreams(MediaStreamType.EmbeddedImage) - .Where(i => i.Type == MediaStreamType.EmbeddedImage) - .ToList(); + var imageStreams = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery + { + ItemId = item.Id, + Type = MediaStreamType.EmbeddedImage + }); // Can't extract if we didn't find a video stream in the file if (imageStreams.Count == 0) @@ -63,7 +74,7 @@ namespace MediaBrowser.Providers.MediaInfo return GetImage((Audio)item, imageStreams, cancellationToken); } - public async Task<DynamicImageResponse> GetImage(Audio item, List<MediaStream> imageStreams, CancellationToken cancellationToken) + private async Task<DynamicImageResponse> GetImage(Audio item, List<MediaStream> imageStreams, CancellationToken cancellationToken) { var path = GetAudioImagePath(item); @@ -75,7 +86,7 @@ namespace MediaBrowser.Providers.MediaInfo imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ?? imageStreams.FirstOrDefault(); - var imageStreamIndex = imageStream == null ? (int?)null : imageStream.Index; + var imageStreamIndex = imageStream?.Index; var tempFile = await _mediaEncoder.ExtractAudioImage(item.Path, imageStreamIndex, cancellationToken).ConfigureAwait(false); @@ -127,6 +138,7 @@ namespace MediaBrowser.Providers.MediaInfo return Path.Join(AudioImagesPath, prefix, filename); } + /// <inheritdoc /> public bool Supports(BaseItem item) { if (item.IsShortcut) diff --git a/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs b/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs index c41d36d76..96d7d139a 100644 --- a/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/EmbeddedImageProvider.cs @@ -8,13 +8,16 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Providers.MediaInfo { @@ -44,15 +47,21 @@ namespace MediaBrowser.Providers.MediaInfo "logo", }; + private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaEncoder _mediaEncoder; + private readonly ILogger<EmbeddedImageProvider> _logger; /// <summary> /// Initializes a new instance of the <see cref="EmbeddedImageProvider"/> class. /// </summary> + /// <param name="mediaSourceManager">The media source manager for fetching item streams and attachments.</param> /// <param name="mediaEncoder">The media encoder for extracting attached/embedded images.</param> - public EmbeddedImageProvider(IMediaEncoder mediaEncoder) + /// <param name="logger">The logger.</param> + public EmbeddedImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ILogger<EmbeddedImageProvider> logger) { + _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; + _logger = logger; } /// <inheritdoc /> @@ -114,22 +123,31 @@ namespace MediaBrowser.Providers.MediaInfo ImageType.Primary => _primaryImageFileNames, ImageType.Backdrop => _backdropImageFileNames, ImageType.Logo => _logoImageFileNames, - _ => _primaryImageFileNames + _ => Array.Empty<string>() }; + if (imageFileNames.Length == 0) + { + _logger.LogWarning("Attempted to load unexpected image type: {Type}", type); + return new DynamicImageResponse { HasImage = false }; + } + // Try attachments first - var attachmentStream = item.GetMediaSources(false) - .SelectMany(source => source.MediaAttachments) + var attachmentStream = _mediaSourceManager.GetMediaAttachments(item.Id) .FirstOrDefault(attachment => !string.IsNullOrEmpty(attachment.FileName) && imageFileNames.Any(name => attachment.FileName.Contains(name, StringComparison.OrdinalIgnoreCase))); if (attachmentStream != null) { - return await ExtractAttachment(item, cancellationToken, attachmentStream, mediaSource); + return await ExtractAttachment(item, attachmentStream, mediaSource, cancellationToken); } // Fall back to EmbeddedImage streams - var imageStreams = item.GetMediaStreams().FindAll(i => i.Type == MediaStreamType.EmbeddedImage); + var imageStreams = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery + { + ItemId = item.Id, + Type = MediaStreamType.EmbeddedImage + }); if (imageStreams.Count == 0) { @@ -156,20 +174,28 @@ namespace MediaBrowser.Providers.MediaInfo } } + var format = imageStream.Codec switch + { + "mjpeg" => ImageFormat.Jpg, + "png" => ImageFormat.Png, + "gif" => ImageFormat.Gif, + _ => ImageFormat.Jpg + }; + string extractedImagePath = - await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, imageStream, imageStream.Index, ".jpg", cancellationToken) + await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, imageStream, imageStream.Index, format, cancellationToken) .ConfigureAwait(false); return new DynamicImageResponse { - Format = ImageFormat.Jpg, + Format = format, HasImage = true, Path = extractedImagePath, Protocol = MediaProtocol.File }; } - private async Task<DynamicImageResponse> ExtractAttachment(Video item, CancellationToken cancellationToken, MediaAttachment attachmentStream, MediaSourceInfo mediaSource) + private async Task<DynamicImageResponse> ExtractAttachment(Video item, MediaAttachment attachmentStream, MediaSourceInfo mediaSource, CancellationToken cancellationToken) { var extension = string.IsNullOrEmpty(attachmentStream.MimeType) ? Path.GetExtension(attachmentStream.FileName) @@ -180,10 +206,6 @@ namespace MediaBrowser.Providers.MediaInfo extension = ".jpg"; } - string extractedAttachmentPath = - await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, null, attachmentStream.Index, extension, cancellationToken) - .ConfigureAwait(false); - ImageFormat format = extension switch { ".bmp" => ImageFormat.Bmp, @@ -194,6 +216,10 @@ namespace MediaBrowser.Providers.MediaInfo _ => ImageFormat.Jpg }; + string extractedAttachmentPath = + await _mediaEncoder.ExtractVideoImage(item.Path, item.Container, mediaSource, null, attachmentStream.Index, format, cancellationToken) + .ConfigureAwait(false); + return new DynamicImageResponse { Format = format, diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs index dd4a5f061..ba284187e 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs @@ -1,7 +1,3 @@ -#nullable disable - -#pragma warning disable CA1002, CS1591 - using System; using System.Collections.Generic; using System.IO; @@ -12,15 +8,30 @@ using MediaBrowser.Model.Globalization; namespace MediaBrowser.Providers.MediaInfo { + /// <summary> + /// Resolves external subtitles for videos. + /// </summary> public class SubtitleResolver { private readonly ILocalizationManager _localization; + /// <summary> + /// Initializes a new instance of the <see cref="SubtitleResolver"/> class. + /// </summary> + /// <param name="localization">The localization manager.</param> public SubtitleResolver(ILocalizationManager localization) { _localization = localization; } + /// <summary> + /// Retrieves the external subtitle streams for the provided video. + /// </summary> + /// <param name="video">The video to search from.</param> + /// <param name="startIndex">The stream index to start adding subtitle streams at.</param> + /// <param name="directoryService">The directory service to search for files.</param> + /// <param name="clearCache">True if the directory service cache should be cleared before searching.</param> + /// <returns>The external subtitle streams located.</returns> public List<MediaStream> GetExternalSubtitleStreams( Video video, int startIndex, @@ -56,6 +67,13 @@ namespace MediaBrowser.Providers.MediaInfo return streams; } + /// <summary> + /// Locates the external subtitle files for the provided video. + /// </summary> + /// <param name="video">The video to search from.</param> + /// <param name="directoryService">The directory service to search for files.</param> + /// <param name="clearCache">True if the directory service cache should be cleared before searching.</param> + /// <returns>The external subtitle file paths located.</returns> public IEnumerable<string> GetExternalSubtitleFiles( Video video, IDirectoryService directoryService, @@ -74,6 +92,13 @@ namespace MediaBrowser.Providers.MediaInfo } } + /// <summary> + /// Extracts the subtitle files from the provided list and adds them to the list of streams. + /// </summary> + /// <param name="streams">The list of streams to add external subtitles to.</param> + /// <param name="videoPath">The path to the video file.</param> + /// <param name="startIndex">The stream index to start adding subtitle streams at.</param> + /// <param name="files">The files to add if they are subtitles.</param> public void AddExternalSubtitleStreams( List<MediaStream> streams, string videoPath, @@ -120,6 +145,12 @@ namespace MediaBrowser.Providers.MediaInfo while (languageSpan.Length > 0) { var lastDot = languageSpan.LastIndexOf('.'); + if (lastDot < videoFileNameWithoutExtension.Length) + { + languageSpan = ReadOnlySpan<char>.Empty; + break; + } + var currentSlice = languageSpan[lastDot..]; if (currentSlice.Equals(".default", StringComparison.OrdinalIgnoreCase) || currentSlice.Equals(".forced", StringComparison.OrdinalIgnoreCase) @@ -133,12 +164,19 @@ namespace MediaBrowser.Providers.MediaInfo break; } - // Try to translate to three character code - // Be flexible and check against both the full and three character versions var language = languageSpan.ToString(); - var culture = _localization.FindLanguageInfo(language); + if (string.IsNullOrWhiteSpace(language)) + { + language = null; + } + else + { + // Try to translate to three character code + // Be flexible and check against both the full and three character versions + var culture = _localization.FindLanguageInfo(language); - language = culture == null ? language : culture.ThreeLetterISOLanguageName; + language = culture == null ? language : culture.ThreeLetterISOLanguageName; + } mediaStream = new MediaStream { diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index d226182c0..d4bf62970 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -4,7 +4,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; @@ -19,16 +21,19 @@ namespace MediaBrowser.Providers.MediaInfo /// </summary> public class VideoImageProvider : IDynamicImageProvider, IHasOrder { + private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaEncoder _mediaEncoder; private readonly ILogger<VideoImageProvider> _logger; /// <summary> /// Initializes a new instance of the <see cref="VideoImageProvider"/> class. /// </summary> + /// <param name="mediaSourceManager">The media source manager for fetching item streams.</param> /// <param name="mediaEncoder">The media encoder for capturing images.</param> /// <param name="logger">The logger.</param> - public VideoImageProvider(IMediaEncoder mediaEncoder, ILogger<VideoImageProvider> logger) + public VideoImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ILogger<VideoImageProvider> logger) { + _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; _logger = logger; } @@ -78,12 +83,18 @@ namespace MediaBrowser.Providers.MediaInfo // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in. // Always use 10 seconds for dvd because our duration could be out of whack - var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue && - item.RunTimeTicks.Value > 0 + var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks > 0 ? TimeSpan.FromTicks(item.RunTimeTicks.Value / 10) : TimeSpan.FromSeconds(10); - var videoStream = item.GetDefaultVideoStream() ?? item.GetMediaStreams().FirstOrDefault(i => i.Type == MediaStreamType.Video); + var query = new MediaStreamQuery { ItemId = item.Id, Index = item.DefaultVideoStreamIndex }; + var videoStream = _mediaSourceManager.GetMediaStreams(query).FirstOrDefault(); + if (videoStream == null) + { + query.Type = MediaStreamType.Video; + query.Index = null; + videoStream = _mediaSourceManager.GetMediaStreams(query).FirstOrDefault(); + } if (videoStream == null) { diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs index 5559b9db6..8a32cb07c 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs @@ -319,6 +319,12 @@ namespace MediaBrowser.Providers.Music { case "name-credit": { + if (reader.IsEmptyElement) + { + reader.Read(); + break; + } + using var subReader = reader.ReadSubtree(); return ParseArtistNameCredit(subReader); } @@ -355,6 +361,12 @@ namespace MediaBrowser.Providers.Music { case "artist": { + if (reader.IsEmptyElement) + { + reader.Read(); + break; + } + var id = reader.GetAttribute("id"); using var subReader = reader.ReadSubtree(); return ParseArtistArtistCredit(subReader, id); @@ -457,8 +469,8 @@ namespace MediaBrowser.Providers.Music }; using var reader = XmlReader.Create(oReader, settings); - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -471,7 +483,7 @@ namespace MediaBrowser.Providers.Music { if (reader.IsEmptyElement) { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); continue; } @@ -481,14 +493,14 @@ namespace MediaBrowser.Providers.Music default: { - reader.Skip(); + await reader.SkipAsync().ConfigureAwait(false); break; } } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } @@ -755,6 +767,12 @@ namespace MediaBrowser.Providers.Music case "artist-credit": { + if (reader.IsEmptyElement) + { + reader.Read(); + break; + } + using var subReader = reader.ReadSubtree(); var artist = ParseArtistCredit(subReader); diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs index f67ac6ede..d8b33a799 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -17,24 +16,17 @@ namespace MediaBrowser.Providers.Plugins.Omdb { public class OmdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder { - private readonly IHttpClientFactory _httpClientFactory; private readonly OmdbItemProvider _itemProvider; - private readonly IFileSystem _fileSystem; - private readonly IServerConfigurationManager _configurationManager; - private readonly IApplicationHost _appHost; + private readonly OmdbProvider _omdbProvider; public OmdbEpisodeProvider( - IApplicationHost appHost, IHttpClientFactory httpClientFactory, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { - _httpClientFactory = httpClientFactory; - _fileSystem = fileSystem; - _configurationManager = configurationManager; - _appHost = appHost; - _itemProvider = new OmdbItemProvider(_appHost, httpClientFactory, libraryManager, fileSystem, configurationManager); + _itemProvider = new OmdbItemProvider(httpClientFactory, libraryManager, fileSystem, configurationManager); + _omdbProvider = new OmdbProvider(httpClientFactory, fileSystem, configurationManager); } // After TheTvDb @@ -44,12 +36,12 @@ namespace MediaBrowser.Providers.Plugins.Omdb public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken) { - return _itemProvider.GetSearchResults(searchInfo, "episode", cancellationToken); + return _itemProvider.GetSearchResults(searchInfo, cancellationToken); } public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo info, CancellationToken cancellationToken) { - var result = new MetadataResult<Episode>() + var result = new MetadataResult<Episode> { Item = new Episode(), QueriedById = true @@ -61,13 +53,20 @@ namespace MediaBrowser.Providers.Plugins.Omdb return result; } - if (info.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string? seriesImdbId) && !string.IsNullOrEmpty(seriesImdbId)) + if (info.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string? seriesImdbId) + && !string.IsNullOrEmpty(seriesImdbId) + && info.IndexNumber.HasValue + && info.ParentIndexNumber.HasValue) { - if (info.IndexNumber.HasValue && info.ParentIndexNumber.HasValue) - { - result.HasMetadata = await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager) - .FetchEpisodeData(result, info.IndexNumber.Value, info.ParentIndexNumber.Value, info.GetProviderId(MetadataProvider.Imdb), seriesImdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); - } + result.HasMetadata = await _omdbProvider.FetchEpisodeData( + result, + info.IndexNumber.Value, + info.ParentIndexNumber.Value, + info.GetProviderId(MetadataProvider.Imdb), + seriesImdbId, + info.MetadataLanguage, + info.MetadataCountryCode, + cancellationToken).ConfigureAwait(false); } return result; diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs index fa82089c8..4c3fc23b2 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs @@ -2,12 +2,12 @@ #pragma warning disable CS1591 +using System; using System.Collections.Generic; -using System.Globalization; +using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -23,16 +23,12 @@ namespace MediaBrowser.Providers.Plugins.Omdb public class OmdbImageProvider : IRemoteImageProvider, IHasOrder { private readonly IHttpClientFactory _httpClientFactory; - private readonly IFileSystem _fileSystem; - private readonly IServerConfigurationManager _configurationManager; - private readonly IApplicationHost _appHost; + private readonly OmdbProvider _omdbProvider; - public OmdbImageProvider(IApplicationHost appHost, IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager) + public OmdbImageProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { _httpClientFactory = httpClientFactory; - _fileSystem = fileSystem; - _configurationManager = configurationManager; - _appHost = appHost; + _omdbProvider = new OmdbProvider(_httpClientFactory, fileSystem, configurationManager); } public string Name => "The Open Movie Database"; @@ -52,38 +48,27 @@ namespace MediaBrowser.Providers.Plugins.Omdb public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken) { var imdbId = item.GetProviderId(MetadataProvider.Imdb); + if (string.IsNullOrWhiteSpace(imdbId)) + { + return Enumerable.Empty<RemoteImageInfo>(); + } - var list = new List<RemoteImageInfo>(); - - var provider = new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager); + var rootObject = await _omdbProvider.GetRootObject(imdbId, cancellationToken).ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(imdbId)) + if (string.IsNullOrEmpty(rootObject.Poster)) { - var rootObject = await provider.GetRootObject(imdbId, cancellationToken).ConfigureAwait(false); + return Enumerable.Empty<RemoteImageInfo>(); + } - if (!string.IsNullOrEmpty(rootObject.Poster)) + // the poster url is sometimes higher quality than the poster api + return new[] + { + new RemoteImageInfo { - if (item is Episode) - { - // img.omdbapi.com is returning 404's - list.Add(new RemoteImageInfo - { - ProviderName = Name, - Url = rootObject.Poster - }); - } - else - { - list.Add(new RemoteImageInfo - { - ProviderName = Name, - Url = string.Format(CultureInfo.InvariantCulture, "https://img.omdbapi.com/?i={0}&apikey=2c9d9507", imdbId) - }); - } + ProviderName = Name, + Url = rootObject.Poster } - } - - return list; + }; } public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 2409993a2..e5753b2b5 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -8,11 +8,11 @@ using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Extensions.Json; -using MediaBrowser.Common; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -31,13 +31,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb { private readonly IHttpClientFactory _httpClientFactory; private readonly ILibraryManager _libraryManager; - private readonly IFileSystem _fileSystem; - private readonly IServerConfigurationManager _configurationManager; - private readonly IApplicationHost _appHost; private readonly JsonSerializerOptions _jsonOptions; + private readonly OmdbProvider _omdbProvider; public OmdbItemProvider( - IApplicationHost appHost, IHttpClientFactory httpClientFactory, ILibraryManager libraryManager, IFileSystem fileSystem, @@ -45,9 +42,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { _httpClientFactory = httpClientFactory; _libraryManager = libraryManager; - _fileSystem = fileSystem; - _configurationManager = configurationManager; - _appHost = appHost; + _omdbProvider = new OmdbProvider(_httpClientFactory, fileSystem, configurationManager); _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); @@ -59,185 +54,166 @@ namespace MediaBrowser.Providers.Plugins.Omdb // After primary option public int Order => 2; + public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(TrailerInfo searchInfo, CancellationToken cancellationToken) + { + return GetSearchResultsInternal(searchInfo, true, cancellationToken); + } + public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken) { - return GetSearchResults(searchInfo, "series", cancellationToken); + return GetSearchResultsInternal(searchInfo, true, cancellationToken); } public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken) { - return GetSearchResults(searchInfo, "movie", cancellationToken); + return GetSearchResultsInternal(searchInfo, true, cancellationToken); } - public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ItemLookupInfo searchInfo, string type, CancellationToken cancellationToken) + public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken) { - return GetSearchResultsInternal(searchInfo, type, true, cancellationToken); + return GetSearchResultsInternal(searchInfo, true, cancellationToken); } - private async Task<IEnumerable<RemoteSearchResult>> GetSearchResultsInternal(ItemLookupInfo searchInfo, string type, bool isSearch, CancellationToken cancellationToken) + private async Task<IEnumerable<RemoteSearchResult>> GetSearchResultsInternal(ItemLookupInfo searchInfo, bool isSearch, CancellationToken cancellationToken) { + var type = searchInfo switch + { + EpisodeInfo => "episode", + SeriesInfo => "series", + _ => "movie" + }; + + // This is a bit hacky? var episodeSearchInfo = searchInfo as EpisodeInfo; + var indexNumberEnd = episodeSearchInfo?.IndexNumberEnd; var imdbId = searchInfo.GetProviderId(MetadataProvider.Imdb); - var urlQuery = "plot=full&r=json"; - if (type == "episode" && episodeSearchInfo != null) + var urlQuery = new StringBuilder("plot=full&r=json"); + if (episodeSearchInfo != null) { episodeSearchInfo.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out imdbId); - } - - var name = searchInfo.Name; - var year = searchInfo.Year; + if (searchInfo.IndexNumber.HasValue) + { + urlQuery.Append("&Episode=").Append(searchInfo.IndexNumber.Value); + } - if (!string.IsNullOrWhiteSpace(name)) - { - var parsedName = _libraryManager.ParseName(name); - var yearInName = parsedName.Year; - name = parsedName.Name; - year ??= yearInName; + if (searchInfo.ParentIndexNumber.HasValue) + { + urlQuery.Append("&Season=").Append(searchInfo.ParentIndexNumber.Value); + } } if (string.IsNullOrWhiteSpace(imdbId)) { - if (year.HasValue) + var name = searchInfo.Name; + var year = searchInfo.Year; + if (!string.IsNullOrWhiteSpace(name)) { - urlQuery += "&y=" + year.Value.ToString(CultureInfo.InvariantCulture); + var parsedName = _libraryManager.ParseName(name); + var yearInName = parsedName.Year; + name = parsedName.Name; + year ??= yearInName; } - // &s means search and returns a list of results as opposed to t - if (isSearch) - { - urlQuery += "&s=" + WebUtility.UrlEncode(name); - } - else + if (year.HasValue) { - urlQuery += "&t=" + WebUtility.UrlEncode(name); + urlQuery.Append("&y=").Append(year); } - urlQuery += "&type=" + type; + // &s means search and returns a list of results as opposed to t + urlQuery.Append(isSearch ? "&s=" : "&t="); + urlQuery.Append(WebUtility.UrlEncode(name)); + urlQuery.Append("&type=") + .Append(type); } else { - urlQuery += "&i=" + imdbId; + urlQuery.Append("&i=") + .Append(imdbId); isSearch = false; } - if (type == "episode") - { - if (searchInfo.IndexNumber.HasValue) - { - urlQuery += string.Format(CultureInfo.InvariantCulture, "&Episode={0}", searchInfo.IndexNumber); - } - - if (searchInfo.ParentIndexNumber.HasValue) - { - urlQuery += string.Format(CultureInfo.InvariantCulture, "&Season={0}", searchInfo.ParentIndexNumber); - } - } - - var url = OmdbProvider.GetOmdbUrl(urlQuery); + var url = OmdbProvider.GetOmdbUrl(urlQuery.ToString()); - using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); + using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var resultList = new List<SearchResult>(); if (isSearch) { var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); - if (searchResultList != null && searchResultList.Search != null) + if (searchResultList?.Search != null) { - resultList.AddRange(searchResultList.Search); + var resultCount = searchResultList.Search.Count; + var result = new RemoteSearchResult[resultCount]; + for (var i = 0; i < resultCount; i++) + { + result[i] = ResultToMetadataResult(searchResultList.Search[i], searchInfo, indexNumberEnd); + } + + return result; } } else { var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); - if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(result?.Response, "true", StringComparison.OrdinalIgnoreCase)) { - resultList.Add(result); + return new[] { ResultToMetadataResult(result, searchInfo, indexNumberEnd) }; } } - return resultList.Select(result => - { - var item = new RemoteSearchResult - { - IndexNumber = searchInfo.IndexNumber, - Name = result.Title, - ParentIndexNumber = searchInfo.ParentIndexNumber, - SearchProviderName = Name - }; - - if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue) - { - item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value; - } - - item.SetProviderId(MetadataProvider.Imdb, result.imdbID); - - if (result.Year.Length > 0 - && int.TryParse(result.Year.AsSpan().Slice(0, Math.Min(result.Year.Length, 4)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear)) - { - item.ProductionYear = parsedYear; - } - - if (!string.IsNullOrEmpty(result.Released) - && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var released)) - { - item.PremiereDate = released; - } - - if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase)) - { - item.ImageUrl = result.Poster; - } - - return item; - }); + return Enumerable.Empty<RemoteSearchResult>(); } public Task<MetadataResult<Trailer>> GetMetadata(TrailerInfo info, CancellationToken cancellationToken) { - return GetMovieResult<Trailer>(info, cancellationToken); + return GetResult<Trailer>(info, cancellationToken); } - public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(TrailerInfo searchInfo, CancellationToken cancellationToken) + public Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken) { - return GetSearchResults(searchInfo, "movie", cancellationToken); + return GetResult<Series>(info, cancellationToken); } - public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken) + public Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken) { - var result = new MetadataResult<Series> + return GetResult<Movie>(info, cancellationToken); + } + + private RemoteSearchResult ResultToMetadataResult(SearchResult result, ItemLookupInfo searchInfo, int? indexNumberEnd) + { + var item = new RemoteSearchResult { - Item = new Series(), - QueriedById = true + IndexNumber = searchInfo.IndexNumber, + Name = result.Title, + ParentIndexNumber = searchInfo.ParentIndexNumber, + SearchProviderName = Name, + IndexNumberEnd = indexNumberEnd }; - var imdbId = info.GetProviderId(MetadataProvider.Imdb); - if (string.IsNullOrWhiteSpace(imdbId)) + item.SetProviderId(MetadataProvider.Imdb, result.imdbID); + + if (OmdbProvider.TryParseYear(result.Year, out var parsedYear)) { - imdbId = await GetSeriesImdbId(info, cancellationToken).ConfigureAwait(false); - result.QueriedById = false; + item.ProductionYear = parsedYear; } - if (!string.IsNullOrEmpty(imdbId)) + if (!string.IsNullOrEmpty(result.Released) + && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var released)) { - result.Item.SetProviderId(MetadataProvider.Imdb, imdbId); - result.HasMetadata = true; - - await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); + item.PremiereDate = released; } - return result; - } + if (!string.IsNullOrWhiteSpace(result.Poster)) + { + item.ImageUrl = result.Poster; + } - public Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken) - { - return GetMovieResult<Movie>(info, cancellationToken); + return item; } - private async Task<MetadataResult<T>> GetMovieResult<T>(ItemLookupInfo info, CancellationToken cancellationToken) + private async Task<MetadataResult<T>> GetResult<T>(ItemLookupInfo info, CancellationToken cancellationToken) where T : BaseItem, new() { var result = new MetadataResult<T> @@ -249,7 +225,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var imdbId = info.GetProviderId(MetadataProvider.Imdb); if (string.IsNullOrWhiteSpace(imdbId)) { - imdbId = await GetMovieImdbId(info, cancellationToken).ConfigureAwait(false); + imdbId = await GetImdbId(info, cancellationToken).ConfigureAwait(false); result.QueriedById = false; } @@ -258,22 +234,15 @@ namespace MediaBrowser.Providers.Plugins.Omdb result.Item.SetProviderId(MetadataProvider.Imdb, imdbId); result.HasMetadata = true; - await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); + await _omdbProvider.Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); } return result; } - private async Task<string> GetMovieImdbId(ItemLookupInfo info, CancellationToken cancellationToken) - { - var results = await GetSearchResultsInternal(info, "movie", false, cancellationToken).ConfigureAwait(false); - var first = results.FirstOrDefault(); - return first?.GetProviderId(MetadataProvider.Imdb); - } - - private async Task<string> GetSeriesImdbId(SeriesInfo info, CancellationToken cancellationToken) + private async Task<string> GetImdbId(ItemLookupInfo info, CancellationToken cancellationToken) { - var results = await GetSearchResultsInternal(info, "series", false, cancellationToken).ConfigureAwait(false); + var results = await GetSearchResultsInternal(info, false, cancellationToken).ConfigureAwait(false); var first = results.FirstOrDefault(); return first?.GetProviderId(MetadataProvider.Imdb); } diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 816a882b4..12ea2d55b 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -4,15 +4,16 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; +using System.Net.Http.Json; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Extensions.Json; -using MediaBrowser.Common; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -28,24 +29,22 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IFileSystem _fileSystem; private readonly IServerConfigurationManager _configurationManager; private readonly IHttpClientFactory _httpClientFactory; - private readonly IApplicationHost _appHost; private readonly JsonSerializerOptions _jsonOptions; /// <summary>Initializes a new instance of the <see cref="OmdbProvider"/> class.</summary> /// <param name="httpClientFactory">HttpClientFactory to use for calls to OMDB service.</param> /// <param name="fileSystem">IFileSystem to use for store OMDB data.</param> - /// <param name="appHost">IApplicationHost to use.</param> /// <param name="configurationManager">IServerConfigurationManager to use.</param> - public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager) + public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { _httpClientFactory = httpClientFactory; _fileSystem = fileSystem; _configurationManager = configurationManager; - _appHost = appHost; _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options); - _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); - _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); + // These converters need to take priority + _jsonOptions.Converters.Insert(0, new JsonOmdbNotAvailableStringConverter()); + _jsonOptions.Converters.Insert(0, new JsonOmdbNotAvailableInt32Converter()); } /// <summary>Fetches data from OMDB service.</summary> @@ -68,8 +67,9 @@ namespace MediaBrowser.Providers.Plugins.Omdb var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false); + var isEnglishRequested = IsConfiguredForEnglish(item, language); // Only take the name and rating if the user's language is set to English, since Omdb has no localization - if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport) + if (isEnglishRequested) { item.Name = result.Title; @@ -79,9 +79,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4 - && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, CultureInfo.InvariantCulture, out var year) - && year >= 0) + if (TryParseYear(result.Year, out var year)) { item.ProductionYear = year; } @@ -117,7 +115,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb item.SetProviderId(MetadataProvider.Imdb, result.imdbID); } - ParseAdditionalMetadata(itemResult, result); + ParseAdditionalMetadata(itemResult, result, isEnglishRequested); } /// <summary>Gets data about an episode.</summary> @@ -180,8 +178,9 @@ namespace MediaBrowser.Providers.Plugins.Omdb return false; } + var isEnglishRequested = IsConfiguredForEnglish(item, language); // Only take the name and rating if the user's language is set to English, since Omdb has no localization - if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport) + if (isEnglishRequested) { item.Name = result.Title; @@ -191,9 +190,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4 - && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, CultureInfo.InvariantCulture, out var year) - && year >= 0) + if (TryParseYear(result.Year, out var year)) { item.ProductionYear = year; } @@ -229,7 +226,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb item.SetProviderId(MetadataProvider.Imdb, result.imdbID); } - ParseAdditionalMetadata(itemResult, result); + ParseAdditionalMetadata(itemResult, result, isEnglishRequested); return true; } @@ -263,6 +260,30 @@ namespace MediaBrowser.Providers.Plugins.Omdb return Url + "&" + query; } + /// <summary> + /// Extract the year from a string. + /// </summary> + /// <param name="input">The input string.</param> + /// <param name="year">The year.</param> + /// <returns>A value indicating whether the input could successfully be parsed as a year.</returns> + public static bool TryParseYear(string input, [NotNullWhen(true)] out int? year) + { + if (string.IsNullOrEmpty(input)) + { + year = 0; + return false; + } + + if (int.TryParse(input.AsSpan(0, 4), NumberStyles.Number, CultureInfo.InvariantCulture, out var result)) + { + year = result; + return true; + } + + year = 0; + return false; + } + private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(imdbId)) @@ -295,7 +316,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb "i={0}&plot=short&tomatoes=true&r=json", imdbParam)); - var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); + var rootObject = await _httpClientFactory.CreateClient(NamedClient.Default).GetFromJsonAsync<RootObject>(url, _jsonOptions, cancellationToken).ConfigureAwait(false); await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); @@ -335,37 +356,13 @@ namespace MediaBrowser.Providers.Plugins.Omdb imdbParam, seasonId)); - var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); + var rootObject = await _httpClientFactory.CreateClient(NamedClient.Default).GetFromJsonAsync<SeasonRootObject>(url, _jsonOptions, cancellationToken).ConfigureAwait(false); await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); return path; } - /// <summary>Gets response from OMDB service as type T.</summary> - /// <param name="httpClient">HttpClient instance to use for service call.</param> - /// <param name="url">Http URL to use for service call.</param> - /// <param name="cancellationToken">CancellationToken to use for service call.</param> - /// <typeparam name="T">The first generic type parameter.</typeparam> - /// <returns>OMDB service response as type T.</returns> - public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken) - { - using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); - await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - - return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false); - } - - /// <summary>Gets response from OMDB service.</summary> - /// <param name="httpClient">HttpClient instance to use for service call.</param> - /// <param name="url">Http URL to use for service call.</param> - /// <param name="cancellationToken">CancellationToken to use for service call.</param> - /// <returns>OMDB service response as HttpResponseMessage.</returns> - public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken) - { - return httpClient.GetAsync(url, cancellationToken); - } - internal string GetDataFilePath(string imdbId) { if (string.IsNullOrEmpty(imdbId)) @@ -394,31 +391,25 @@ namespace MediaBrowser.Providers.Plugins.Omdb return Path.Combine(dataPath, filename); } - private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result) + private static void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result, bool isEnglishRequested) where T : BaseItem { var item = itemResult.Item; - var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport; - // Grab series genres because IMDb data is better than TVDB. Leave movies alone // But only do it if English is the preferred language because this data will not be localized - if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre)) + if (isEnglishRequested && !string.IsNullOrWhiteSpace(result.Genre)) { item.Genres = Array.Empty<string>(); - foreach (var genre in result.Genre - .Split(',', StringSplitOptions.RemoveEmptyEntries) - .Select(i => i.Trim()) - .Where(i => !string.IsNullOrWhiteSpace(i))) + foreach (var genre in result.Genre.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { item.AddGenre(genre); } } - if (isConfiguredForEnglish) + if (isEnglishRequested) { - // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in item.Overview = result.Plot; } @@ -431,7 +422,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { var person = new PersonInfo { - Name = result.Director.Trim(), + Name = result.Director, Type = PersonType.Director }; @@ -442,7 +433,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { var person = new PersonInfo { - Name = result.Writer.Trim(), + Name = result.Writer, Type = PersonType.Writer }; @@ -451,29 +442,34 @@ namespace MediaBrowser.Providers.Plugins.Omdb if (!string.IsNullOrWhiteSpace(result.Actors)) { - var actorList = result.Actors.Split(','); + var actorList = result.Actors.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var actor in actorList) { - if (!string.IsNullOrWhiteSpace(actor)) + if (string.IsNullOrWhiteSpace(actor)) { - var person = new PersonInfo - { - Name = actor.Trim(), - Type = PersonType.Actor - }; - - itemResult.AddPerson(person); + continue; } + + var person = new PersonInfo + { + Name = actor, + Type = PersonType.Actor + }; + + itemResult.AddPerson(person); } } } - private bool IsConfiguredForEnglish(BaseItem item) + private static bool IsConfiguredForEnglish(BaseItem item, string language) { - var lang = item.GetPreferredMetadataLanguage(); + if (string.IsNullOrEmpty(language)) + { + language = item.GetPreferredMetadataLanguage(); + } // The data isn't localized and so can only be used for English users - return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase); + return string.Equals(language, "en", StringComparison.OrdinalIgnoreCase); } internal class SeasonRootObject @@ -550,7 +546,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb if (Ratings != null) { var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase)); - if (rating != null && rating.Value != null) + if (rating?.Value != null) { var value = rating.Value.TrimEnd('%'); if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var score)) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs index 35dc36811..29a557c31 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs @@ -13,7 +13,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -67,40 +66,12 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets return Enumerable.Empty<RemoteImageInfo>(); } - var remoteImages = new List<RemoteImageInfo>(); + var posters = collection.Images.Posters; + var backdrops = collection.Images.Backdrops; + var remoteImages = new List<RemoteImageInfo>(posters.Count + backdrops.Count); - for (var i = 0; i < collection.Images.Posters.Count; i++) - { - var poster = collection.Images.Posters[i]; - remoteImages.Add(new RemoteImageInfo - { - Url = _tmdbClientManager.GetPosterUrl(poster.FilePath), - CommunityRating = poster.VoteAverage, - VoteCount = poster.VoteCount, - Width = poster.Width, - Height = poster.Height, - Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language), - ProviderName = Name, - Type = ImageType.Primary, - RatingType = RatingType.Score - }); - } - - for (var i = 0; i < collection.Images.Backdrops.Count; i++) - { - var backdrop = collection.Images.Backdrops[i]; - remoteImages.Add(new RemoteImageInfo - { - Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath), - CommunityRating = backdrop.VoteAverage, - VoteCount = backdrop.VoteCount, - Width = backdrop.Width, - Height = backdrop.Height, - ProviderName = Name, - Type = ImageType.Backdrop, - RatingType = RatingType.Score - }); - } + _tmdbClientManager.ConvertPostersToRemoteImageInfo(posters, language, remoteImages); + _tmdbClientManager.ConvertBackdropsToRemoteImageInfo(backdrops, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs index 907f0160d..9a78a7536 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/PluginConfiguration.cs @@ -11,5 +11,20 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// Gets or sets a value indicating whether include adult content when searching with TMDb. /// </summary> public bool IncludeAdult { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether tags should be imported for series from TMDb. + /// </summary> + public bool ExcludeTagsSeries { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether tags should be imported for movies from TMDb. + /// </summary> + public bool ExcludeTagsMovies { get; set; } + + /// <summary> + /// Gets or sets a value indicating the maximum number of cast members to fetch for an item. + /// </summary> + public int MaxCastMembers { get; set; } = 15; } } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html index 6f42549d7..12b4c7ca4 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html +++ b/MediaBrowser.Providers/Plugins/Tmdb/Configuration/config.html @@ -12,6 +12,18 @@ <input is="emby-checkbox" type="checkbox" id="includeAdult" /> <span>Include adult content in search results.</span> </label> + <label class="checkboxContainer"> + <input is="emby-checkbox" type="checkbox" id="excludeTagsSeries" /> + <span>Exclude tags/keywords from metadata fetched for series.</span> + </label> + <label class="checkboxContainer"> + <input is="emby-checkbox" type="checkbox" id="excludeTagsMovies" /> + <span>Exclude tags/keywords from metadata fetched for movies.</span> + </label> + <div class="inputContainer"> + <input is="emby-input" type="number" id="maxCastMembers" pattern="[0-9]*" required min="0" max="1000" label="Max Cast Members" /> + <div class="fieldDescription">The maximum number of cast members to fetch for an item.</div> + </div> <br /> <div> <button is="emby-button" type="submit" class="raised button-submit block"><span>Save</span></button> @@ -29,20 +41,33 @@ Dashboard.showLoadingMsg(); ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) { document.querySelector('#includeAdult').checked = config.IncludeAdult; + document.querySelector('#excludeTagsSeries').checked = config.ExcludeTagsSeries; + document.querySelector('#excludeTagsMovies').checked = config.ExcludeTagsMovies; + + var maxCastMembers = document.querySelector('#maxCastMembers'); + maxCastMembers.value = config.MaxCastMembers; + maxCastMembers.dispatchEvent(new Event('change', { + bubbles: true, + cancelable: false + })); + Dashboard.hideLoadingMsg(); }); }); - + document.querySelector('.configForm') .addEventListener('submit', function (e) { Dashboard.showLoadingMsg(); - + ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) { config.IncludeAdult = document.querySelector('#includeAdult').checked; + config.ExcludeTagsSeries = document.querySelector('#excludeTagsSeries').checked; + config.ExcludeTagsMovies = document.querySelector('#excludeTagsMovies').checked; + config.MaxCastMembers = document.querySelector('#maxCastMembers').value; ApiClient.updatePluginConfiguration(PluginConfig.pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult); }); - + e.preventDefault(); return false; }); diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs index 015eddc1a..f71f7bd10 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs @@ -13,7 +13,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; using TMDbLib.Objects.Find; @@ -84,40 +83,12 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies return Enumerable.Empty<RemoteImageInfo>(); } - var remoteImages = new List<RemoteImageInfo>(); + var posters = movie.Images.Posters; + var backdrops = movie.Images.Backdrops; + var remoteImages = new List<RemoteImageInfo>(posters.Count + backdrops.Count); - for (var i = 0; i < movie.Images.Posters.Count; i++) - { - var poster = movie.Images.Posters[i]; - remoteImages.Add(new RemoteImageInfo - { - Url = _tmdbClientManager.GetPosterUrl(poster.FilePath), - CommunityRating = poster.VoteAverage, - VoteCount = poster.VoteCount, - Width = poster.Width, - Height = poster.Height, - Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language), - ProviderName = Name, - Type = ImageType.Primary, - RatingType = RatingType.Score - }); - } - - for (var i = 0; i < movie.Images.Backdrops.Count; i++) - { - var backdrop = movie.Images.Backdrops[i]; - remoteImages.Add(new RemoteImageInfo - { - Url = _tmdbClientManager.GetPosterUrl(backdrop.FilePath), - CommunityRating = backdrop.VoteAverage, - VoteCount = backdrop.VoteCount, - Width = backdrop.Width, - Height = backdrop.Height, - ProviderName = Name, - Type = ImageType.Backdrop, - RatingType = RatingType.Score - }); - } + _tmdbClientManager.ConvertPostersToRemoteImageInfo(posters, language, remoteImages); + _tmdbClientManager.ConvertBackdropsToRemoteImageInfo(backdrops, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 9dd067856..fcaacc90d 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -241,8 +241,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies if (movieResult.Credits?.Cast != null) { - // TODO configurable - foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers)) + foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers)) { var personInfo = new PersonInfo { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index 1fc5ccba5..7ce4cfe67 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -60,21 +60,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People return Enumerable.Empty<RemoteImageInfo>(); } - var remoteImages = new RemoteImageInfo[personResult.Images.Profiles.Count]; + var profiles = personResult.Images.Profiles; + var remoteImages = new List<RemoteImageInfo>(profiles.Count); - for (var i = 0; i < personResult.Images.Profiles.Count; i++) - { - var image = personResult.Images.Profiles[i]; - remoteImages[i] = new RemoteImageInfo - { - ProviderName = Name, - Type = ImageType.Primary, - Width = image.Width, - Height = image.Height, - Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language), - Url = _tmdbClientManager.GetProfileUrl(image.FilePath) - }; - } + _tmdbClientManager.ConvertProfilesToRemoteImageInfo(profiles, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs index eb75e9405..5eec776b5 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs @@ -12,7 +12,6 @@ using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -75,23 +74,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV return Enumerable.Empty<RemoteImageInfo>(); } - var remoteImages = new RemoteImageInfo[stills.Count]; - for (var i = 0; i < stills.Count; i++) - { - var image = stills[i]; - remoteImages[i] = new RemoteImageInfo - { - Url = _tmdbClientManager.GetStillUrl(image.FilePath), - CommunityRating = image.VoteAverage, - VoteCount = image.VoteCount, - Width = image.Width, - Height = image.Height, - Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language), - ProviderName = Name, - Type = ImageType.Primary, - RatingType = RatingType.Score - }; - } + var remoteImages = new List<RemoteImageInfo>(stills.Count); + + _tmdbClientManager.ConvertStillsToRemoteImageInfo(stills, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs index 3f826843a..8ac9d0cab 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs @@ -154,7 +154,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV if (credits?.Cast != null) { - foreach (var actor in credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers)) + foreach (var actor in credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers)) { metadataResult.AddPerson(new PersonInfo { @@ -168,7 +168,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV if (credits?.GuestStars != null) { - foreach (var guest in credits.GuestStars.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers)) + foreach (var guest in credits.GuestStars.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers)) { metadataResult.AddPerson(new PersonInfo { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs index ca44c9bbc..4446fa966 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs @@ -11,7 +11,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -62,23 +61,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV return Enumerable.Empty<RemoteImageInfo>(); } - var remoteImages = new RemoteImageInfo[posters.Count]; - for (var i = 0; i < posters.Count; i++) - { - var image = posters[i]; - remoteImages[i] = new RemoteImageInfo - { - Url = _tmdbClientManager.GetPosterUrl(image.FilePath), - CommunityRating = image.VoteAverage, - VoteCount = image.VoteCount, - Width = image.Width, - Height = image.Height, - Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language), - ProviderName = Name, - Type = ImageType.Primary, - RatingType = RatingType.Score - }; - } + var remoteImages = new List<RemoteImageInfo>(posters.Count); + + _tmdbClientManager.ConvertPostersToRemoteImageInfo(posters, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs index 4ac889680..7afaddc24 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs @@ -67,7 +67,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var credits = seasonResult.Credits; if (credits?.Cast != null) { - var cast = credits.Cast.OrderBy(c => c.Order).Take(TmdbUtils.MaxCastMembers).ToList(); + var cast = credits.Cast.OrderBy(c => c.Order).Take(Plugin.Instance.Configuration.MaxCastMembers).ToList(); for (var i = 0; i < cast.Count; i++) { result.AddPerson(new PersonInfo diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs index f3f340378..5ef3736c4 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs @@ -11,7 +11,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -70,41 +69,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var posters = series.Images.Posters; var backdrops = series.Images.Backdrops; + var remoteImages = new List<RemoteImageInfo>(posters.Count + backdrops.Count); - var remoteImages = new RemoteImageInfo[posters.Count + backdrops.Count]; - - for (var i = 0; i < posters.Count; i++) - { - var poster = posters[i]; - remoteImages[i] = new RemoteImageInfo - { - Url = _tmdbClientManager.GetPosterUrl(poster.FilePath), - CommunityRating = poster.VoteAverage, - VoteCount = poster.VoteCount, - Width = poster.Width, - Height = poster.Height, - Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language), - ProviderName = Name, - Type = ImageType.Primary, - RatingType = RatingType.Score - }; - } - - for (var i = 0; i < backdrops.Count; i++) - { - var backdrop = series.Images.Backdrops[i]; - remoteImages[posters.Count + i] = new RemoteImageInfo - { - Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath), - CommunityRating = backdrop.VoteAverage, - VoteCount = backdrop.VoteCount, - Width = backdrop.Width, - Height = backdrop.Height, - ProviderName = Name, - Type = ImageType.Backdrop, - RatingType = RatingType.Score - }; - } + _tmdbClientManager.ConvertPostersToRemoteImageInfo(posters, language, remoteImages); + _tmdbClientManager.ConvertBackdropsToRemoteImageInfo(backdrops, language, remoteImages); return remoteImages; } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index feda15cf7..77e22ffbf 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -331,7 +331,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV { if (seriesResult.Credits?.Cast != null) { - foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers)) + foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers)) { var personInfo = new PersonInfo { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 74be4c793..4d3bc61e5 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -1,10 +1,13 @@ -#nullable disable +#nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; using Microsoft.Extensions.Caching.Memory; using TMDbLib.Client; using TMDbLib.Objects.Collections; @@ -57,11 +60,17 @@ namespace MediaBrowser.Providers.Plugins.Tmdb await EnsureClientConfigAsync().ConfigureAwait(false); + var extraMethods = MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Videos; + if (!(Plugin.Instance?.Configuration.ExcludeTagsMovies).GetValueOrDefault()) + { + extraMethods |= MovieMethods.Keywords; + } + movie = await _tmDbClient.GetMovieAsync( tmdbId, TmdbUtils.NormalizeLanguage(language), imageLanguages, - MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Keywords | MovieMethods.Videos, + extraMethods, cancellationToken).ConfigureAwait(false); if (movie != null) @@ -123,11 +132,17 @@ namespace MediaBrowser.Providers.Plugins.Tmdb await EnsureClientConfigAsync().ConfigureAwait(false); + var extraMethods = TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings | TvShowMethods.EpisodeGroups; + if (!(Plugin.Instance?.Configuration.ExcludeTagsSeries).GetValueOrDefault()) + { + extraMethods |= TvShowMethods.Keywords; + } + series = await _tmDbClient.GetTvShowAsync( tmdbId, language: TmdbUtils.NormalizeLanguage(language), includeImageLanguage: imageLanguages, - extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings | TvShowMethods.EpisodeGroups, + extraMethods: extraMethods, cancellationToken: cancellationToken).ConfigureAwait(false); if (series != null) @@ -471,33 +486,29 @@ namespace MediaBrowser.Providers.Plugins.Tmdb } /// <summary> - /// Gets the absolute URL of the poster. + /// Handles bad path checking and builds the absolute url. /// </summary> - /// <param name="posterPath">The relative URL of the poster.</param> + /// <param name="size">The image size to fetch.</param> + /// <param name="path">The relative URL of the image.</param> /// <returns>The absolute URL.</returns> - public string GetPosterUrl(string posterPath) + private string GetUrl(string size, string path) { - if (string.IsNullOrEmpty(posterPath)) + if (string.IsNullOrEmpty(path)) { return null; } - return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.PosterSizes[^1], posterPath).ToString(); + return _tmDbClient.GetImageUrl(size, path, true).ToString(); } /// <summary> - /// Gets the absolute URL of the backdrop image. + /// Gets the absolute URL of the poster. /// </summary> - /// <param name="posterPath">The relative URL of the backdrop image.</param> + /// <param name="posterPath">The relative URL of the poster.</param> /// <returns>The absolute URL.</returns> - public string GetBackdropUrl(string posterPath) + public string GetPosterUrl(string posterPath) { - if (string.IsNullOrEmpty(posterPath)) - { - return null; - } - - return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.BackdropSizes[^1], posterPath).ToString(); + return GetUrl(_tmDbClient.Config.Images.PosterSizes[^1], posterPath); } /// <summary> @@ -507,27 +518,79 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// <returns>The absolute URL.</returns> public string GetProfileUrl(string actorProfilePath) { - if (string.IsNullOrEmpty(actorProfilePath)) - { - return null; - } + return GetUrl(_tmDbClient.Config.Images.ProfileSizes[^1], actorProfilePath); + } - return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.ProfileSizes[^1], actorProfilePath).ToString(); + /// <summary> + /// Converts poster <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s. + /// </summary> + /// <param name="images">The input images.</param> + /// <param name="requestLanguage">The requested language.</param> + /// <param name="results">The collection to add the remote images into.</param> + public void ConvertPostersToRemoteImageInfo(List<ImageData> images, string requestLanguage, List<RemoteImageInfo> results) + { + ConvertToRemoteImageInfo(images, _tmDbClient.Config.Images.PosterSizes[^1], ImageType.Primary, requestLanguage, results); } /// <summary> - /// Gets the absolute URL of the still image. + /// Converts backdrop <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s. /// </summary> - /// <param name="filePath">The relative URL of the still image.</param> - /// <returns>The absolute URL.</returns> - public string GetStillUrl(string filePath) + /// <param name="images">The input images.</param> + /// <param name="requestLanguage">The requested language.</param> + /// <param name="results">The collection to add the remote images into.</param> + public void ConvertBackdropsToRemoteImageInfo(List<ImageData> images, string requestLanguage, List<RemoteImageInfo> results) { - if (string.IsNullOrEmpty(filePath)) + ConvertToRemoteImageInfo(images, _tmDbClient.Config.Images.BackdropSizes[^1], ImageType.Backdrop, requestLanguage, results); + } + + /// <summary> + /// Converts profile <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s. + /// </summary> + /// <param name="images">The input images.</param> + /// <param name="requestLanguage">The requested language.</param> + /// <param name="results">The collection to add the remote images into.</param> + public void ConvertProfilesToRemoteImageInfo(List<ImageData> images, string requestLanguage, List<RemoteImageInfo> results) + { + ConvertToRemoteImageInfo(images, _tmDbClient.Config.Images.ProfileSizes[^1], ImageType.Primary, requestLanguage, results); + } + + /// <summary> + /// Converts still <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s. + /// </summary> + /// <param name="images">The input images.</param> + /// <param name="requestLanguage">The requested language.</param> + /// <param name="results">The collection to add the remote images into.</param> + public void ConvertStillsToRemoteImageInfo(List<ImageData> images, string requestLanguage, List<RemoteImageInfo> results) + { + ConvertToRemoteImageInfo(images, _tmDbClient.Config.Images.StillSizes[^1], ImageType.Primary, requestLanguage, results); + } + + /// <summary> + /// Converts <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s. + /// </summary> + /// <param name="images">The input images.</param> + /// <param name="size">The size of the image to fetch.</param> + /// <param name="type">The type of the image.</param> + /// <param name="requestLanguage">The requested language.</param> + /// <param name="results">The collection to add the remote images into.</param> + private void ConvertToRemoteImageInfo(List<ImageData> images, string size, ImageType type, string requestLanguage, List<RemoteImageInfo> results) + { + for (var i = 0; i < images.Count; i++) { - return null; + var image = images[i]; + results.Add(new RemoteImageInfo + { + Url = GetUrl(size, image.FilePath), + CommunityRating = image.VoteAverage, + VoteCount = image.VoteCount, + Width = image.Width, + Height = image.Height, + Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, requestLanguage), + ProviderName = TmdbUtils.ProviderName, + Type = type, + RatingType = RatingType.Score + }); } - - return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.StillSizes[^1], filePath).ToString(); } private Task EnsureClientConfigAsync() @@ -542,7 +605,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb GC.SuppressFinalize(this); } -/// <summary> + /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 58ab9f547..a3a78103e 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -29,11 +29,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb public const string ApiKey = "4219e299c89411838049ab0dab19ebd5"; /// <summary> - /// Maximum number of cast members to pull. - /// </summary> - public const int MaxCastMembers = 15; - - /// <summary> /// The crew types to keep. /// </summary> public static readonly string[] WantedCrewTypes = diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs index 9d223b4b6..770dc3e00 100644 --- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs @@ -130,11 +130,12 @@ namespace MediaBrowser.Providers.TV /// <returns>The async task.</returns> private async Task FillInMissingSeasonsAsync(Series series, CancellationToken cancellationToken) { - var episodesInSeriesFolder = series.GetRecursiveChildren(i => i is Episode) - .Cast<Episode>() + var seriesChildren = series.GetRecursiveChildren(i => i is Episode || i is Season); + var episodesInSeriesFolder = seriesChildren + .OfType<Episode>() .Where(i => !i.IsInSeasonFolder); - List<Season> seasons = series.Children.OfType<Season>().ToList(); + List<Season> seasons = seriesChildren.OfType<Season>().ToList(); // Loop through the unique season numbers foreach (var episode in episodesInSeriesFolder) diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index d02aea556..935ff5f59 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -71,7 +71,7 @@ namespace MediaBrowser.XbmcMetadata } catch (Exception ex) { - _logger.LogError(ex, "Error saving metadata for {path}", item.Path ?? item.Name); + _logger.LogError(ex, "Error saving metadata for {Path}", item.Path ?? item.Name); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 9d558b6ce..bcf9a8366 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -784,8 +784,18 @@ namespace MediaBrowser.XbmcMetadata.Parsers case "fanart": { - var subtree = reader.ReadSubtree(); - subtree.ReadToDescendant("thumb"); + if (reader.IsEmptyElement) + { + reader.Read(); + break; + } + + using var subtree = reader.ReadSubtree(); + if (!subtree.ReadToDescendant("thumb")) + { + break; + } + FetchThumbNode(subtree, itemResult); break; } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index 2c893ac9f..3011d65a6 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -103,7 +103,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - Logger.LogInformation("Unrecognized series status: " + status); + Logger.LogInformation("Unrecognized series status: {Status}", status); } } diff --git a/RSSDP/HttpParserBase.cs b/RSSDP/HttpParserBase.cs index c56249523..6b6c13d99 100644 --- a/RSSDP/HttpParserBase.cs +++ b/RSSDP/HttpParserBase.cs @@ -82,7 +82,7 @@ namespace Rssdp.Infrastructure throw new ArgumentNullException(nameof(versionData)); } - var versionSeparatorIndex = versionData.IndexOf('/'); + var versionSeparatorIndex = versionData.IndexOf('/', StringComparison.Ordinal); if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length) { throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData)); @@ -101,7 +101,7 @@ namespace Rssdp.Infrastructure { // Header format is // name: value - var headerKeySeparatorIndex = line.IndexOf(":", StringComparison.OrdinalIgnoreCase); + var headerKeySeparatorIndex = line.IndexOf(':', StringComparison.Ordinal); var headerName = line.Substring(0, headerKeySeparatorIndex).Trim(); var headerValue = line.Substring(headerKeySeparatorIndex + 1).Trim(); @@ -172,7 +172,7 @@ namespace Rssdp.Infrastructure else { var segments = headerValue.Split(SeparatorCharacters); - if (headerValue.Contains('"')) + if (headerValue.Contains('"', StringComparison.Ordinal)) { for (int segmentIndex = 0; segmentIndex < segments.Length; segmentIndex++) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 64d19803d..a7767b3c0 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -15,8 +15,6 @@ namespace Rssdp.Infrastructure /// </summary> public class SsdpDevicePublisher : DisposableManagedObjectBase, ISsdpDevicePublisher { - private readonly INetworkManager _networkManager; - private ISsdpCommunicationsServer _CommsServer; private string _OSName; private string _OSVersion; @@ -38,19 +36,17 @@ namespace Rssdp.Infrastructure /// <summary> /// Default constructor. /// </summary> - public SsdpDevicePublisher(ISsdpCommunicationsServer communicationsServer, INetworkManager networkManager, - string osName, string osVersion, bool sendOnlyMatchedHost) + public SsdpDevicePublisher( + ISsdpCommunicationsServer communicationsServer, + string osName, + string osVersion, + bool sendOnlyMatchedHost) { if (communicationsServer == null) { throw new ArgumentNullException(nameof(communicationsServer)); } - if (networkManager == null) - { - throw new ArgumentNullException(nameof(networkManager)); - } - if (osName == null) { throw new ArgumentNullException(nameof(osName)); @@ -77,7 +73,6 @@ namespace Rssdp.Infrastructure _RecentSearchRequests = new Dictionary<string, SearchRequest>(StringComparer.OrdinalIgnoreCase); _Random = new Random(); - _networkManager = networkManager; _CommsServer = communicationsServer; _CommsServer.RequestReceived += CommsServer_RequestReceived; _OSName = osName; diff --git a/debian/jellyfin.service b/debian/jellyfin.service index b79cd47c7..e215a8536 100644 --- a/debian/jellyfin.service +++ b/debian/jellyfin.service @@ -10,5 +10,27 @@ ExecStart = /usr/bin/jellyfin ${JELLYFIN_WEB_OPT} ${JELLYFIN_RESTART_OPT} ${JELL Restart = on-failure TimeoutSec = 15 +NoNewPrivileges=true +SystemCallArchitectures=native +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK +ProtectKernelModules=True +SystemCallFilter=~@clock +SystemCallFilter=~@aio +SystemCallFilter=~@chown +SystemCallFilter=~@cpu-emulation +SystemCallFilter=~@debug +SystemCallFilter=~@keyring +SystemCallFilter=~@memlock +SystemCallFilter=~@module +SystemCallFilter=~@mount +SystemCallFilter=~@obsolete +SystemCallFilter=~@privileged +SystemCallFilter=~@raw-io +SystemCallFilter=~@reboot +SystemCallFilter=~@setuid +SystemCallFilter=~@swap +SystemCallErrorNumber=EPERM + + [Install] WantedBy = multi-user.target diff --git a/deployment/Dockerfile.centos.amd64 b/deployment/Dockerfile.centos.amd64 index 78f051e4f..3967a165d 100644 --- a/deployment/Dockerfile.centos.amd64 +++ b/deployment/Dockerfile.centos.amd64 @@ -13,7 +13,7 @@ RUN yum update -yq \ && yum install -yq @buildsys-build rpmdevtools yum-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel git wget # Install DotNET SDK -RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget -q https://download.visualstudio.microsoft.com/download/pr/17b6759f-1af0-41bc-ab12-209ba0377779/e8d02195dbf1434b940e0f05ae086453/dotnet-sdk-6.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64 index 14eeb6eed..bc40a8059 100644 --- a/deployment/Dockerfile.fedora.amd64 +++ b/deployment/Dockerfile.fedora.amd64 @@ -12,7 +12,7 @@ RUN dnf update -yq \ && dnf install -yq @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel systemd wget # Install DotNET SDK -RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget -q https://download.visualstudio.microsoft.com/download/pr/17b6759f-1af0-41bc-ab12-209ba0377779/e8d02195dbf1434b940e0f05ae086453/dotnet-sdk-6.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index 8733be89c..c1b541c59 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -17,7 +17,7 @@ RUN apt-get update -yqq \ libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0 # Install dotnet repository -RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget -q https://download.visualstudio.microsoft.com/download/pr/17b6759f-1af0-41bc-ab12-209ba0377779/e8d02195dbf1434b940e0f05ae086453/dotnet-sdk-6.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index 6ae0d53cc..6aa98a289 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,7 @@ RUN apt-get update -yqq \ mmv build-essential lsb-release # Install dotnet repository -RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget -q https://download.visualstudio.microsoft.com/download/pr/17b6759f-1af0-41bc-ab12-209ba0377779/e8d02195dbf1434b940e0f05ae086453/dotnet-sdk-6.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 154388148..cc9d8dc79 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,7 @@ RUN apt-get update -yqq \ mmv build-essential lsb-release # Install dotnet repository -RUN wget -q https://download.visualstudio.microsoft.com/download/pr/20283373-1d83-4879-8278-0afb7fd4035e/56f204f174743b29a656499ad0fc93c3/dotnet-sdk-6.0.100-rc.2.21505.57-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget -q https://download.visualstudio.microsoft.com/download/pr/17b6759f-1af0-41bc-ab12-209ba0377779/e8d02195dbf1434b940e0f05ae086453/dotnet-sdk-6.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/unraid/docker-templates/README.md b/deployment/unraid/docker-templates/README.md index 2c268e8b3..8e401e009 100644 --- a/deployment/unraid/docker-templates/README.md +++ b/deployment/unraid/docker-templates/README.md @@ -8,7 +8,7 @@ Click on the Docker tab Add the following line under "Template Repositories" -https://github.com/jellyfin/jellyfin/blob/master/deployment/unraid/docker-templates +https://github.com/jellyfin/jellyfin/tree/master/deployment/unraid/docker-templates Click save than click on Add Container and select jellyfin. diff --git a/jellyfin.ruleset b/jellyfin.ruleset index dfb991170..7adc35087 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -38,13 +38,29 @@ </Rules> <Rules AnalyzerId="Microsoft.CodeAnalysis.NetAnalyzers" RuleNamespace="Microsoft.Design"> + <!-- error on CA1063: Implement IDisposable correctly --> + <Rule Id="CA1063" Action="Error" /> <!-- error on CA1305: Specify IFormatProvider --> <Rule Id="CA1305" Action="Error" /> + <!-- error on CA1307: Specify StringComparison for clarity --> + <Rule Id="CA1307" Action="Error" /> + <!-- error on CA1309: Use ordinal StringComparison --> + <Rule Id="CA1309" Action="Error" /> <!-- error on CA1725: Parameter names should match base declaration --> <Rule Id="CA1725" Action="Error" /> + <!-- error on CA1725: Call async methods when in an async method --> + <Rule Id="CA1727" Action="Error" /> + <!-- error on CA1813: Avoid unsealed attributes --> + <Rule Id="CA1813" Action="Error" /> + <!-- error on CA1843: Do not use 'WaitAll' with a single task --> + <Rule Id="CA1843" Action="Error" /> + <!-- error on CA1845: Use span-based 'string.Concat' --> + <Rule Id="CA1845" Action="Error" /> <!-- error on CA2016: Forward the CancellationToken parameter to methods that take one or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token --> <Rule Id="CA2016" Action="Error" /> + <!-- error on CA2254: Template should be a static expression --> + <Rule Id="CA2254" Action="Error" /> <!-- disable warning CA1014: Mark assemblies with CLSCompliantAttribute --> <Rule Id="CA1014" Action="Info" /> @@ -77,6 +93,8 @@ <Rule Id="CA1822" Action="Info" /> <!-- disable warning CA2000: Dispose objects before losing scope --> <Rule Id="CA2000" Action="Info" /> + <!-- disable warning CA2253: Named placeholders should not be numeric values --> + <Rule Id="CA2253" Action="Info" /> <!-- disable warning CA5394: Do not use insecure randomness --> <Rule Id="CA5394" Action="Info" /> @@ -90,6 +108,8 @@ <Rule Id="CA1303" Action="None" /> <!-- disable warning CA1308: Normalize strings to uppercase --> <Rule Id="CA1308" Action="None" /> + <!-- disable warning CA1848: Use the LoggerMessage delegates --> + <Rule Id="CA1848" Action="None" /> <!-- disable warning CA2101: Specify marshaling for P/Invoke string arguments --> <Rule Id="CA2101" Action="None" /> <!-- disable warning CA2234: Pass System.Uri objects instead of strings --> diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index cd03958b6..6f5c0ed0c 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -132,6 +132,8 @@ namespace Jellyfin.Api.Tests.Auth authorizationInfo.User.AddDefaultPreferences(); authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin); authorizationInfo.IsApiKey = false; + authorizationInfo.HasToken = true; + authorizationInfo.Token = "fake-token"; _jellyfinAuthServiceMock.Setup( a => a.Authenticate( diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 922b3d94f..2aced0669 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -15,9 +15,9 @@ <PackageReference Include="AutoFixture" Version="4.17.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 1fe4e2565..ce607b2ec 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -12,7 +12,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.Controller.Tests/BaseItemManagerTests.cs b/tests/Jellyfin.Controller.Tests/BaseItemManagerTests.cs new file mode 100644 index 000000000..edceef4a7 --- /dev/null +++ b/tests/Jellyfin.Controller.Tests/BaseItemManagerTests.cs @@ -0,0 +1,89 @@ +using System; +using MediaBrowser.Controller.BaseItemManager; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Model.Configuration; +using Moq; +using Xunit; + +namespace Jellyfin.Controller.Tests +{ + public class BaseItemManagerTests + { + [Theory] + [InlineData(typeof(Book), "LibraryEnabled", true)] + [InlineData(typeof(Book), "LibraryDisabled", false)] + [InlineData(typeof(MusicArtist), "Enabled", true)] + [InlineData(typeof(MusicArtist), "ServerDisabled", false)] + public void IsMetadataFetcherEnabled_ChecksOptions_ReturnsExpected(Type itemType, string fetcherName, bool expected) + { + BaseItem item = (BaseItem)Activator.CreateInstance(itemType)!; + + var libraryOptions = new LibraryOptions + { + TypeOptions = new[] + { + new TypeOptions + { + Type = "Book", + MetadataFetchers = new[] { "LibraryEnabled" } + } + } + }; + + var serverConfiguration = new ServerConfiguration(); + foreach (var typeConfig in serverConfiguration.MetadataOptions) + { + typeConfig.DisabledMetadataFetchers = new[] { "ServerDisabled" }; + } + + var serverConfigurationManager = new Mock<IServerConfigurationManager>(); + serverConfigurationManager.Setup(scm => scm.Configuration) + .Returns(serverConfiguration); + + var baseItemManager = new BaseItemManager(serverConfigurationManager.Object); + var actual = baseItemManager.IsMetadataFetcherEnabled(item, libraryOptions, fetcherName); + + Assert.Equal(expected, actual); + } + + [Theory] + [InlineData(typeof(Book), "LibraryEnabled", true)] + [InlineData(typeof(Book), "LibraryDisabled", false)] + [InlineData(typeof(MusicArtist), "Enabled", true)] + [InlineData(typeof(MusicArtist), "ServerDisabled", false)] + public void IsImageFetcherEnabled_ChecksOptions_ReturnsExpected(Type itemType, string fetcherName, bool expected) + { + BaseItem item = (BaseItem)Activator.CreateInstance(itemType)!; + + var libraryOptions = new LibraryOptions + { + TypeOptions = new[] + { + new TypeOptions + { + Type = "Book", + ImageFetchers = new[] { "LibraryEnabled" } + } + } + }; + + var serverConfiguration = new ServerConfiguration(); + foreach (var typeConfig in serverConfiguration.MetadataOptions) + { + typeConfig.DisabledImageFetchers = new[] { "ServerDisabled" }; + } + + var serverConfigurationManager = new Mock<IServerConfigurationManager>(); + serverConfigurationManager.Setup(scm => scm.Configuration) + .Returns(serverConfiguration); + + var baseItemManager = new BaseItemManager(serverConfigurationManager.Object); + var actual = baseItemManager.IsImageFetcherEnabled(item, libraryOptions, fetcherName); + + Assert.Equal(expected, actual); + } + } +} diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index e9a951571..0ffc19833 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -12,7 +12,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 1fb95aab4..098166001 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -7,7 +7,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> diff --git a/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj b/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj index 2dc4ac19a..ee3af7559 100644 --- a/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj +++ b/tests/Jellyfin.Extensions.Tests/Jellyfin.Extensions.Tests.csproj @@ -7,7 +7,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 201f63a2d..dc4a42c19 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -22,7 +22,7 @@ <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> diff --git a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs b/tests/Jellyfin.Model.Tests/Cryptography/PasswordHashTests.cs index bfece97b6..6948280a3 100644 --- a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs +++ b/tests/Jellyfin.Model.Tests/Cryptography/PasswordHashTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using MediaBrowser.Common.Cryptography; +using MediaBrowser.Model.Cryptography; using Xunit; -namespace Jellyfin.Common.Tests.Cryptography +namespace Jellyfin.Model.Tests.Cryptography { public static class PasswordHashTests { diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index a37e5ac92..7e8397d9f 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -7,7 +7,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 75d466198..4096873a3 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -12,7 +12,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 2873f6161..1e7fedb36 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -71,9 +71,9 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 1/seriesname 05.mkv", 5)] // no hyphen between series name and episode number [InlineData("[BBT-RMX] Ranma ½ - 154 [50AC421A].mkv", 154)] // hyphens in the pre-name info, triple digit episode number [InlineData("Season 2/Episode 21 - 94 Meetings.mp4", 21)] // Title starts with a number + [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] // [InlineData("Case Closed (1996-2007)/Case Closed - 317.mkv", 317)] // triple digit episode number // TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)] - // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] // TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] // TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)] // TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] diff --git a/tests/Jellyfin.Naming.Tests/TV/SeriesPathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/SeriesPathParserTest.cs new file mode 100644 index 000000000..ceb5f8b73 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/SeriesPathParserTest.cs @@ -0,0 +1,28 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class SeriesPathParserTest + { + [Theory] + [InlineData("The.Show.S01", "The.Show")] + [InlineData("/The.Show.S01", "The.Show")] + [InlineData("/some/place/The.Show.S01", "The.Show")] + [InlineData("/something/The.Show.S01", "The.Show")] + [InlineData("The Show Season 10", "The Show")] + [InlineData("The Show S01E01", "The Show")] + [InlineData("The Show S01E01 Episode", "The Show")] + [InlineData("/something/The Show/Season 1", "The Show")] + [InlineData("/something/The Show/S01", "The Show")] + public void SeriesPathParserParseTest(string path, string name) + { + NamingOptions o = new NamingOptions(); + var res = SeriesPathParser.Parse(o, path); + + Assert.Equal(name, res.SeriesName); + Assert.True(res.Success); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/SeriesResolverTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeriesResolverTests.cs new file mode 100644 index 000000000..97f4b4058 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/SeriesResolverTests.cs @@ -0,0 +1,28 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class SeriesResolverTests + { + [Theory] + [InlineData("The.Show.S01", "The Show")] + [InlineData("The.Show.S01.COMPLETE", "The Show")] + [InlineData("S.H.O.W.S01", "S.H.O.W")] + [InlineData("The.Show.P.I.S01", "The Show P.I")] + [InlineData("The_Show_Season_1", "The Show")] + [InlineData("/something/The_Show/Season 10", "The Show")] + [InlineData("The Show", "The Show")] + [InlineData("/some/path/The Show", "The Show")] + [InlineData("/some/path/The Show s02e10 720p hdtv", "The Show")] + [InlineData("/some/path/The Show s02e10 the episode 720p hdtv", "The Show")] + public void SeriesResolverResolveTest(string path, string name) + { + NamingOptions o = new NamingOptions(); + var res = SeriesResolver.Resolve(o, path); + + Assert.Equal(name, res.Name); + } + } +} diff --git a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj index 75d9b9ea9..78556ee67 100644 --- a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj @@ -12,7 +12,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs index 1cad625b7..61f913252 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs @@ -34,7 +34,7 @@ namespace Jellyfin.Networking.Tests } /// <summary> - /// Checks that thge given IP address is not in the network provided. + /// Checks that the given IP address is not in the network provided. /// </summary> /// <param name="network">Network address(es).</param> /// <param name="value">The IP to check.</param> diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index a24eee693..6b9397437 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -35,9 +35,9 @@ namespace Jellyfin.Networking.Tests // eth16 only [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] // All interfaces excluded. (including loopbacks) - [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[127.0.0.1/8,::1/128]")] + [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] // vEthernet1 and vEthernet212 should be excluded. - [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24,127.0.0.1/8,::1/128]")] + [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] // Overlapping interface, [InlineData("192.168.1.110/24,-20,br0|192.168.1.10/24,-16,br0|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.110/24,192.168.1.10/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) @@ -476,5 +476,51 @@ namespace Jellyfin.Networking.Tests Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); } + + [Theory] + [InlineData("192.168.1.209/24,-16,eth16", "192.168.1.0/24", "", "192.168.1.209")] // Only 1 address so use it. + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "", "192.168.1.208")] // LAN address is specified by default. + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "10.0.0.1", "10.0.0.1")] // return bind address + + public void GetBindInterface_NoSourceGiven_Success(string interfaces, string lan, string bind, string result) + { + var conf = new NetworkConfiguration + { + EnableIPV4 = true, + LocalNetworkSubnets = lan.Split(','), + LocalNetworkAddresses = bind.Split(',') + }; + + NetworkManager.MockNetworkSettings = interfaces; + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + + var interfaceToUse = nm.GetBindInterface(string.Empty, out _); + + Assert.Equal(result, interfaceToUse); + } + + [Theory] + [InlineData("192.168.1.209/24,-16,eth16", "192.168.1.0/24", "", "192.168.1.210", "192.168.1.209")] // Source on LAN + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "", "192.168.1.209", "192.168.1.208")] // Source on LAN + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "", "8.8.8.8", "10.0.0.1")] // Source external. + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "10.0.0.1", "192.168.1.209", "10.0.0.1")] // LAN not bound, so return external. + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "192.168.1.208,10.0.0.1", "8.8.8.8", "10.0.0.1")] // return external bind address + [InlineData("192.168.1.208/24,-16,eth16|10.0.0.1/24,10,eth7", "192.168.1.0/24", "192.168.1.208,10.0.0.1", "192.168.1.210", "192.168.1.208")] // return LAN bind address + public void GetBindInterface_ValidSourceGiven_Success(string interfaces, string lan, string bind, string source, string result) + { + var conf = new NetworkConfiguration + { + EnableIPV4 = true, + LocalNetworkSubnets = lan.Split(','), + LocalNetworkAddresses = bind.Split(',') + }; + + NetworkManager.MockNetworkSettings = interfaces; + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + + var interfaceToUse = nm.GetBindInterface(source, out _); + + Assert.Equal(result, interfaceToUse); + } } } diff --git a/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj index 0b2db64b0..10767ae23 100644 --- a/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj +++ b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj @@ -7,7 +7,13 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <None Include="Test Data\**\*.*"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> diff --git a/tests/Jellyfin.Providers.Tests/Manager/ItemImageProviderTests.cs b/tests/Jellyfin.Providers.Tests/Manager/ItemImageProviderTests.cs new file mode 100644 index 000000000..2ba5c47d7 --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Manager/ItemImageProviderTests.cs @@ -0,0 +1,597 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Providers; +using MediaBrowser.Providers.Manager; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Providers.Tests.Manager +{ + public class ItemImageProviderTests + { + private const string TestDataImagePath = "Test Data/Images/blank{0}.jpg"; + + [Fact] + public void ValidateImages_PhotoEmptyProviders_NoChange() + { + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.ValidateImages(new Photo(), Enumerable.Empty<ILocalImageProvider>(), null); + + Assert.False(changed); + } + + [Fact] + public void ValidateImages_EmptyItemEmptyProviders_NoChange() + { + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.ValidateImages(new Video(), Enumerable.Empty<ILocalImageProvider>(), null); + + Assert.False(changed); + } + + private static TheoryData<ImageType, int> GetImageTypesWithCount() + { + var theoryTypes = new TheoryData<ImageType, int> + { + // minimal test cases that hit different handling + { ImageType.Primary, 1 }, + { ImageType.Backdrop, 1 }, + { ImageType.Backdrop, 2 } + }; + + return theoryTypes; + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void ValidateImages_EmptyItemAndPopulatedProviders_AddsImages(ImageType imageType, int imageCount) + { + // Has to exist for querying DateModified time on file, results stored but not checked so not populating + BaseItem.FileSystem = Mock.Of<IFileSystem>(); + + var item = new Video(); + var imageProvider = GetImageProvider(imageType, imageCount, true); + + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.ValidateImages(item, new[] { imageProvider }, null); + + Assert.True(changed); + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void ValidateImages_PopulatedItemWithGoodPathsAndEmptyProviders_NoChange(ImageType imageType, int imageCount) + { + var item = GetItemWithImages(imageType, imageCount, true); + + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.ValidateImages(item, Enumerable.Empty<ILocalImageProvider>(), null); + + Assert.False(changed); + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void ValidateImages_PopulatedItemWithBadPathsAndEmptyProviders_RemovesImage(ImageType imageType, int imageCount) + { + var item = GetItemWithImages(imageType, imageCount, false); + + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.ValidateImages(item, Enumerable.Empty<ILocalImageProvider>(), null); + + Assert.True(changed); + Assert.Empty(item.GetImages(imageType)); + } + + [Fact] + public void MergeImages_EmptyItemNewImagesEmpty_NoChange() + { + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.MergeImages(new Video(), Array.Empty<LocalImageInfo>()); + + Assert.False(changed); + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void MergeImages_PopulatedItemWithGoodPathsAndPopulatedNewImages_AddsUpdatesImages(ImageType imageType, int imageCount) + { + // valid and not valid paths - should replace the valid paths with the invalid ones + var item = GetItemWithImages(imageType, imageCount, true); + var images = GetImages(imageType, imageCount, false); + + var itemImageProvider = GetItemImageProvider(null, null); + var changed = itemImageProvider.MergeImages(item, images); + + Assert.True(changed); + // adds for types that allow multiple, replaces singular type images + if (item.AllowsMultipleImages(imageType)) + { + Assert.Equal(imageCount * 2, item.GetImages(imageType).Count()); + } + else + { + Assert.Single(item.GetImages(imageType)); + Assert.Same(images[0].FileInfo.FullName, item.GetImages(imageType).First().Path); + } + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void MergeImages_PopulatedItemWithGoodPathsAndSameNewImages_NoChange(ImageType imageType, int imageCount) + { + var oldTime = new DateTime(1970, 1, 1); + + // match update time with time added to item images (unix epoch) + var fileSystem = new Mock<IFileSystem>(); + fileSystem.Setup(fs => fs.GetLastWriteTimeUtc(It.IsAny<FileSystemMetadata>())) + .Returns(oldTime); + BaseItem.FileSystem = fileSystem.Object; + + // all valid paths - matching for strictly updating + var item = GetItemWithImages(imageType, imageCount, true); + // set size to non-zero to allow for updates to occur + foreach (var image in item.GetImages(imageType)) + { + image.DateModified = oldTime; + image.Height = 1; + image.Width = 1; + } + + var images = GetImages(imageType, imageCount, true); + + var itemImageProvider = GetItemImageProvider(null, fileSystem); + var changed = itemImageProvider.MergeImages(item, images); + + Assert.False(changed); + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public void MergeImages_PopulatedItemWithGoodPathsAndSameNewImagesWithNewTimestamps_ResetsImageSizes(ImageType imageType, int imageCount) + { + var oldTime = new DateTime(1970, 1, 1); + var updatedTime = new DateTime(2021, 1, 1); + + var fileSystem = new Mock<IFileSystem>(); + fileSystem.Setup(fs => fs.GetLastWriteTimeUtc(It.IsAny<FileSystemMetadata>())) + .Returns(updatedTime); + BaseItem.FileSystem = fileSystem.Object; + + // all valid paths - matching for strictly updating + var item = GetItemWithImages(imageType, imageCount, true); + // set size to non-zero to allow for image size reset to occur + foreach (var image in item.GetImages(imageType)) + { + image.DateModified = oldTime; + image.Height = 1; + image.Width = 1; + } + + var images = GetImages(imageType, imageCount, true); + + var itemImageProvider = GetItemImageProvider(null, fileSystem); + var changed = itemImageProvider.MergeImages(item, images); + + Assert.True(changed); + // before and after paths are the same, verify updated by size reset to 0 + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + foreach (var image in item.GetImages(imageType)) + { + Assert.Equal(updatedTime, image.DateModified); + Assert.Equal(0, image.Height); + Assert.Equal(0, image.Width); + } + } + + [Theory] + [InlineData(ImageType.Primary, 1, false)] + [InlineData(ImageType.Backdrop, 2, false)] + [InlineData(ImageType.Primary, 1, true)] + [InlineData(ImageType.Backdrop, 2, true)] + public async void RefreshImages_PopulatedItemPopulatedProviderDynamic_UpdatesImagesIfForced(ImageType imageType, int imageCount, bool forceRefresh) + { + var item = GetItemWithImages(imageType, imageCount, false); + + var libraryOptions = GetLibraryOptions(item, imageType, imageCount); + + var imageResponse = new DynamicImageResponse + { + HasImage = true, + Format = ImageFormat.Jpg, + Path = "url path", + Protocol = MediaProtocol.Http + }; + + var dynamicProvider = new Mock<IDynamicImageProvider>(MockBehavior.Strict); + dynamicProvider.Setup(rp => rp.Name).Returns("MockDynamicProvider"); + dynamicProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + dynamicProvider.Setup(rp => rp.GetImage(item, imageType, It.IsAny<CancellationToken>())) + .ReturnsAsync(imageResponse); + + var refreshOptions = forceRefresh + ? new ImageRefreshOptions(Mock.Of<IDirectoryService>()) + { + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllImages = true + } + : new ImageRefreshOptions(Mock.Of<IDirectoryService>()); + + var itemImageProvider = GetItemImageProvider(null, new Mock<IFileSystem>()); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { dynamicProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.Equal(forceRefresh, result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + if (forceRefresh) + { + // replaces multi-types + Assert.Single(item.GetImages(imageType)); + } + else + { + // adds to multi-types if room + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + } + } + + [Theory] + [InlineData(ImageType.Primary, 1, true, MediaProtocol.Http)] + [InlineData(ImageType.Backdrop, 2, true, MediaProtocol.Http)] + [InlineData(ImageType.Primary, 1, true, MediaProtocol.File)] + [InlineData(ImageType.Backdrop, 2, true, MediaProtocol.File)] + [InlineData(ImageType.Primary, 1, false, MediaProtocol.File)] + [InlineData(ImageType.Backdrop, 2, false, MediaProtocol.File)] + public async void RefreshImages_EmptyItemPopulatedProviderDynamic_AddsImages(ImageType imageType, int imageCount, bool responseHasPath, MediaProtocol protocol) + { + // Has to exist for querying DateModified time on file, results stored but not checked so not populating + BaseItem.FileSystem = Mock.Of<IFileSystem>(); + + var item = new Video(); + + var libraryOptions = GetLibraryOptions(item, imageType, imageCount); + + // Path must exist if set: is read in as a stream by AsyncFile.OpenRead + var imageResponse = new DynamicImageResponse + { + HasImage = true, + Format = ImageFormat.Jpg, + Path = responseHasPath ? string.Format(CultureInfo.InvariantCulture, TestDataImagePath, 0) : null, + Protocol = protocol + }; + + var dynamicProvider = new Mock<IDynamicImageProvider>(MockBehavior.Strict); + dynamicProvider.Setup(rp => rp.Name).Returns("MockDynamicProvider"); + dynamicProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + dynamicProvider.Setup(rp => rp.GetImage(item, imageType, It.IsAny<CancellationToken>())) + .ReturnsAsync(imageResponse); + + var refreshOptions = new ImageRefreshOptions(Mock.Of<IDirectoryService>()); + + var providerManager = new Mock<IProviderManager>(MockBehavior.Strict); + providerManager.Setup(pm => pm.SaveImage(item, It.IsAny<Stream>(), It.IsAny<string>(), imageType, null, It.IsAny<CancellationToken>())) + .Callback<BaseItem, Stream, string, ImageType, int?, CancellationToken>((callbackItem, _, _, callbackType, _, _) => callbackItem.SetImagePath(callbackType, 0, new FileSystemMetadata())) + .Returns(Task.CompletedTask); + var itemImageProvider = GetItemImageProvider(providerManager.Object, null); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { dynamicProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.True(result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + // dynamic provider unable to return multiple images + Assert.Single(item.GetImages(imageType)); + if (protocol == MediaProtocol.Http) + { + Assert.Equal(imageResponse.Path, item.GetImagePath(imageType, 0)); + } + } + + [Theory] + [InlineData(ImageType.Primary, 1, false)] + [InlineData(ImageType.Backdrop, 1, false)] + [InlineData(ImageType.Backdrop, 2, false)] + [InlineData(ImageType.Primary, 1, true)] + [InlineData(ImageType.Backdrop, 1, true)] + [InlineData(ImageType.Backdrop, 2, true)] + public async void RefreshImages_PopulatedItemPopulatedProviderRemote_UpdatesImagesIfForced(ImageType imageType, int imageCount, bool forceRefresh) + { + var item = GetItemWithImages(imageType, imageCount, false); + + var libraryOptions = GetLibraryOptions(item, imageType, imageCount); + + var remoteProvider = new Mock<IRemoteImageProvider>(MockBehavior.Strict); + remoteProvider.Setup(rp => rp.Name).Returns("MockRemoteProvider"); + remoteProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + + var refreshOptions = forceRefresh + ? new ImageRefreshOptions(Mock.Of<IDirectoryService>()) + { + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllImages = true + } + : new ImageRefreshOptions(Mock.Of<IDirectoryService>()); + + var remoteInfo = new RemoteImageInfo[imageCount]; + for (int i = 0; i < imageCount; i++) + { + remoteInfo[i] = new RemoteImageInfo + { + Type = imageType, + Url = "image url " + i, + Width = 1 // min width is set to 0, this will always pass + }; + } + + var providerManager = new Mock<IProviderManager>(MockBehavior.Strict); + providerManager.Setup(pm => pm.GetAvailableRemoteImages(It.IsAny<BaseItem>(), It.IsAny<RemoteImageQuery>(), It.IsAny<CancellationToken>())) + .ReturnsAsync(remoteInfo); + var itemImageProvider = GetItemImageProvider(providerManager.Object, new Mock<IFileSystem>()); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { remoteProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.Equal(forceRefresh, result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + foreach (var image in item.GetImages(imageType)) + { + if (forceRefresh) + { + Assert.Matches(@"image url [0-9]", image.Path); + } + else + { + Assert.DoesNotMatch(@"image url [0-9]", image.Path); + } + } + } + + [Theory] + [InlineData(ImageType.Primary, 0, false)] // singular type only fetches if type is missing from item, no caching + [InlineData(ImageType.Backdrop, 0, false)] // empty item, no cache to check + [InlineData(ImageType.Backdrop, 1, false)] // populated item, cached so no download + [InlineData(ImageType.Backdrop, 1, true)] // populated item, forced to download + public async void RefreshImages_NonStubItemPopulatedProviderRemote_DownloadsIfNecessary(ImageType imageType, int initialImageCount, bool fullRefresh) + { + var targetImageCount = 1; + + // Set path and media source manager so images will be downloaded (EnableImageStub will return false) + var item = GetItemWithImages(imageType, initialImageCount, false); + item.Path = "non-empty path"; + BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>(); + + // seek 2 so it won't short-circuit out of downloading when populated + var libraryOptions = GetLibraryOptions(item, imageType, 2); + + const string Content = "Content"; + var remoteProvider = new Mock<IRemoteImageProvider>(MockBehavior.Strict); + remoteProvider.Setup(rp => rp.Name).Returns("MockRemoteProvider"); + remoteProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + remoteProvider.Setup(rp => rp.GetImageResponse(It.IsAny<string>(), It.IsAny<CancellationToken>())) + .ReturnsAsync((string url, CancellationToken _) => new HttpResponseMessage + { + ReasonPhrase = url, + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Content, Encoding.UTF8, "image/jpeg") + }); + + var refreshOptions = fullRefresh + ? new ImageRefreshOptions(Mock.Of<IDirectoryService>()) + { + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllImages = true + } + : new ImageRefreshOptions(Mock.Of<IDirectoryService>()); + + var remoteInfo = new RemoteImageInfo[targetImageCount]; + for (int i = 0; i < targetImageCount; i++) + { + remoteInfo[i] = new RemoteImageInfo() + { + Type = imageType, + Url = "image url " + i, + Width = 1 // min width is set to 0, this will always pass + }; + } + + var providerManager = new Mock<IProviderManager>(MockBehavior.Strict); + providerManager.Setup(pm => pm.GetAvailableRemoteImages(It.IsAny<BaseItem>(), It.IsAny<RemoteImageQuery>(), It.IsAny<CancellationToken>())) + .ReturnsAsync(remoteInfo); + providerManager.Setup(pm => pm.SaveImage(item, It.IsAny<Stream>(), It.IsAny<string>(), imageType, null, It.IsAny<CancellationToken>())) + .Callback<BaseItem, Stream, string, ImageType, int?, CancellationToken>((callbackItem, _, _, callbackType, _, _) => + callbackItem.SetImagePath(callbackType, callbackItem.AllowsMultipleImages(callbackType) ? callbackItem.GetImages(callbackType).Count() : 0, new FileSystemMetadata())) + .Returns(Task.CompletedTask); + var fileSystem = new Mock<IFileSystem>(); + // match reported file size to image content length - condition for skipping already downloaded multi-images + fileSystem.Setup(fs => fs.GetFileInfo(It.IsAny<string>())) + .Returns(new FileSystemMetadata { Length = Content.Length }); + var itemImageProvider = GetItemImageProvider(providerManager.Object, fileSystem); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { remoteProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.Equal(initialImageCount == 0 || fullRefresh, result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + Assert.Equal(targetImageCount, item.GetImages(imageType).Count()); + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public async void RefreshImages_EmptyItemPopulatedProviderRemoteExtras_LimitsImages(ImageType imageType, int imageCount) + { + var item = new Video(); + + var libraryOptions = GetLibraryOptions(item, imageType, imageCount); + + var remoteProvider = new Mock<IRemoteImageProvider>(MockBehavior.Strict); + remoteProvider.Setup(rp => rp.Name).Returns("MockRemoteProvider"); + remoteProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + + var refreshOptions = new ImageRefreshOptions(Mock.Of<IDirectoryService>()); + + // populate remote with double the required images to verify count is trimmed to the library option count + var remoteInfoCount = imageCount * 2; + var remoteInfo = new RemoteImageInfo[remoteInfoCount]; + for (int i = 0; i < remoteInfoCount; i++) + { + remoteInfo[i] = new RemoteImageInfo() + { + Type = imageType, + Url = "image url " + i, + Width = 1 // min width is set to 0, this will always pass + }; + } + + var providerManager = new Mock<IProviderManager>(MockBehavior.Strict); + providerManager.Setup(pm => pm.GetAvailableRemoteImages(It.IsAny<BaseItem>(), It.IsAny<RemoteImageQuery>(), It.IsAny<CancellationToken>())) + .ReturnsAsync(remoteInfo); + var itemImageProvider = GetItemImageProvider(providerManager.Object, null); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { remoteProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.True(result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + var actualImages = item.GetImages(imageType).ToList(); + Assert.Equal(imageCount, actualImages.Count); + // images from the provider manager are sorted by preference (earlier images are higher priority) so we can verify that low url numbers are chosen + foreach (var image in actualImages) + { + var index = int.Parse(Regex.Match(image.Path, @"[0-9]+").Value, NumberStyles.Integer, CultureInfo.InvariantCulture); + Assert.True(index < imageCount); + } + } + + [Theory] + [MemberData(nameof(GetImageTypesWithCount))] + public async void RefreshImages_PopulatedItemEmptyProviderRemoteFullRefresh_DoesntClearImages(ImageType imageType, int imageCount) + { + var item = GetItemWithImages(imageType, imageCount, false); + + var libraryOptions = GetLibraryOptions(item, imageType, imageCount); + + var remoteProvider = new Mock<IRemoteImageProvider>(MockBehavior.Strict); + remoteProvider.Setup(rp => rp.Name).Returns("MockRemoteProvider"); + remoteProvider.Setup(rp => rp.GetSupportedImages(item)) + .Returns(new[] { imageType }); + + var refreshOptions = new ImageRefreshOptions(Mock.Of<IDirectoryService>()) + { + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllImages = true + }; + + var itemImageProvider = GetItemImageProvider(Mock.Of<IProviderManager>(), null); + var result = await itemImageProvider.RefreshImages(item, libraryOptions, new List<IImageProvider> { remoteProvider.Object }, refreshOptions, CancellationToken.None); + + Assert.False(result.UpdateType.HasFlag(ItemUpdateType.ImageUpdate)); + Assert.Equal(imageCount, item.GetImages(imageType).Count()); + } + + private static ItemImageProvider GetItemImageProvider(IProviderManager? providerManager, Mock<IFileSystem>? mockFileSystem) + { + // strict to ensure this isn't accidentally used where a prepared mock is intended + providerManager ??= Mock.Of<IProviderManager>(MockBehavior.Strict); + + // BaseItem.ValidateImages depends on the directory service being able to list directory contents, give it the expected valid file paths + mockFileSystem ??= new Mock<IFileSystem>(MockBehavior.Strict); + mockFileSystem.Setup(fs => fs.GetFilePaths(It.IsAny<string>(), It.IsAny<bool>())) + .Returns(new[] + { + string.Format(CultureInfo.InvariantCulture, TestDataImagePath, 0), + string.Format(CultureInfo.InvariantCulture, TestDataImagePath, 1) + }); + + return new ItemImageProvider(new NullLogger<ItemImageProvider>(), providerManager, mockFileSystem.Object); + } + + private static BaseItem GetItemWithImages(ImageType type, int count, bool validPaths) + { + // Has to exist for querying DateModified time on file, results stored but not checked so not populating + BaseItem.FileSystem ??= Mock.Of<IFileSystem>(); + + var item = new Video(); + + var path = validPaths ? TestDataImagePath : "invalid path {0}"; + for (int i = 0; i < count; i++) + { + item.SetImagePath(type, i, new FileSystemMetadata + { + FullName = string.Format(CultureInfo.InvariantCulture, path, i), + }); + } + + return item; + } + + private static ILocalImageProvider GetImageProvider(ImageType type, int count, bool validPaths) + { + var images = GetImages(type, count, validPaths); + + var imageProvider = new Mock<ILocalImageProvider>(); + imageProvider.Setup(ip => ip.GetImages(It.IsAny<BaseItem>(), It.IsAny<IDirectoryService>())) + .Returns(images); + return imageProvider.Object; + } + + /// <summary> + /// Creates a list of <see cref="LocalImageInfo"/> references of the specified type and size, optionally pointing to files that exist. + /// </summary> + private static LocalImageInfo[] GetImages(ImageType type, int count, bool validPaths) + { + var path = validPaths ? TestDataImagePath : "invalid path {0}"; + var images = new LocalImageInfo[count]; + for (int i = 0; i < count; i++) + { + images[i] = new LocalImageInfo + { + Type = type, + FileInfo = new FileSystemMetadata + { + FullName = string.Format(CultureInfo.InvariantCulture, path, i) + } + }; + } + + return images; + } + + /// <summary> + /// Generates a <see cref="LibraryOptions"/> object that will allow for the requested number of images for the target type. + /// </summary> + private static LibraryOptions GetLibraryOptions(BaseItem item, ImageType type, int count) + { + return new LibraryOptions + { + TypeOptions = new[] + { + new TypeOptions + { + Type = item.GetType().Name, + ImageOptions = new[] + { + new ImageOption + { + Type = type, + Limit = count, + MinWidth = 0 + } + } + } + } + }; + } + } +} diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs index b194e3885..558321810 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/EmbeddedImageProviderTests.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -5,11 +6,14 @@ using System.Threading.Tasks; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Providers.MediaInfo; +using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -17,200 +21,136 @@ namespace Jellyfin.Providers.Tests.MediaInfo { public class EmbeddedImageProviderTests { - private static TheoryData<BaseItem> GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty_TestData() - { - return new () - { - new AudioBook(), - new BoxSet(), - new Series(), - new Season(), - }; - } - [Theory] - [MemberData(nameof(GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty_TestData))] - public void GetSupportedImages_UnsupportedBaseItems_ReturnsEmpty(BaseItem item) + [InlineData(typeof(AudioBook))] + [InlineData(typeof(BoxSet))] + [InlineData(typeof(Series))] + [InlineData(typeof(Season))] + [InlineData(typeof(Episode), ImageType.Primary)] + [InlineData(typeof(Movie), ImageType.Logo, ImageType.Backdrop, ImageType.Primary)] + public void GetSupportedImages_AnyBaseItem_ReturnsExpected(Type type, params ImageType[] expected) { - var embeddedImageProvider = GetEmbeddedImageProvider(null); - Assert.Empty(embeddedImageProvider.GetSupportedImages(item)); - } - - private static TheoryData<BaseItem, IEnumerable<ImageType>> GetSupportedImages_SupportedBaseItems_ReturnsPopulated_TestData() - { - return new TheoryData<BaseItem, IEnumerable<ImageType>> - { - { new Episode(), new List<ImageType> { ImageType.Primary } }, - { new Movie(), new List<ImageType> { ImageType.Logo, ImageType.Backdrop, ImageType.Primary } }, - }; - } - - [Theory] - [MemberData(nameof(GetSupportedImages_SupportedBaseItems_ReturnsPopulated_TestData))] - public void GetSupportedImages_SupportedBaseItems_ReturnsPopulated(BaseItem item, IEnumerable<ImageType> expected) - { - var embeddedImageProvider = GetEmbeddedImageProvider(null); + BaseItem item = (BaseItem)Activator.CreateInstance(type)!; + var embeddedImageProvider = new EmbeddedImageProvider(Mock.Of<IMediaSourceManager>(), Mock.Of<IMediaEncoder>(), new NullLogger<EmbeddedImageProvider>()); var actual = embeddedImageProvider.GetSupportedImages(item); Assert.Equal(expected.OrderBy(i => i.ToString()), actual.OrderBy(i => i.ToString())); } [Fact] - public async void GetImage_InputWithNoStreams_ReturnsNoImage() + public async void GetImage_NoStreams_ReturnsNoImage() { - var embeddedImageProvider = GetEmbeddedImageProvider(null); + var input = new Movie(); - var input = GetMovie(new List<MediaAttachment>(), new List<MediaStream>()); + var mediaSourceManager = GetMediaSourceManager(input, new List<MediaAttachment>(), new List<MediaStream>()); + var embeddedImageProvider = new EmbeddedImageProvider(mediaSourceManager, null, new NullLogger<EmbeddedImageProvider>()); var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); Assert.NotNull(actual); Assert.False(actual.HasImage); } - [Fact] - public async void GetImage_InputWithUnlabeledAttachments_ReturnsNoImage() + [Theory] + [InlineData("chapter", null, 1, ImageType.Chapter, null)] // unexpected type, nothing found + [InlineData("unmatched", null, 1, ImageType.Primary, null)] // doesn't default on no match + [InlineData("clearlogo.png", null, 1, ImageType.Logo, ImageFormat.Png)] // extract extension from name + [InlineData("backdrop", "image/bmp", 2, ImageType.Backdrop, ImageFormat.Bmp)] // extract extension from mimetype + [InlineData("poster", null, 3, ImageType.Primary, ImageFormat.Jpg)] // default extension to jpg + public async void GetImage_Attachment_ReturnsCorrectSelection(string filename, string mimetype, int targetIndex, ImageType type, ImageFormat? expectedFormat) { - var embeddedImageProvider = GetEmbeddedImageProvider(null); - - // add an attachment without a filename - has a list to look through but finds nothing - var input = GetMovie( - new List<MediaAttachment> { new () }, - new List<MediaStream>()); - - var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actual); - Assert.False(actual.HasImage); - } + var attachments = new List<MediaAttachment>(); + string pathPrefix = "path"; + for (int i = 1; i <= targetIndex; i++) + { + var name = i == targetIndex ? filename : "unmatched"; + attachments.Add(new () + { + FileName = name, + MimeType = mimetype, + Index = i + }); + } - [Fact] - public async void GetImage_InputWithLabeledAttachments_ReturnsCorrectSelection() - { - // first tests file extension detection, second uses mimetype, third defaults to jpg - MediaAttachment sampleAttachment1 = new () { FileName = "clearlogo.png", Index = 1 }; - MediaAttachment sampleAttachment2 = new () { FileName = "backdrop", MimeType = "image/bmp", Index = 2 }; - MediaAttachment sampleAttachment3 = new () { FileName = "poster", Index = 3 }; - string targetPath1 = "path1.png"; - string targetPath2 = "path2.bmp"; - string targetPath3 = "path2.jpg"; + var input = new Movie(); var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 1, ".png", CancellationToken.None)) - .Returns(Task.FromResult(targetPath1)); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 2, ".bmp", CancellationToken.None)) - .Returns(Task.FromResult(targetPath2)); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), 3, ".jpg", CancellationToken.None)) - .Returns(Task.FromResult(targetPath3)); - var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object); - - var input = GetMovie( - new List<MediaAttachment> { sampleAttachment1, sampleAttachment2, sampleAttachment3 }, - new List<MediaStream>()); - - var actualLogo = await embeddedImageProvider.GetImage(input, ImageType.Logo, CancellationToken.None); - Assert.NotNull(actualLogo); - Assert.True(actualLogo.HasImage); - Assert.Equal(targetPath1, actualLogo.Path); - Assert.Equal(ImageFormat.Png, actualLogo.Format); - - var actualBackdrop = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None); - Assert.NotNull(actualBackdrop); - Assert.True(actualBackdrop.HasImage); - Assert.Equal(targetPath2, actualBackdrop.Path); - Assert.Equal(ImageFormat.Bmp, actualBackdrop.Format); - - var actualPrimary = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actualPrimary); - Assert.True(actualPrimary.HasImage); - Assert.Equal(targetPath3, actualPrimary.Path); - Assert.Equal(ImageFormat.Jpg, actualPrimary.Format); - } - - [Fact] - public async void GetImage_InputWithUnlabeledEmbeddedImages_BackdropReturnsNoImage() - { - var embeddedImageProvider = GetEmbeddedImageProvider(null); + mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<int>(), It.IsAny<ImageFormat>(), It.IsAny<CancellationToken>())) + .Returns<string, string, MediaSourceInfo, MediaStream, int, ImageFormat, CancellationToken>((_, _, _, _, index, ext, _) => Task.FromResult(pathPrefix + index + "." + ext)); + var mediaSourceManager = GetMediaSourceManager(input, attachments, new List<MediaStream>()); + var embeddedImageProvider = new EmbeddedImageProvider(mediaSourceManager, mediaEncoder.Object, new NullLogger<EmbeddedImageProvider>()); - var input = GetMovie( - new List<MediaAttachment>(), - new List<MediaStream> { new () { Type = MediaStreamType.EmbeddedImage } }); - - var actual = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None); + var actual = await embeddedImageProvider.GetImage(input, type, CancellationToken.None); Assert.NotNull(actual); - Assert.False(actual.HasImage); + if (expectedFormat == null) + { + Assert.False(actual.HasImage); + } + else + { + Assert.True(actual.HasImage); + Assert.Equal(pathPrefix + targetIndex + "." + expectedFormat, actual.Path, StringComparer.OrdinalIgnoreCase); + Assert.Equal(expectedFormat, actual.Format); + } } - [Fact] - public async void GetImage_InputWithUnlabeledEmbeddedImages_PrimaryReturnsImage() + [Theory] + [InlineData("chapter", null, 1, ImageType.Chapter, null)] // unexpected type, nothing found + [InlineData(null, null, 1, ImageType.Backdrop, null)] // no label, can only find primary + [InlineData(null, null, 1, ImageType.Primary, ImageFormat.Jpg)] // no label, finds primary + [InlineData("backdrop", null, 2, ImageType.Backdrop, ImageFormat.Jpg)] // uses label to find index 2, not just pulling first stream + [InlineData("cover", null, 2, ImageType.Primary, ImageFormat.Jpg)] // uses label to find index 2, not just pulling first stream + [InlineData(null, "mjpeg", 1, ImageType.Primary, ImageFormat.Jpg)] + [InlineData(null, "png", 1, ImageType.Primary, ImageFormat.Png)] + [InlineData(null, "gif", 1, ImageType.Primary, ImageFormat.Gif)] + public async void GetImage_Embedded_ReturnsCorrectSelection(string label, string? codec, int targetIndex, ImageType type, ImageFormat? expectedFormat) { - MediaStream sampleStream = new () { Type = MediaStreamType.EmbeddedImage, Index = 1 }; - string targetPath = "path"; - + var streams = new List<MediaStream>(); + for (int i = 1; i <= targetIndex; i++) + { + var comment = i == targetIndex ? label : "unmatched"; + streams.Add(new () + { + Type = MediaStreamType.EmbeddedImage, + Index = i, + Comment = comment, + Codec = codec + }); + } + + var input = new Movie(); + + var pathPrefix = "path"; var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream, 1, ".jpg", CancellationToken.None)) - .Returns(Task.FromResult(targetPath)); - var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object); - - var input = GetMovie( - new List<MediaAttachment>(), - new List<MediaStream> { sampleStream }); - - var actual = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); + mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<int>(), It.IsAny<ImageFormat>(), It.IsAny<CancellationToken>())) + .Returns<string, string, MediaSourceInfo, MediaStream, int, ImageFormat, CancellationToken>((_, _, _, stream, index, ext, _) => + { + Assert.Equal(streams[index - 1], stream); + return Task.FromResult(pathPrefix + index + "." + ext); + }); + var mediaSourceManager = GetMediaSourceManager(input, new List<MediaAttachment>(), streams); + var embeddedImageProvider = new EmbeddedImageProvider(mediaSourceManager, mediaEncoder.Object, new NullLogger<EmbeddedImageProvider>()); + + var actual = await embeddedImageProvider.GetImage(input, type, CancellationToken.None); Assert.NotNull(actual); - Assert.True(actual.HasImage); - Assert.Equal(targetPath, actual.Path); - Assert.Equal(ImageFormat.Jpg, actual.Format); - } - - [Fact] - public async void GetImage_InputWithLabeledEmbeddedImages_ReturnsCorrectSelection() - { - // primary is second stream to ensure it's not defaulting, backdrop is first - MediaStream sampleStream1 = new () { Type = MediaStreamType.EmbeddedImage, Index = 1, Comment = "backdrop" }; - MediaStream sampleStream2 = new () { Type = MediaStreamType.EmbeddedImage, Index = 2, Comment = "cover" }; - string targetPath1 = "path1.jpg"; - string targetPath2 = "path2.jpg"; - - var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream1, 1, ".jpg", CancellationToken.None)) - .Returns(Task.FromResult(targetPath1)); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), sampleStream2, 2, ".jpg", CancellationToken.None)) - .Returns(Task.FromResult(targetPath2)); - var embeddedImageProvider = GetEmbeddedImageProvider(mediaEncoder.Object); - - var input = GetMovie( - new List<MediaAttachment>(), - new List<MediaStream> { sampleStream1, sampleStream2 }); - - var actualPrimary = await embeddedImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actualPrimary); - Assert.True(actualPrimary.HasImage); - Assert.Equal(targetPath2, actualPrimary.Path); - Assert.Equal(ImageFormat.Jpg, actualPrimary.Format); - - var actualBackdrop = await embeddedImageProvider.GetImage(input, ImageType.Backdrop, CancellationToken.None); - Assert.NotNull(actualBackdrop); - Assert.True(actualBackdrop.HasImage); - Assert.Equal(targetPath1, actualBackdrop.Path); - Assert.Equal(ImageFormat.Jpg, actualBackdrop.Format); - } - - private static EmbeddedImageProvider GetEmbeddedImageProvider(IMediaEncoder? mediaEncoder) - { - return new EmbeddedImageProvider(mediaEncoder); + if (expectedFormat == null) + { + Assert.False(actual.HasImage); + } + else + { + Assert.True(actual.HasImage); + Assert.Equal(pathPrefix + targetIndex + "." + expectedFormat, actual.Path, StringComparer.OrdinalIgnoreCase); + Assert.Equal(expectedFormat, actual.Format); + } } - private static Movie GetMovie(List<MediaAttachment> mediaAttachments, List<MediaStream> mediaStreams) + private static IMediaSourceManager GetMediaSourceManager(BaseItem item, List<MediaAttachment> mediaAttachments, List<MediaStream> mediaStreams) { - // Mocking IMediaSourceManager GetMediaAttachments and GetMediaStreams instead of mocking Movie works, but - // has concurrency problems between this and VideoImageProviderTests due to BaseItem.MediaSourceManager - // being static - var movie = new Mock<Movie>(); - - movie.Setup(item => item.GetMediaSources(It.IsAny<bool>())) - .Returns(new List<MediaSourceInfo> { new () { MediaAttachments = mediaAttachments } } ); - movie.Setup(item => item.GetMediaStreams()) + var mediaSourceManager = new Mock<IMediaSourceManager>(MockBehavior.Strict); + mediaSourceManager.Setup(i => i.GetMediaAttachments(item.Id)) + .Returns(mediaAttachments); + mediaSourceManager.Setup(i => i.GetMediaStreams(It.Is<MediaStreamQuery>(q => q.ItemId == item.Id && q.Type == MediaStreamType.EmbeddedImage))) .Returns(mediaStreams); - - return movie.Object; + return mediaSourceManager.Object; } } } diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs index c289a7112..33da277e3 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs @@ -80,6 +80,37 @@ namespace Jellyfin.Providers.Tests.MediaInfo } } + [Theory] + [InlineData("/video/My Video.mkv", "/video/My Video.srt", "srt", null, false, false)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.srt", "srt", null, false, false)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.foreign.srt", "srt", null, true, false)] + [InlineData("/video/My Video.mkv", "/video/My Video.forced.srt", "srt", null, true, false)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.default.srt", "srt", null, false, true)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.forced.default.srt", "srt", null, true, true)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.en.srt", "srt", "en", false, false)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.default.en.srt", "srt", "en", false, true)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.default.forced.en.srt", "srt", "en", true, true)] + [InlineData("/video/My.Video.mkv", "/video/My.Video.en.default.forced.srt", "srt", "en", true, true)] + public void AddExternalSubtitleStreams_GivenSingleFile_ReturnsExpectedSubtitle(string videoPath, string file, string codec, string? language, bool isForced, bool isDefault) + { + var streams = new List<MediaStream>(); + var expected = CreateMediaStream(file, codec, language, 0, isForced, isDefault); + + new SubtitleResolver(Mock.Of<ILocalizationManager>()).AddExternalSubtitleStreams(streams, videoPath, 0, new[] { file }); + + Assert.Single(streams); + + var actual = streams[0]; + + Assert.Equal(expected.Index, actual.Index); + Assert.Equal(expected.Type, actual.Type); + Assert.Equal(expected.IsExternal, actual.IsExternal); + Assert.Equal(expected.Path, actual.Path); + Assert.Equal(expected.IsDefault, actual.IsDefault); + Assert.Equal(expected.IsForced, actual.IsForced); + Assert.Equal(expected.Language, actual.Language); + } + private static MediaStream CreateMediaStream(string path, string codec, string? language, int index, bool isForced = false, bool isDefault = false) { return new () diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs index 0f51a2b8f..839925dd1 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/VideoImageProviderTests.cs @@ -2,8 +2,11 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; @@ -16,85 +19,56 @@ namespace Jellyfin.Providers.Tests.MediaInfo { public class VideoImageProviderTests { - [Fact] - public async void GetImage_InputIsPlaceholder_ReturnsNoImage() + private static TheoryData<Video> GetImage_UnsupportedInput_ReturnsNoImage_TestData() { - var videoImageProvider = GetVideoImageProvider(null); - - var input = new Movie + return new () { - IsPlaceHolder = true - }; - - var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actual); - Assert.False(actual.HasImage); - } + new Movie { IsPlaceHolder = true }, - [Fact] - public async void GetImage_NoDefaultVideoStream_ReturnsNoImage() - { - var videoImageProvider = GetVideoImageProvider(null); + new Movie { DefaultVideoStreamIndex = null }, - var input = new Movie - { - DefaultVideoStreamIndex = null + // set a default index but don't put anything there (invalid input, but provider shouldn't break) + new Movie { DefaultVideoStreamIndex = 0 } }; - - var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actual); - Assert.False(actual.HasImage); } - [Fact] - public async void GetImage_DefaultSetButNoVideoStream_ReturnsNoImage() + [Theory] + [MemberData(nameof(GetImage_UnsupportedInput_ReturnsNoImage_TestData))] + public async void GetImage_UnsupportedInput_ReturnsNoImage(Video input) { - var videoImageProvider = GetVideoImageProvider(null); - - // set a default index but don't put anything there (invalid input, but provider shouldn't break) - var input = GetMovie(0, null, new List<MediaStream>()); + var mediaSourceManager = GetMediaSourceManager(input, null, new List<MediaStream>()); + var videoImageProvider = new VideoImageProvider(mediaSourceManager, Mock.Of<IMediaEncoder>(), new NullLogger<VideoImageProvider>()); var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); Assert.NotNull(actual); Assert.False(actual.HasImage); } - [Fact] - public async void GetImage_DefaultSetMultipleVideoStreams_ReturnsDefaultStreamImage() + [Theory] + [InlineData(1, 1)] // default not first stream + [InlineData(5, 0)] // default out of valid range + public async void GetImage_DefaultVideoStreams_ReturnsCorrectStreamImage(int defaultIndex, int targetIndex) { - MediaStream firstStream = new () { Type = MediaStreamType.Video, Index = 0 }; - MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 1 }; - string targetPath = "path.jpg"; + var input = new Movie { DefaultVideoStreamIndex = defaultIndex }; + string targetPath = "path.jpg"; + var mediaStreams = new List<MediaStream>(); var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), firstStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None)) - .Returns(Task.FromResult("wrong stream called!")); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), targetStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None)) - .Returns(Task.FromResult(targetPath)); - var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object); - var input = GetMovie(1, targetStream, new List<MediaStream> { firstStream, targetStream } ); - - var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.NotNull(actual); - Assert.True(actual.HasImage); - Assert.Equal(targetPath, actual.Path); - Assert.Equal(ImageFormat.Jpg, actual.Format); - } + for (int i = 0; i <= targetIndex; i++) + { + var mediaStream = new MediaStream { Type = MediaStreamType.Video, Index = i }; + mediaStreams.Add(mediaStream); - [Fact] - public async void GetImage_InvalidDefaultSingleVideoStream_ReturnsFirstVideoStreamImage() - { - MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 }; - string targetPath = "path.jpg"; + var path = i == targetIndex ? targetPath : "wrong stream called!"; + mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), mediaStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>())) + .Returns(Task.FromResult(path)); + } - var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), targetStream, It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None)) - .Returns(Task.FromResult(targetPath)); - var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object); + var defaultStream = defaultIndex < mediaStreams.Count ? mediaStreams[targetIndex] : null; + var mediaSourceManager = GetMediaSourceManager(input, defaultStream, mediaStreams); - // provide query results for default (empty) and all streams (populated) - var input = GetMovie(5, null, new List<MediaStream> { targetStream }); + var videoImageProvider = new VideoImageProvider(mediaSourceManager, mediaEncoder.Object, new NullLogger<VideoImageProvider>()); var actual = await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); Assert.NotNull(actual); @@ -103,10 +77,19 @@ namespace Jellyfin.Providers.Tests.MediaInfo Assert.Equal(ImageFormat.Jpg, actual.Format); } - [Fact] - public async void GetImage_NoTimeSpanSet_CallsEncoderWithDefaultTime() + [Theory] + [InlineData(null, 10)] // default time + [InlineData(500, 50)] // calculated time + public async void GetImage_TimeSpan_SelectsCorrectTime(int? runTimeSeconds, long expectedSeconds) { MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 }; + var input = new Movie + { + DefaultVideoStreamIndex = 0, + RunTimeTicks = runTimeSeconds * TimeSpan.TicksPerSecond + }; + + var mediaSourceManager = GetMediaSourceManager(input, targetStream, new List<MediaStream> { targetStream }); // use a callback to catch the actual value // provides more information on failure than verifying a specific input was called on the mock @@ -115,62 +98,29 @@ namespace Jellyfin.Providers.Tests.MediaInfo mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None)) .Callback<string, string, MediaSourceInfo, MediaStream, Video3DFormat?, TimeSpan?, CancellationToken>((_, _, _, _, _, timeSpan, _) => actualTimeSpan = timeSpan) .Returns(Task.FromResult("path")); - var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object); - var input = GetMovie(0, targetStream, new List<MediaStream> { targetStream }); + var videoImageProvider = new VideoImageProvider(mediaSourceManager, mediaEncoder.Object, new NullLogger<VideoImageProvider>()); // not testing return, just verifying what gets requested for time span await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - Assert.Equal(TimeSpan.FromSeconds(10), actualTimeSpan); + Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), actualTimeSpan); } - [Fact] - public async void GetImage_TimeSpanSet_CallsEncoderWithCalculatedTime() + private static IMediaSourceManager GetMediaSourceManager(Video item, MediaStream? defaultStream, List<MediaStream> mediaStreams) { - MediaStream targetStream = new () { Type = MediaStreamType.Video, Index = 0 }; - - TimeSpan? actualTimeSpan = null; - var mediaEncoder = new Mock<IMediaEncoder>(MockBehavior.Strict); - mediaEncoder.Setup(encoder => encoder.ExtractVideoImage(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MediaSourceInfo>(), It.IsAny<MediaStream>(), It.IsAny<Video3DFormat?>(), It.IsAny<TimeSpan?>(), CancellationToken.None)) - .Callback<string, string, MediaSourceInfo, MediaStream, Video3DFormat?, TimeSpan?, CancellationToken>((_, _, _, _, _, timeSpan, _) => actualTimeSpan = timeSpan) - .Returns(Task.FromResult("path")); - var videoImageProvider = GetVideoImageProvider(mediaEncoder.Object); - - var input = GetMovie(0, targetStream, new List<MediaStream> { targetStream }); - input.RunTimeTicks = 5000; - - // not testing return, just verifying what gets requested for time span - await videoImageProvider.GetImage(input, ImageType.Primary, CancellationToken.None); - - Assert.Equal(TimeSpan.FromTicks(500), actualTimeSpan); - } - - private static VideoImageProvider GetVideoImageProvider(IMediaEncoder? mediaEncoder) - { - // strict to ensure this isn't accidentally used where a prepared mock is intended - mediaEncoder ??= new Mock<IMediaEncoder>(MockBehavior.Strict).Object; - return new VideoImageProvider(mediaEncoder, new NullLogger<VideoImageProvider>()); - } - - private static Movie GetMovie(int defaultVideoStreamIndex, MediaStream? defaultStream, List<MediaStream> mediaStreams) - { - // Mocking IMediaSourceManager GetMediaStreams instead of mocking Movie works, but has concurrency problems - // between this and EmbeddedImageProviderTests due to BaseItem.MediaSourceManager being static - var movie = new Mock<Movie> + var defaultStreamList = new List<MediaStream>(); + if (defaultStream != null) { - Object = - { - DefaultVideoStreamIndex = defaultVideoStreamIndex - } - }; + defaultStreamList.Add(defaultStream); + } - movie.Setup(item => item.GetDefaultVideoStream()) - .Returns(defaultStream!); - movie.Setup(item => item.GetMediaStreams()) + var mediaSourceManager = new Mock<IMediaSourceManager>(MockBehavior.Strict); + mediaSourceManager.Setup(i => i.GetMediaStreams(It.Is<MediaStreamQuery>(q => q.ItemId == item.Id && q.Index == item.DefaultVideoStreamIndex))) + .Returns(defaultStreamList); + mediaSourceManager.Setup(i => i.GetMediaStreams(It.Is<MediaStreamQuery>(q => q.ItemId == item.Id && q.Type == MediaStreamType.Video))) .Returns(mediaStreams); - - return movie.Object; + return mediaSourceManager.Object; } } } diff --git a/tests/Jellyfin.Providers.Tests/Test Data/Images/blank0.jpg b/tests/Jellyfin.Providers.Tests/Test Data/Images/blank0.jpg new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Test Data/Images/blank0.jpg diff --git a/tests/Jellyfin.Providers.Tests/Test Data/Images/blank1.jpg b/tests/Jellyfin.Providers.Tests/Test Data/Images/blank1.jpg new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Test Data/Images/blank1.jpg diff --git a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs index f6a7c676f..efd2d9553 100644 --- a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs +++ b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs @@ -23,5 +23,18 @@ namespace Jellyfin.Providers.Tests.Tmdb { Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input!)); } + + [Theory] + [InlineData(null, null, null)] + [InlineData(null, "en-US", null)] + [InlineData("en", null, "en")] + [InlineData("en", "en-US", "en-US")] + [InlineData("fr-CA", "fr-BE", "fr-CA")] + [InlineData("fr-CA", "fr", "fr-CA")] + [InlineData("de", "en-US", "de")] + public static void AdjustImageLanguage_Valid_Success(string imageLanguage, string requestLanguage, string expected) + { + Assert.Equal(expected, TmdbUtils.AdjustImageLanguage(imageLanguage, requestLanguage)); + } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 5ecd84604..028ebdf55 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -21,7 +21,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.17.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs index c393742eb..a0fe4a5cf 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs @@ -1,5 +1,4 @@ -using System; -using Emby.Server.Implementations.Library.Resolvers.TV; +using Emby.Server.Implementations.Library.Resolvers.TV; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; @@ -17,19 +16,16 @@ namespace Jellyfin.Server.Implementations.Tests.Library [Fact] public void Resolve_GivenVideoInExtrasFolder_DoesNotResolveToEpisode() { - var season = new Season { Name = "Season 1" }; var parent = new Folder { Name = "extras" }; - var libraryManagerMock = new Mock<ILibraryManager>(); - libraryManagerMock.Setup(x => x.GetItemById(It.IsAny<Guid>())).Returns(season); - var episodeResolver = new EpisodeResolver(libraryManagerMock.Object); + var episodeResolver = new EpisodeResolver(null); var itemResolveArgs = new ItemResolveArgs( Mock.Of<IServerApplicationPaths>(), Mock.Of<IDirectoryService>()) { Parent = parent, CollectionType = CollectionType.TvShows, - FileInfo = new FileSystemMetadata() + FileInfo = new FileSystemMetadata { FullName = "All My Children/Season 01/Extras/All My Children S01E01 - Behind The Scenes.mkv" } @@ -45,7 +41,7 @@ namespace Jellyfin.Server.Implementations.Tests.Library // Have to create a mock because of moq proxies not being castable to a concrete implementation // https://github.com/jellyfin/jellyfin/blob/ab0cff8556403e123642dc9717ba778329554634/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs#L48 - var episodeResolver = new EpisodeResolverMock(Mock.Of<ILibraryManager>()); + var episodeResolver = new EpisodeResolverMock(); var itemResolveArgs = new ItemResolveArgs( Mock.Of<IServerApplicationPaths>(), Mock.Of<IDirectoryService>()) @@ -62,7 +58,7 @@ namespace Jellyfin.Server.Implementations.Tests.Library private class EpisodeResolverMock : EpisodeResolver { - public EpisodeResolverMock(ILibraryManager libraryManager) : base(libraryManager) + public EpisodeResolverMock() : base(null) { } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs new file mode 100644 index 000000000..8ed3d8b94 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs @@ -0,0 +1,32 @@ +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.IO; +using Emby.Server.Implementations.Library; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.MediaInfo; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Library +{ + public class MediaSourceManagerTests + { + private readonly MediaSourceManager _mediaSourceManager; + + public MediaSourceManagerTests() + { + IFixture fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }); + fixture.Inject<IFileSystem>(fixture.Create<ManagedFileSystem>()); + _mediaSourceManager = fixture.Create<MediaSourceManager>(); + } + + [Theory] + [InlineData(@"C:\mydir\myfile.ext", MediaProtocol.File)] + [InlineData("/mydir/myfile.ext", MediaProtocol.File)] + [InlineData("file:///mydir/myfile.ext", MediaProtocol.File)] + [InlineData("http://example.com/stream.m3u8", MediaProtocol.Http)] + [InlineData("https://example.com/stream.m3u8", MediaProtocol.Http)] + [InlineData("rtsp://media.example.com:554/twister/audiotrack", MediaProtocol.Rtsp)] + public void GetPathProtocol_ValidArg_Correct(string path, MediaProtocol expected) + => Assert.Equal(expected, _mediaSourceManager.GetPathProtocol(path)); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs index 976afe195..09aec82b0 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs @@ -61,7 +61,7 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { Name = "The Big Bang Theory", IsProgramSeries = true, - OriginalAirDate = new DateTime(2018, 12, 6) + OriginalAirDate = new DateTime(2018, 12, 6, 0, 0, 0, DateTimeKind.Local) }); data.Add( @@ -70,7 +70,7 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { Name = "The Big Bang Theory", IsProgramSeries = true, - OriginalAirDate = new DateTime(2018, 12, 6), + OriginalAirDate = new DateTime(2018, 12, 6, 0, 0, 0, DateTimeKind.Local), EpisodeTitle = "The VCR Illumination" }); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs index 143020d43..3e7d6ed1d 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs @@ -40,7 +40,7 @@ namespace Jellyfin.Server.Implementations.Tests.Localization await localizationManager.LoadAll(); var cultures = localizationManager.GetCultures().ToList(); - Assert.Equal(189, cultures.Count); + Assert.Equal(190, cultures.Count); var germany = cultures.FirstOrDefault(x => x.TwoLetterISOLanguageName.Equals("de", StringComparison.Ordinal)); Assert.NotNull(germany); diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs index 827365363..3396a94e5 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs @@ -40,7 +40,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(MediaTypeNames.Text.Html, response.Content.Headers.ContentType?.MediaType); StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Server.Integration.Tests.TestPage.html")!); - Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd()); + Assert.Equal(await response.Content.ReadAsStringAsync().ConfigureAwait(false), await reader.ReadToEndAsync().ConfigureAwait(false)); } [Fact] diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 9d7b447ed..5b884cddf 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -9,9 +9,9 @@ <PackageReference Include="AutoFixture" Version="4.17.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="Xunit.Priority" Version="1.1.6" /> diff --git a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs index 976e19d46..3d34a18e7 100644 --- a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs @@ -3,7 +3,6 @@ using System.Collections.Concurrent; using System.IO; using System.Threading; using Emby.Server.Implementations; -using Emby.Server.Implementations.IO; using MediaBrowser.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; @@ -67,7 +66,7 @@ namespace Jellyfin.Server.Integration.Tests var startupConfig = Program.CreateAppConfiguration(commandLineOpts, appPaths); ILoggerFactory loggerFactory = new SerilogLoggerFactory(); - var serviceCollection = new ServiceCollection(); + _disposableComponents.Add(loggerFactory); // Create the app host and initialize it @@ -75,11 +74,10 @@ namespace Jellyfin.Server.Integration.Tests appPaths, loggerFactory, commandLineOpts, - new ConfigurationBuilder().Build(), - new ManagedFileSystem(loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths), - serviceCollection); + new ConfigurationBuilder().Build()); _disposableComponents.Add(appHost); - appHost.Init(); + var serviceCollection = new ServiceCollection(); + appHost.Init(serviceCollection); // Configure the web host builder Program.ConfigureWebHostBuilder(builder, appHost, serviceCollection, commandLineOpts, startupConfig, appPaths); diff --git a/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs index 0a463cfa3..bf74efa09 100644 --- a/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs +++ b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs @@ -2,9 +2,7 @@ using System.Collections.Generic; using System.Reflection; using Emby.Server.Implementations; using MediaBrowser.Controller; -using MediaBrowser.Model.IO; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Integration.Tests @@ -21,22 +19,16 @@ namespace Jellyfin.Server.Integration.Tests /// <param name="loggerFactory">The <see cref="ILoggerFactory" /> to be used by the <see cref="CoreAppHost" />.</param> /// <param name="options">The <see cref="StartupOptions" /> to be used by the <see cref="CoreAppHost" />.</param> /// <param name="startup">The <see cref="IConfiguration" /> to be used by the <see cref="CoreAppHost" />.</param> - /// <param name="fileSystem">The <see cref="IFileSystem" /> to be used by the <see cref="CoreAppHost" />.</param> - /// <param name="collection">The <see cref="IServiceCollection"/> to be used by the <see cref="CoreAppHost"/>.</param> public TestAppHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, - IConfiguration startup, - IFileSystem fileSystem, - IServiceCollection collection) + IConfiguration startup) : base( applicationPaths, loggerFactory, options, - startup, - fileSystem, - collection) + startup) { } diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 67ae0e080..29d7646a6 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -10,9 +10,9 @@ <PackageReference Include="AutoFixture" Version="4.17.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0-rc.2*" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="3.1.0" /> diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index 94294c8bf..edf9e0fef 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -13,7 +13,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> |
