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**
-
-
-**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**
-
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
-
-**Expected behavior**
-
-
-**Server Logs**
-
-
-**FFmpeg Logs**
-
-
-**Browser Console Logs**
-
-
-**Screenshots**
-
-
-**Additional context**
-
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: |
+
+
+ Changes in OpenAPI specification found. Expand to see details.
+
+ ${{ steps.read-diff.outputs.body }}
+
+
+ - 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: |
+
+
+ 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 @@
enable
- true
$(MSBuildThisFileDirectory)/jellyfin.ruleset
+
+ true
+
+
AllEnabledByDefault
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 ""
+ ""
+ ""
- + ""
- + ""
- + ""
+ + ""
+ + ""
+ + ""
+ ""
+ "";
}
@@ -330,75 +329,73 @@ namespace Emby.Dlna.ContentDirectory
int totalCount;
- using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
+ var settings = new XmlWriterSettings
{
- 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))
+ {
+ 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(id);
+ var item = serverItem.Item;
+
+ if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal))
{
- Encoding = Encoding.UTF8,
- CloseOutput = false,
- OmitXmlDeclaration = true,
- ConformanceLevel = ConformanceLevel.Fragment
- };
+ totalCount = 1;
- 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(id);
- var item = serverItem.Item;
-
- if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal))
+ if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue)
{
- totalCount = 1;
+ var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount);
- 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);
- }
-
- 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;
-
- provided = childrenResult.Items.Count;
-
- foreach (var i in childrenResult.Items)
- {
- 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, item, _user, null, null, deviceId, filter);
}
- writer.WriteFullEndElement();
+ 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;
+
+ 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);
+ }
+ }
}
+ writer.WriteFullEndElement();
+ writer.Flush();
xmlWriter.WriteElementString("Result", builder.ToString());
}
@@ -449,53 +446,46 @@ namespace Emby.Dlna.ContentDirectory
}
QueryResult 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()
+ 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"]);
+
+ var item = serverItem.Item;
+
+ childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount);
+ foreach (var i in childrenResult.Items)
{
- 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"]);
-
- var item = serverItem.Item;
-
- childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount);
-
- var dlnaOptions = _config.GetDlnaConfiguration();
-
- 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();
bool? isFolder = null;
- if (search.SearchType == SearchType.Audio)
+ switch (search.SearchType)
{
- 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();
- isFolder = true;
- }
- else if (search.SearchType == SearchType.MusicAlbum)
- {
- // items = items.OfType();
- 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
/// The .
private QueryResult GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit)
{
- if (item is MusicGenre)
+ switch (item)
{
- return GetMusicGenreItems(item, Guid.Empty, user, sort, startIndex, limit);
+ 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 MusicArtist)
+ if (stubType != StubType.Folder && item is IHasCollectionType collectionFolder)
{
- return GetMusicArtistItems(item, Guid.Empty, user, sort, startIndex, limit);
- }
-
- if (item is Genre)
- {
- 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(), startIndex, limit);
- }
+ // TODO should this be doing something?
+ return new QueryResult();
}
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)
+ switch (stubType)
{
- return GetMusicLatest(item, user, query);
+ 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.Playlists)
+ var serverItems = new ServerItem[]
{
- return GetMusicPlaylists(user, 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);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Genres)
- {
- return GetMusicGenres(item, user, query);
- }
-
- var list = new List
- {
- 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
- }
+ 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 (limit < serverItems.Length)
+ {
+ serverItems = serverItems[..limit.Value];
+ }
+
return new QueryResult
{
- 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)
+ switch (stubType)
{
- return GetMovieContinueWatching(item, user, query);
+ 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.Latest)
+ var array = new ServerItem[]
{
- return GetMovieLatest(item, user, query);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Movies)
- {
- return GetMovieMovies(item, user, query);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Collections)
- {
- return GetMovieCollections(user, query);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Favorites)
- {
- return GetMovieFavorites(item, user, query);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Genres)
- {
- return GetGenres(item, user, query);
- }
-
- 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
- }
+ 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 (limit < array.Length)
+ {
+ array = array[..limit.Value];
+ }
+
return new QueryResult
{
Items = array,
@@ -900,22 +788,21 @@ namespace Emby.Dlna.ContentDirectory
/// The .
private QueryResult 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
- {
- Items = folders,
- TotalRecordCount = folders.Length
- },
- startIndex,
- limit);
+ return new QueryResult
+ {
+ Items = items,
+ TotalRecordCount = totalRecordCount
+ };
}
///
@@ -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)
+ switch (stubType)
{
- return GetMovieContinueWatching(item, user, query);
+ 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);
- }
-
- if (stubType.HasValue && stubType.Value == StubType.Genres)
- {
- return GetGenres(item, user, query);
- }
-
- var list = new List
- {
- 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
- }
+ 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 (limit < serverItems.Length)
+ {
+ serverItems = serverItems[..limit.Value];
+ }
+
return new QueryResult
{
- 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.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetMovieContinueWatching(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult 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);
- }
-
- ///
- /// Returns the series meeting the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
- ///
- /// Returns the Movie folders meeting the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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
///
/// Returns the Movie collections meeting the criteria.
///
- /// The see cref="User"/>.
/// The see cref="InternalItemsQuery"/>.
/// The .
- private QueryResult GetMovieCollections(User user, InternalItemsQuery query)
+ private QueryResult 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
}
///
- /// Returns the Music albums meeting the criteria.
+ /// Returns the children that meet the criteria.
///
/// The .
- /// The .
/// The .
+ /// The item type.
+ /// A value indicating whether to only fetch favorite items.
/// The .
- private QueryResult GetMusicAlbums(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult GetChildrenOfItem(BaseItem parent, InternalItemsQuery query, string itemType, bool isFavorite = false)
{
query.Recursive = true;
query.Parent = parent;
- query.SetUser(user);
-
- query.IncludeItemTypes = new[] { nameof(MusicAlbum) };
-
- var result = _libraryManager.GetItemsResult(query);
-
- return ToResult(result);
- }
-
- ///
- /// Returns the Music songs meeting the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
- ///
- /// Returns the songs tagged as favourite that meet the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
- ///
- /// Returns the series tagged as favourite that meet the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult GetFavoriteSeries(BaseItem parent, User user, InternalItemsQuery query)
- {
- 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);
- }
-
- ///
- /// Returns the episodes tagged as favourite that meet the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
- ///
- /// Returns the movies tagged as favourite that meet the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
- ///
- /// /// Returns the albums tagged as favourite that meet the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetGenres(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult GetGenres(BaseItem parent, InternalItemsQuery query)
{
- var genresResult = _libraryManager.GetGenres(new InternalItemsQuery(user)
- {
- AncestorIds = new[] { parent.Id },
- StartIndex = query.StartIndex,
- Limit = query.Limit
- });
+ // Don't sort
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
+ query.AncestorIds = new[] { parent.Id };
+ var genresResult = _libraryManager.GetGenres(query);
- var result = new QueryResult
- {
- TotalRecordCount = genresResult.TotalRecordCount,
- Items = genresResult.Items.Select(i => i.Item1).ToArray()
- };
-
- return ToResult(result);
+ return ToResult(genresResult);
}
///
/// Returns the music genres meeting the criteria.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetMusicGenres(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult GetMusicGenres(BaseItem parent, InternalItemsQuery query)
{
- var genresResult = _libraryManager.GetMusicGenres(new InternalItemsQuery(user)
- {
- AncestorIds = new[] { parent.Id },
- StartIndex = query.StartIndex,
- Limit = query.Limit
- });
+ // Don't sort
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
+ query.AncestorIds = new[] { parent.Id };
+ var genresResult = _libraryManager.GetMusicGenres(query);
- var result = new QueryResult
- {
- TotalRecordCount = genresResult.TotalRecordCount,
- Items = genresResult.Items.Select(i => i.Item1).ToArray()
- };
-
- return ToResult(result);
+ return ToResult(genresResult);
}
///
/// Returns the music albums by artist that meet the criteria.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetMusicAlbumArtists(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult GetMusicAlbumArtists(BaseItem parent, InternalItemsQuery query)
{
- var artists = _libraryManager.GetAlbumArtists(new InternalItemsQuery(user)
- {
- AncestorIds = new[] { parent.Id },
- StartIndex = query.StartIndex,
- Limit = query.Limit
- });
+ // Don't sort
+ query.OrderBy = Array.Empty<(string, SortOrder)>();
+ query.AncestorIds = new[] { parent.Id };
+ var artists = _libraryManager.GetAlbumArtists(query);
- var result = new QueryResult
- {
- TotalRecordCount = artists.TotalRecordCount,
- Items = artists.Items.Select(i => i.Item1).ToArray()
- };
-
- return ToResult(result);
+ return ToResult(artists);
}
///
/// Returns the music artists meeting the criteria.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetMusicArtists(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult 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
- {
- 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);
}
///
/// Returns the artists tagged as favourite that meet the criteria.
///
/// The .
- /// The .
/// The .
/// The .
- private QueryResult GetFavoriteArtists(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult 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
- {
- 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);
}
///
/// Returns the music playlists meeting the criteria.
///
- /// The user.
/// The query.
/// The .
- private QueryResult GetMusicPlaylists(User user, InternalItemsQuery query)
+ private QueryResult GetMusicPlaylists(InternalItemsQuery query)
{
query.Parent = null;
query.IncludeItemTypes = new[] { nameof(Playlist) };
- query.SetUser(user);
query.Recursive = true;
var result = _libraryManager.GetItemsResult(query);
@@ -1388,31 +1021,6 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
- ///
- /// Returns the latest music meeting the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult 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);
- }
-
///
/// Returns the next up item meeting the criteria.
///
@@ -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
}
///
- /// Returns the latest tv meeting the criteria.
+ /// Returns the latest items of [itemType] meeting the criteria.
///
/// The .
- /// The .
/// The .
+ /// The item type.
/// The .
- private QueryResult GetTvLatest(BaseItem parent, User user, InternalItemsQuery query)
+ private QueryResult 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(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);
- }
-
- ///
- /// Returns the latest movies meeting the criteria.
- ///
- /// The .
- /// The .
- /// The .
- /// The .
- private QueryResult GetMovieLatest(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(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.
///
/// The .
- /// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
- private QueryResult GetMusicArtistItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
+ private QueryResult 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.
///
/// The .
- /// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
- private QueryResult GetGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
+ private QueryResult 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.
///
/// The .
- /// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
- private QueryResult GetMusicGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
+ private QueryResult 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);
}
///
- /// Converts a array into a .
+ /// Converts into a .
///
/// An array of .
/// A .
- private static QueryResult ToResult(BaseItem[] result)
+ private static QueryResult ToResult(IReadOnlyCollection result)
{
var serverItems = result
- .Select(i => new ServerItem(i))
+ .Select(i => new ServerItem(i, null))
.ToArray();
return new QueryResult
{
- TotalRecordCount = result.Length,
+ TotalRecordCount = result.Count,
Items = serverItems
};
}
@@ -1605,10 +1181,12 @@ namespace Emby.Dlna.ContentDirectory
/// The .
private static QueryResult ToResult(QueryResult 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
{
@@ -1618,35 +1196,34 @@ namespace Emby.Dlna.ContentDirectory
}
///
- /// Sets the sorting method on a query.
+ /// Converts a query result to a .
///
- /// The .
- /// The .
- /// True if pre-sorted.
- private static void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted)
+ /// A .
+ /// The .
+ private static QueryResult 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
{
- query.OrderBy = new[] { (ItemSortBy.SortName, sort.SortOrder) };
- }
+ TotalRecordCount = result.TotalRecordCount,
+ Items = serverItems
+ };
}
///
- /// Apply paging to a query.
+ /// Gets the sorting method on a query.
///
- /// The .
- /// The start index.
- /// The maximum number to return.
- /// A .
- private static QueryResult ApplyPaging(QueryResult result, int? startIndex, int? limit)
+ /// The .
+ /// True if pre-sorted.
+ 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) };
}
///
@@ -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(id.AsSpan(0, dividerIndex), true, out var parsedStubType))
{
- if (id.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))
- {
- stubType = Enum.Parse(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 class.
///
/// The .
- public ServerItem(BaseItem item)
+ /// The stub type.
+ 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;
}
}
///
- /// Gets or sets the underlying base item.
+ /// Gets the underlying base item.
///
- public BaseItem Item { get; set; }
+ public BaseItem Item { get; }
///
- /// Gets or sets the DLNA item type.
+ /// Gets the DLNA item type.
///
- 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());
- }
-
///
/// 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
}
///
- 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 @@
-
+
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("network");
- _disabled = appHost.ListenWithHttps && _netConfig.RequireHttps;
+ var netConfig = config.GetConfiguration("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 _transparentImageTypes
= new HashSet(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
},
//
new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"),
+ //
+ new EpisodeExpression(@"[^\\/]*?()\.?[Ee]([0-9]+)\.([^\\/]*)$"),
new EpisodeExpression("(?[0-9]{4})[\\.-](?[0-9]{2})[\\.-](?[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(@"(.*(\\|\/))*(?.+)\/[Ss](eason)?[\. _\-]*(?[0-9]+)")
+ {
+ IsNamed = true
+ },
+
+ // Series and season only expression
+ // "the show S01", "the show season 1"
+ new EpisodeExpression(@"(.*(\\|\/))*(?.+)[\. _\-]+[sS](eason)?[\. _\-]*(?[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 @@
-
+
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
+{
+ ///
+ /// Holder object for Series information.
+ ///
+ public class SeriesInfo
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Path to the file.
+ public SeriesInfo(string path)
+ {
+ Path = path;
+ }
+
+ ///
+ /// Gets or sets the path.
+ ///
+ /// The path.
+ public string Path { get; set; }
+
+ ///
+ /// Gets or sets the name of the series.
+ ///
+ /// The name of the series.
+ 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
+{
+ ///
+ /// 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.
+ ///
+ public static class SeriesPathParser
+ {
+ ///
+ /// Parses information about series from path.
+ ///
+ /// object containing EpisodeExpressions and MultipleEpisodeExpressions.
+ /// Path.
+ /// Returns object.
+ 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
+{
+ ///
+ /// Holder object for result.
+ ///
+ public class SeriesPathParserResult
+ {
+ ///
+ /// Gets or sets the name of the series.
+ ///
+ /// The name of the series.
+ public string? SeriesName { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether parsing was successful.
+ ///
+ 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
+{
+ ///
+ /// Used to resolve information about series from path.
+ ///
+ public static class SeriesResolver
+ {
+ ///
+ /// 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".
+ ///
+ private static readonly Regex _seriesNameRegex = new Regex(@"((?[^\._]{2,})[\._]*)|([\._](?[^\._]{2,}))");
+
+ ///
+ /// Resolve information about series from path.
+ ///
+ /// object passed to .
+ /// Path to series.
+ /// SeriesInfo.
+ 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
///
/// The disposable parts.
///
- private readonly List _disposableParts = new List();
+ private readonly ConcurrentDictionary _disposableParts = new ();
private readonly IFileSystem _fileSystemManager;
private readonly IConfiguration _startupConfig;
@@ -128,7 +131,6 @@ namespace Emby.Server.Implementations
private List _creatingInstances;
private IMediaEncoder _mediaEncoder;
private ISessionManager _sessionManager;
- private string[] _urlPrefixes;
///
/// Gets or sets all concrete types.
@@ -147,25 +149,20 @@ namespace Emby.Server.Implementations
/// Instance of the interface.
/// Instance of the interface.
/// The interface.
- /// Instance of the interface.
- /// Instance of the interface.
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(), applicationPaths);
Logger = LoggerFactory.CreateLogger();
- 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
///
/// Gets the singleton instance.
///
- public INetworkManager NetManager { get; internal set; }
+ public INetworkManager NetManager { get; private set; }
///
/// Gets a value indicating whether this instance has changes that require the entire application to restart.
@@ -230,24 +227,22 @@ namespace Emby.Server.Implementations
///
protected ILogger Logger { get; }
- protected IServiceCollection ServiceCollection { get; }
-
///
/// Gets the logger factory.
///
protected ILoggerFactory LoggerFactory { get; }
///
- /// Gets or sets the application paths.
+ /// Gets the application paths.
///
/// The application paths.
- protected IServerApplicationPaths ApplicationPaths { get; set; }
+ protected IServerApplicationPaths ApplicationPaths { get; }
///
- /// Gets or sets the configuration manager.
+ /// Gets the configuration manager.
///
/// The configuration manager.
- public ServerConfigurationManager ConfigurationManager { get; set; }
+ public ServerConfigurationManager ConfigurationManager { get; }
///
/// Gets or sets the service provider.
@@ -350,22 +345,6 @@ namespace Emby.Server.Implementations
.Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
}
- ///
- /// Creates an instance of type and resolves all constructor dependencies.
- ///
- /// The type.
- /// System.Object.
- public object CreateInstance(Type type)
- => ActivatorUtilities.CreateInstance(ServiceProvider, type);
-
- ///
- /// Creates an instance of type and resolves all constructor dependencies.
- ///
- /// The type.
- /// T.
- public T CreateInstance()
- => ActivatorUtilities.CreateInstance(ServiceProvider);
-
///
/// Creates the instance safe.
///
@@ -375,7 +354,7 @@ namespace Emby.Server.Implementations
{
_creatingInstances ??= new List();
- 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 GetExportTypes()
{
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;
+ }
+ }
}
///
@@ -434,9 +420,9 @@ namespace Emby.Server.Implementations
if (manageLifetime)
{
- lock (_disposableParts)
+ foreach (var part in parts.OfType())
{
- _disposableParts.AddRange(parts.OfType());
+ _disposableParts.TryAdd(part, byte.MinValue);
}
}
@@ -455,9 +441,9 @@ namespace Emby.Server.Implementations
if (manageLifetime)
{
- lock (_disposableParts)
+ foreach (var part in parts.OfType())
{
- _disposableParts.AddRange(parts.OfType());
+ _disposableParts.TryAdd(part, byte.MinValue);
}
}
@@ -521,7 +507,7 @@ namespace Emby.Server.Implementations
}
///
- 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);
}
///
/// Registers services/resources with the service collection that will be available via DI.
///
- protected virtual void RegisterServices()
+ /// Instance of the interface.
+ protected virtual void RegisterServices(IServiceCollection serviceCollection)
{
- ServiceCollection.AddSingleton(_startupOptions);
+ serviceCollection.AddSingleton(_startupOptions);
- ServiceCollection.AddMemoryCache();
+ serviceCollection.AddMemoryCache();
- ServiceCollection.AddSingleton(ConfigurationManager);
- ServiceCollection.AddSingleton(ConfigurationManager);
- ServiceCollection.AddSingleton(this);
- ServiceCollection.AddSingleton(_pluginManager);
- ServiceCollection.AddSingleton(ApplicationPaths);
+ serviceCollection.AddSingleton(ConfigurationManager);
+ serviceCollection.AddSingleton(ConfigurationManager);
+ serviceCollection.AddSingleton(this);
+ serviceCollection.AddSingleton(_pluginManager);
+ serviceCollection.AddSingleton(ApplicationPaths);
- ServiceCollection.AddSingleton(_fileSystemManager);
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton(_fileSystemManager);
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton(NetManager);
+ serviceCollection.AddSingleton(NetManager);
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton(_xmlSerializer);
+ serviceCollection.AddSingleton(_xmlSerializer);
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton(this);
- ServiceCollection.AddSingleton(ApplicationPaths);
+ serviceCollection.AddSingleton(this);
+ serviceCollection.AddSingleton(ApplicationPaths);
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
// TODO: Refactor to eliminate the circular dependencies here so that Lazy isn't required
- ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
- ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
- ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
- ServiceCollection.AddSingleton();
+ serviceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
+ serviceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
+ serviceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
// TODO: Refactor to eliminate the circular dependency here so that Lazy isn't required
- ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
- ServiceCollection.AddSingleton();
+ serviceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService));
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddScoped();
+ serviceCollection.AddScoped();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddScoped();
- ServiceCollection.AddScoped();
- ServiceCollection.AddScoped();
-
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddScoped();
+ serviceCollection.AddScoped();
+ serviceCollection.AddScoped();
+ serviceCollection.AddScoped();
+ serviceCollection.AddSingleton();
}
///
@@ -795,8 +783,6 @@ namespace Emby.Server.Implementations
_pluginManager.CreatePlugins();
- _urlPrefixes = GetUrlPrefixes().ToArray();
-
Resolve().AddParts(
GetExports(),
GetExports(),
@@ -864,32 +850,12 @@ namespace Emby.Server.Implementations
}
}
- private IEnumerable GetUrlPrefixes()
- {
- var hosts = new[] { "+" };
-
- return hosts.SelectMany(i =>
- {
- var prefixes = new List
- {
- "http://" + i + ":" + HttpPort + "/"
- };
-
- if (Certificate != null)
- {
- prefixes.Add("https://" + i + ":" + HttpsPort + "/");
- }
-
- return prefixes;
- });
- }
-
///
/// Called when [configuration updated].
///
/// The sender.
/// The instance containing the event data.
- 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
}
///
- /// 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.
///
public void NotifyPendingRestart()
{
@@ -1098,11 +1059,6 @@ namespace Emby.Server.Implementations
};
}
- public IEnumerable 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
}
///
- 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);
}
///
- 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);
}
///
- 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);
}
///
- 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);
}
///
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
///
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 _supportedHashMethods = new HashSet()
{
"MD5",
@@ -35,60 +34,81 @@ namespace Emby.Server.Implementations.Cryptography
};
///
- public string DefaultHashMethod => "PBKDF2";
+ public string DefaultHashMethod => "PBKDF2-SHA512";
///
- public IEnumerable GetSupportedHashMethods()
- => _supportedHashMethods;
-
- private byte[] PBKDF2(string method, byte[] bytes, byte[] salt, int iterations)
+ public PasswordHash CreatePasswordHash(ReadOnlySpan 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
+ {
+ { "iterations", DefaultIterations.ToString(CultureInfo.InvariantCulture) }
+ });
}
///
- public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt)
+ public bool Verify(PasswordHash hash, ReadOnlySpan 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));
}
- ///
- public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt)
- => PBKDF2(DefaultHashMethod, bytes, salt, DefaultIterations);
-
///
public byte[] GenerateSalt()
=> GenerateSalt(DefaultSaltLength);
///
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 @@
-
-
-
-
-
-
+
+
+
+
+
+
-
+
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 _logger;
private readonly IServerConfigurationManager _config;
- private readonly IDeviceDiscovery _deviceDiscovery;
private readonly ConcurrentDictionary _createdRules = new ConcurrentDictionary();
@@ -42,17 +41,14 @@ namespace Emby.Server.Implementations.EntryPoints
/// The logger.
/// The application host.
/// The configuration manager.
- /// The device discovery.
public ExternalPortForwarding(
ILogger 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
///
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 _affectedPaths = new List();
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 Completed;
+ public event EventHandler? 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 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 paths)
{
- var itemsToRefresh = paths
+ IEnumerable 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
///
/// The path.
/// BaseItem.
- 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();
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The instance to use.
+ /// The instance to use.
public ManagedFileSystem(
ILogger logger,
IApplicationPaths applicationPaths)
@@ -31,6 +34,7 @@ namespace Emby.Server.Implementations.IO
_tempPath = applicationPaths.TempDirectory;
}
+ ///
public virtual void AddShortcutHandler(IShortcutHandler handler)
{
_shortcutHandlers.Add(handler);
@@ -72,6 +76,7 @@ namespace Emby.Server.Implementations.IO
return handler?.Resolve(filename);
}
+ ///
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));
}
+ ///
public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info)
{
return info.CreationTimeUtc;
}
+ ///
public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
{
return info.LastWriteTimeUtc;
@@ -397,6 +404,7 @@ namespace Emby.Server.Implementations.IO
return GetLastWriteTimeUtc(GetFileSystemInfo(path));
}
+ ///
public virtual void SetHidden(string path, bool isHidden)
{
if (!OperatingSystem.IsWindows())
@@ -421,6 +429,7 @@ namespace Emby.Server.Implementations.IO
}
}
+ ///
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);
}
+ ///
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);
}
+ ///
public virtual string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path))
@@ -530,6 +541,7 @@ namespace Emby.Server.Implementations.IO
return Path.TrimEndingDirectorySeparator(path);
}
+ ///
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);
}
+ ///
public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
{
if (info.IsDirectory)
@@ -558,11 +571,11 @@ namespace Emby.Server.Implementations.IO
return Path.GetFileNameWithoutExtension(info.FullName);
}
+ ///
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;
}
+ ///
public virtual void DeleteFile(string path)
{
SetAttributes(path, false, false);
File.Delete(path);
}
+ ///
public virtual List 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();
}
+ ///
public virtual IEnumerable GetDirectories(string path, bool recursive = false)
{
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive)));
}
+ ///
public virtual IEnumerable GetFiles(string path, bool recursive = false)
{
return GetFiles(path, null, false, recursive);
}
+ ///
public virtual IEnumerable GetFiles(string path, IReadOnlyList? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
var enumerationOptions = GetEnumerationOptions(recursive);
@@ -629,6 +651,7 @@ namespace Emby.Server.Implementations.IO
return ToMetadata(files);
}
+ ///
public virtual IEnumerable GetFileSystemEntries(string path, bool recursive = false)
{
var directoryInfo = new DirectoryInfo(path);
@@ -642,16 +665,19 @@ namespace Emby.Server.Implementations.IO
return infos.Select(GetFileSystemMetadata);
}
+ ///
public virtual IEnumerable GetDirectoryPaths(string path, bool recursive = false)
{
return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive));
}
+ ///
public virtual IEnumerable GetFilePaths(string path, bool recursive = false)
{
return GetFilePaths(path, null, false, recursive);
}
+ ///
public virtual IEnumerable 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;
}
+ ///
public virtual IEnumerable 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
///
public class CoreResolutionIgnoreRule : IResolverIgnoreRule
{
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
private readonly IServerApplicationPaths _serverApplicationPaths;
///
/// Initializes a new instance of the class.
///
- /// The library manager.
+ /// The naming options.
/// The server application paths.
- 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;
///
/// 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;
-
///
/// The _root folder.
///
@@ -116,6 +114,7 @@ namespace Emby.Server.Implementations.Library
/// The item repository.
/// The image processor.
/// The memory cache.
+ /// The naming options.
public LibraryManager(
IServerApplicationHost appHost,
ILogger 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
@@ -2501,16 +2501,6 @@ namespace Emby.Server.Implementations.Library
return RootFolder;
}
- ///
- public bool IsVideoFile(string path)
- {
- return VideoResolver.IsVideoFile(path, GetNamingOptions());
- }
-
- ///
- public bool IsAudioFile(string path)
- => AudioFileParser.IsAudioFile(path, GetNamingOptions());
-
///
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;
}
- ///
- 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
public class AudioResolver : ItemResolver, IMultiItemResolver
{
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
- public AudioResolver(ILibraryManager libraryManager)
+ public AudioResolver(NamingOptions namingOptions)
{
- _libraryManager = libraryManager;
+ _namingOptions = namingOptions;
}
///
@@ -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 files,
- string collectionType,
- IDirectoryService directoryService)
+ string collectionType)
{
if (string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase))
{
- return ResolveMultipleAudio(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(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(ItemResolveArgs args, string path, Folder parent, List 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(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(Folder parent, IEnumerable fileSystemEntries, IDirectoryService directoryService, bool suppportMultiEditions, string collectionType, bool parseName)
- where T : MediaBrowser.Controller.Entities.Audio.Audio, new()
+ private MultiItemResolverResult ResolveMultipleAudio(Folder parent, IEnumerable fileSystemEntries, bool parseName)
{
var files = new List();
var items = new List();
@@ -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 result, FileSystemMetadata file)
+ private static bool ContainsFile(IEnumerable 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
{
private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
///
/// Initializes a new instance of the class.
///
/// The logger.
- /// The file system.
- /// The library manager.
- public MusicAlbumResolver(ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager)
+ /// The naming options.
+ public MusicAlbumResolver(ILogger logger, NamingOptions namingOptions)
{
_logger = logger;
- _fileSystem = fileSystem;
- _libraryManager = libraryManager;
+ _namingOptions = namingOptions;
}
///
@@ -87,7 +85,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
/// true if the provided path points to a music album, false otherwise.
public bool IsMusicAlbum(string path, IDirectoryService directoryService)
{
- return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, _libraryManager);
+ return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService);
}
///
@@ -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 list,
bool allowSubfolders,
- IDirectoryService directoryService,
- ILogger 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
{
private readonly ILogger _logger;
- private readonly IFileSystem _fileSystem;
- private readonly ILibraryManager _libraryManager;
- private readonly IServerConfigurationManager _config;
+ private NamingOptions _namingOptions;
///
/// Initializes a new instance of the class.
///
/// The logger for the created instances.
- /// The file system.
- /// The library manager.
- /// The configuration manager.
+ /// The naming options.
public MusicArtistResolver(
ILogger logger,
- IFileSystem fileSystem,
- ILibraryManager libraryManager,
- IServerConfigurationManager config)
+ NamingOptions namingOptions)
{
_logger = logger;
- _fileSystem = fileSystem;
- _libraryManager = libraryManager;
- _config = config;
+ _namingOptions = namingOptions;
}
///
@@ -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 : MediaBrowser.Controller.Resolvers.ItemResolver
where T : Video, new()
{
- protected BaseVideoResolver(ILibraryManager libraryManager)
+ protected BaseVideoResolver(NamingOptions namingOptions)
{
- LibraryManager = libraryManager;
+ NamingOptions = namingOptions;
}
- protected ILibraryManager LibraryManager { get; }
+ protected NamingOptions NamingOptions { get; }
///
/// Resolves the specified args.
@@ -48,7 +49,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
protected virtual TVideoType ResolveVideo(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 : BaseVideoResolver
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, IMultiItemResolver
{
private readonly IImageProcessor _imageProcessor;
+ private readonly StackResolver _stackResolver;
private string[] _validCollectionTypes = new[]
{
@@ -38,12 +40,13 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
///
/// Initializes a new instance of the class.
///
- /// The library manager.
/// The image processor.
- public MovieResolver(ILibraryManager libraryManager, IImageProcessor imageProcessor)
- : base(libraryManager)
+ /// The naming options.
+ public MovieResolver(IImageProcessor imageProcessor, NamingOptions namingOptions)
+ : base(namingOptions)
{
_imageProcessor = imageProcessor;
+ _stackResolver = new StackResolver(NamingOptions);
}
///
@@ -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
{
private readonly IImageProcessor _imageProcessor;
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
///
/// Initializes a new instance of the class.
///
/// The image processor.
- /// The library manager.
- public PhotoAlbumResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager)
+ /// The naming options.
+ public PhotoAlbumResolver(IImageProcessor imageProcessor, NamingOptions namingOptions)
{
_imageProcessor = imageProcessor;
- _libraryManager = libraryManager;
+ _namingOptions = namingOptions;
}
///
@@ -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
{
private readonly IImageProcessor _imageProcessor;
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
+
private static readonly HashSet _ignoreFiles = new HashSet(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;
}
///
@@ -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
///
/// Initializes a new instance of the class.
///
- /// The library manager.
- public EpisodeResolver(ILibraryManager libraryManager)
- : base(libraryManager)
+ /// The naming options.
+ 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
///
public class SeasonResolver : GenericFolderResolver
{
- private readonly ILibraryManager _libraryManager;
private readonly ILocalizationManager _localization;
private readonly ILogger _logger;
+ private readonly NamingOptions _namingOptions;
///
/// Initializes a new instance of the class.
///
- /// The library manager.
+ /// The naming options.
/// The localization.
/// The logger.
public SeasonResolver(
- ILibraryManager libraryManager,
+ NamingOptions namingOptions,
ILocalizationManager localization,
ILogger 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);
+ _logger.LogDebug(
+ "Found folder underneath series with episode number: {0}. Season {1}. Episode {2}",
+ path,
+ episodeInfo.SeasonNumber.Value,
+ episodeInfo.EpisodeNumber.Value);
- return null;
- }
+ 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
{
private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
+ private readonly NamingOptions _namingOptions;
///
/// Initializes a new instance of the class.
///
/// The logger.
- /// The library manager.
- public SeriesResolver(ILogger logger, ILibraryManager libraryManager)
+ /// The naming options.
+ public SeriesResolver(ILogger logger, NamingOptions namingOptions)
{
_logger = logger;
- _libraryManager = libraryManager;
+ _namingOptions = namingOptions;
}
///
@@ -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 fileSystemChildren,
- ILogger 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
+{
+ ///
+ /// Class CollectionPostScanTask.
+ ///
+ public class CollectionPostScanTask : ILibraryPostScanTask
+ {
+ private readonly ILibraryManager _libraryManager;
+ private readonly ICollectionManager _collectionManager;
+ private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The library manager.
+ /// The collection manager.
+ /// The logger.
+ public CollectionPostScanTask(
+ ILibraryManager libraryManager,
+ ICollectionManager collectionManager,
+ ILogger logger)
+ {
+ _libraryManager = libraryManager;
+ _collectionManager = collectionManager;
+ _logger = logger;
+ }
+
+ ///
+ /// Runs the specified progress.
+ ///
+ /// The progress.
+ /// The cancellation token.
+ /// Task.
+ public async Task Run(IProgress progress, CancellationToken cancellationToken)
+ {
+ var collectionNameMoviesMap = new Dictionary>();
+
+ 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 { 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 GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List 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 _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
- private readonly ICryptoProvider _cryptoProvider;
private readonly ConcurrentDictionary _tokens = new ConcurrentDictionary();
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
@@ -43,12 +42,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings
public SchedulesDirect(
ILogger logger,
- IHttpClientFactory httpClientFactory,
- ICryptoProvider cryptoProvider)
+ IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
- _cryptoProvider = cryptoProvider;
}
///
@@ -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 images, bool returnDefaultImage, double desiredAspect)
+ private static string GetProgramImage(string apiUrl, IEnumerable 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());
+ 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 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
///
public IEnumerable 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
/// System.Int32.
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);
}
///
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
/// System.Int32.
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);
}
///
@@ -35,9 +35,7 @@ namespace Emby.Server.Implementations.Sorting
/// System.String.
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
///
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);
}
///
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
/// System.Int32.
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 @@
///
/// Produces file attribute of "image/*".
///
- 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
///
/// Identifies an action that supports the HTTP GET method.
///
- public class HttpSubscribeAttribute : HttpMethodAttribute
+ public sealed class HttpSubscribeAttribute : HttpMethodAttribute
{
private static readonly IEnumerable _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
///
/// Identifies an action that supports the HTTP GET method.
///
- public class HttpUnsubscribeAttribute : HttpMethodAttribute
+ public sealed class HttpUnsubscribeAttribute : HttpMethodAttribute
{
private static readonly IEnumerable _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.
///
[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 @@
///
/// Produces file attribute of "image/*".
///
- 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 @@
///
/// Produces file attribute of "image/*".
///
- 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 @@
///
/// Produces file attribute of "image/*".
///
- 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 @@
///
/// Produces file attribute of "video/*".
///
- 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
+{
+ ///
+ /// Client log controller.
+ ///
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class ClientLogController : BaseJellyfinApiController
+ {
+ private const int MaxDocumentSize = 1_000_000;
+ private readonly IClientEventLogger _clientEventLogger;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ /// Instance of the interface.
+ public ClientLogController(
+ IClientEventLogger clientEventLogger,
+ IServerConfigurationManager serverConfigurationManager)
+ {
+ _clientEventLogger = clientEventLogger;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ ///
+ /// Upload a document.
+ ///
+ /// Document saved.
+ /// Event logging disabled.
+ /// Upload size too large.
+ /// Create response.
+ [HttpPost("Document")]
+ [ProducesResponseType(typeof(ClientLogDocumentResponseDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)]
+ [AcceptsFile(MediaTypeNames.Text.Plain)]
+ [RequestSizeLimit(MaxDocumentSize)]
+ public async Task> 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, 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 _logger;
@@ -39,19 +36,16 @@ namespace Jellyfin.Api.Controllers
/// Initializes a new instance of the class.
///
/// Instance of the interface.
- /// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
public ItemLookupController(
IProviderManager providerManager,
- IServerConfigurationManager serverConfigurationManager,
IFileSystem fileSystem,
ILibraryManager libraryManager,
ILogger 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 _logger;
+ private readonly ISessionManager _sessionManager;
///
/// Initializes a new instance of the class.
@@ -42,18 +44,21 @@ namespace Jellyfin.Api.Controllers
/// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
+ /// Instance of the interface.
public ItemsController(
IUserManager userManager,
ILibraryManager libraryManager,
ILocalizationManager localization,
IDtoService dtoService,
- ILogger logger)
+ ILogger logger,
+ ISessionManager sessionManager)
{
_userManager = userManager;
_libraryManager = libraryManager;
_localization = localization;
_dtoService = dtoService;
_logger = logger;
+ _sessionManager = sessionManager;
}
///
@@ -763,6 +768,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.
/// Optional. Enable the total record count.
/// Optional. Include image information in output.
+ /// Optional. Whether to exclude the currently active sessions.
/// Items returned.
/// A with the items that are resumable.
[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();
+ 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;
///
/// Initializes a new instance of the class.
@@ -34,17 +33,14 @@ namespace Jellyfin.Api.Controllers
/// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
- /// Instance of the interface.
public PersonsController(
ILibraryManager libraryManager,
IDtoService dtoService,
- IUserManager userManager,
- IUserDataManager userDataManager)
+ IUserManager userManager)
{
_libraryManager = libraryManager;
_dtoService = dtoService;
_userManager = userManager;
- _userDataManager = userDataManager;
}
///
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;
///
@@ -36,16 +35,13 @@ namespace Jellyfin.Api.Controllers
///
/// Instance of the interface.
/// Instance of the interface.
- /// Instance of the interface.
public PluginsController(
IInstallationManager installationManager,
- IPluginManager pluginManager,
- IConfigurationManager config)
+ IPluginManager pluginManager)
{
_installationManager = installationManager;
_pluginManager = pluginManager;
_serializerOptions = JsonDefaults.Options;
- _config = config;
}
///
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;
///
@@ -38,17 +37,14 @@ namespace Jellyfin.Api.Controllers
///
/// Instance of the interface.
/// Instance of the interface.
- /// Instance of the interface.
/// Instance of the interface.
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
/// An with the WakeOnLan infos.
[HttpGet("WakeOnLanInfo")]
[Authorize(Policy = Policies.DefaultAuthorization)]
+ [Obsolete("This endpoint is obsolete.")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> 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;
///
@@ -71,53 +70,58 @@ namespace Jellyfin.Api.Helpers
///
public override void Flush()
{
- _stream.Flush();
+ // Not supported
}
///
public override int Read(byte[] buffer, int offset, int count)
+ => Read(buffer.AsSpan(offset, count));
+
+ ///
+ public override int Read(Span 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;
}
///
public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ => await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
+
+ ///
+ public override async ValueTask ReadAsync(Memory 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 @@
-
-
+
+
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
+{
+ ///
+ /// Client log document response dto.
+ ///
+ public class ClientLogDocumentResponseDto
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The file name.
+ public ClientLogDocumentResponseDto(string fileName)
+ {
+ FileName = fileName;
+ }
+
+ ///
+ /// Gets the resulting filename.
+ ///
+ 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
///
/// Gets or sets bytes downloaded.
///
- public long? BytesDownloaded { get; set; }
+ public long BytesDownloaded { get; set; }
///
/// 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 @@
-
+
@@ -35,7 +35,7 @@
-
+
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(_bindAddresses);
+ return new Collection(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray());
}
///
@@ -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));
}
///
@@ -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();
- // 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 @@
-
-
-
+
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
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
/// The to be used by the .
/// The to be used by the .
/// The to be used by the .
- /// The to be used by the .
- /// The to be used by the .
public CoreAppHost(
IServerApplicationPaths applicationPaths,
ILoggerFactory loggerFactory,
IStartupOptions options,
- IConfiguration startupConfig,
- IFileSystem fileSystem,
- IServiceCollection collection)
+ IConfiguration startupConfig)
: base(
applicationPaths,
loggerFactory,
options,
- startupConfig,
- fileSystem,
- collection)
+ startupConfig)
{
}
///
- 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(
+ serviceCollection.AddDbContextPool(
options => options
.UseLoggerFactory(LoggerFactory)
.UseSqlite($"Filename={Path.Combine(ApplicationPaths.DataPath, "jellyfin.db")}"));
- ServiceCollection.AddEventServices();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddEventServices();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
// TODO search the assemblies instead of adding them manually?
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddSingleton();
+ serviceCollection.AddSingleton();
- ServiceCollection.AddScoped();
+ serviceCollection.AddScoped();
- base.RegisterServices();
+ base.RegisterServices(serviceCollection);
}
///
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>(() =>
+ 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 @@
-
-
-
-
-
-
+
+
+
+
+
+
-
+
-
+
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(), 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
-{
- ///
- /// Class containing extension methods for working with Jellyfin cryptography objects.
- ///
- public static class CryptoExtensions
- {
- ///
- /// Creates a new instance.
- ///
- /// The instance used.
- /// The password that will be hashed.
- /// A instance with the hash method, hash, salt and number of iterations.
- 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
- {
- { "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
///
/// Initializes this instance.
///
- void Init();
-
- ///
- /// Creates the instance.
- ///
- /// The type.
- /// System.Object.
- object CreateInstance(Type type);
+ /// Instance of the interface.
+ 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 @@
-
-
-
+
+
+
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
+{
+ ///
+ public class ClientEventLogger : IClientEventLogger
+ {
+ private readonly IServerApplicationPaths _applicationPaths;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ public ClientEventLogger(IServerApplicationPaths applicationPaths)
+ {
+ _applicationPaths = applicationPaths;
+ }
+
+ ///
+ public async Task 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
+{
+ ///
+ /// The client event logger.
+ ///
+ public interface IClientEventLogger
+ {
+ ///
+ /// Writes a file to the log directory.
+ ///
+ /// The client name writing the document.
+ /// The client version writing the document.
+ /// The file contents to write.
+ /// The created file name.
+ Task 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
///
/// Updates the profile.
///
+ /// The profile id.
/// The profile.
- void UpdateProfile(DeviceProfile profile);
+ void UpdateProfile(string profileId, DeviceProfile profile);
///
/// 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 GetMediaStreams(MediaStreamType type)
- {
- return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
- {
- ItemId = Id,
- Type = type
- });
- }
-
public SongInfo GetLookupInfo()
{
var info = GetItemLookupInfo();
@@ -146,11 +137,7 @@ namespace MediaBrowser.Controller.Entities.Audio
return info;
}
- protected override List> GetAllItemsForMediaSources()
- {
- var list = new List>();
- list.Add(new Tuple(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 = { '?', '/', '&' };
-
///
/// The supported extra folder names and types. See .
///
@@ -335,13 +332,6 @@ namespace MediaBrowser.Controller.Entities
[JsonIgnore]
public string ExternalSeriesId { get; set; }
- ///
- /// Gets or sets the etag.
- ///
- /// The etag.
- [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> GetSortChunks(string s1)
{
var list = new List>();
@@ -987,7 +958,7 @@ namespace MediaBrowser.Controller.Entities
ReadOnlySpan 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);
}
///
@@ -1182,9 +1153,9 @@ namespace MediaBrowser.Controller.Entities
.ToList();
}
- protected virtual List> GetAllItemsForMediaSources()
+ protected virtual IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources()
{
- return new List>();
+ 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);
}
///
@@ -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 { image });
+ RemoveImages(new[] { image });
}
- public void RemoveImages(List deletedImages)
+ public void RemoveImages(IEnumerable 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
}
///
- /// Adds the images.
+ /// Adds the images, updating metadata if they already are part of this item.
///
/// Type of the image.
/// The images.
- /// true if XXXX, false otherwise.
+ /// true if images were added or updated, false otherwise.
/// Cannot call AddImages with chapter images.
public bool AddImages(ImageType imageType, List images)
{
@@ -2512,7 +2484,6 @@ namespace MediaBrowser.Controller.Entities
.ToList();
var newImageList = new List();
- 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(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 GetTrailers()
- {
- if (this is IHasTrailers)
- {
- return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
- }
- else
- {
- return Array.Empty();
- }
- }
-
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
-{
- ///
- /// The item has screenshots.
- ///
- 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 _logger;
private readonly IUserDataManager _userDataManager;
private readonly ITVSeriesManager _tvSeriesManager;
- private readonly IServerConfigurationManager _config;
public UserViewBuilder(
IUserViewManager userViewManager,
ILibraryManager libraryManager,
ILogger logger,
IUserDataManager userDataManager,
- ITVSeriesManager tvSeriesManager,
- IServerConfigurationManager config)
+ ITVSeriesManager tvSeriesManager)
{
_userViewManager = userViewManager;
_libraryManager = libraryManager;
_logger = logger;
_userDataManager = userDataManager;
_tvSeriesManager = tvSeriesManager;
- _config = config;
}
public QueryResult 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> GetAllItemsForMediaSources()
+ protected override IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources()
{
- var list = new List>();
+ var list = new List<(BaseItem, MediaSourceType)>
+ {
+ (this, MediaSourceType.Default)
+ };
- list.Add(new Tuple(this, MediaSourceType.Default));
- list.AddRange(GetLinkedAlternateVersions().Select(i => new Tuple(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(primary, MediaSourceType.Grouping));
- list.AddRange(primary.GetLinkedAlternateVersions().Where(i => !existingIds.Contains(i.Id)).Select(i => new Tuple(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() : video.GetLocalAlternateVersionIds();
+ return i.Item1 is Video video ? video.GetLocalAlternateVersionIds() : Enumerable.Empty();
})
.Select(LibraryManager.GetItemById)
.Where(i => i != null)
.ToList();
- list.AddRange(localAlternates.Select(i => new Tuple(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
@@ -42,11 +42,6 @@ namespace MediaBrowser.Controller
/// The name of the friendly.
string FriendlyName { get; }
- ///
- /// Gets the configured published server url.
- ///
- string PublishedServerUrl { get; }
-
///
/// Gets the system info.
///
@@ -60,32 +55,29 @@ namespace MediaBrowser.Controller
/// Gets a URL specific for the request.
///
/// The instance.
- /// Optional port number.
/// An accessible URL.
- string GetSmartApiUrl(HttpRequest request, int? port = null);
+ string GetSmartApiUrl(HttpRequest request);
///
/// Gets a URL specific for the request.
///
/// The remote of the connection.
- /// Optional port number.
/// An accessible URL.
- string GetSmartApiUrl(IPAddress remoteAddr, int? port = null);
+ string GetSmartApiUrl(IPAddress remoteAddr);
///
/// Gets a URL specific for the request.
///
/// The hostname used in the connection.
- /// Optional port number.
/// An accessible URL.
- string GetSmartApiUrl(string hostname, int? port = null);
+ string GetSmartApiUrl(string hostname);
///
- /// 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.
///
+ /// A value indicating whether to allow HTTPS.
/// The API URL.
- string GetLoopbackHttpApiUrl();
+ string GetApiUrlForLocalAccess(bool allowHttps = true);
///
/// Gets a local (LAN) URL that can be used to access the API.
@@ -103,8 +95,6 @@ namespace MediaBrowser.Controller
/// The API URL.
string GetLocalApiUrl(string hostname, string scheme = null, int? port = null);
- IEnumerable 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
@@ -396,20 +396,6 @@ namespace MediaBrowser.Controller.Library
string viewType,
string sortName);
- ///
- /// Determines whether [is video file] [the specified path].
- ///
- /// The path.
- /// true if [is video file] [the specified path]; otherwise, false.
- bool IsVideoFile(string path);
-
- ///
- /// Determines whether [is audio file] [the specified path].
- ///
- /// The path.
- /// true if [is audio file] [the specified path]; otherwise, false.
- bool IsAudioFile(string path);
-
///
/// Gets the season number from path.
///
@@ -625,11 +611,5 @@ namespace MediaBrowser.Controller.Library
BaseItem GetParentItem(string parentId, Guid? userId);
BaseItem GetParentItem(Guid? parentId, Guid? userId);
-
- ///
- /// Gets or creates a static instance of .
- ///
- /// An instance of the class.
- 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
@@ -30,13 +30,6 @@ namespace MediaBrowser.Controller.Library
/// IEnumerable<MediaStream>.
List GetMediaStreams(Guid itemId);
- ///
- /// Gets the media streams.
- ///
- /// The media source identifier.
- /// IEnumerable<MediaStream>.
- List GetMediaStreams(string mediaSourceId);
-
///
/// Gets the media streams.
///
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; }
///
@@ -236,6 +237,40 @@ namespace MediaBrowser.Controller.Library
return CollectionType;
}
+ ///
+ /// Gets the configured content type for the path.
+ ///
+ ///
+ /// This is subject to future refactoring as it relies on a static property in BaseItem.
+ ///
+ /// The configured content type.
+ public string GetConfiguredContentType()
+ {
+ return BaseItem.LibraryManager.GetConfiguredContentType(Path);
+ }
+
+ ///
+ /// Gets the file system children that do not hit the ignore file check.
+ ///
+ ///
+ /// This is subject to future refactoring as it relies on a static property in BaseItem.
+ ///
+ /// The file system children that are not ignored.
+ public IEnumerable 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;
+ }
+ }
+
///
/// Returns a hash code for this instance.
///
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 @@
-
-
-
-
-
+
+
+
+
+
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
/// Media source information.
/// Media stream information.
/// Index of the stream to extract from.
- /// The extension of the file to write, including the '.'.
+ /// The format of the file to write.
/// CancellationToken to use for operation.
/// Location of video image.
- Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken);
-
- ///
- /// Extracts the video images on interval.
- ///
- /// Input file.
- /// Video container type.
- /// Media stream information.
- /// Media source information.
- /// Video 3D format.
- /// Time interval.
- /// Directory to write images.
- /// Filename prefix to use.
- /// Maximum width of image.
- /// CancellationToken to use for operation.
- /// A task.
- Task ExtractVideoImagesOnInterval(
- string inputFile,
- string container,
- MediaStream videoStream,
- MediaSourceInfo mediaSource,
- Video3DFormat? threedFormat,
- TimeSpan interval,
- string targetDirectory,
- string filenamePrefix,
- int? maxWidth,
- CancellationToken cancellationToken);
+ Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, ImageFormat? targetFormat, CancellationToken cancellationToken);
///
/// 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
@@ -17,11 +17,6 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
///
public class PausedGroupState : AbstractGroupState
{
- ///
- /// The logger.
- ///
- private readonly ILogger _logger;
-
///
/// Initializes a new instance of the class.
///
@@ -29,7 +24,6 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
public PausedGroupState(ILoggerFactory loggerFactory)
: base(loggerFactory)
{
- _logger = LoggerFactory.CreateLogger();
}
///
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
@@ -17,11 +17,6 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
///
public class PlayingGroupState : AbstractGroupState
{
- ///
- /// The logger.
- ///
- private readonly ILogger _logger;
-
///
/// Initializes a new instance of the class.
///
@@ -29,7 +24,6 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
public PlayingGroupState(ILoggerFactory loggerFactory)
: base(loggerFactory)
{
- _logger = LoggerFactory.CreateLogger();
}
///
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
///
public class InternalMetadataFolderImageProvider : ILocalImageProvider, IHasOrder
{
- private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
- /// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
public InternalMetadataFolderImageProvider(
- IServerConfigurationManager config,
IFileSystem fileSystem,
ILogger 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 images, List files, string imagePrefix, bool isInMixedFolder)
@@ -363,11 +358,6 @@ namespace MediaBrowser.LocalMetadata.Images
}));
}
- private void PopulateScreenshots(List images, List files, string imagePrefix, bool isInMixedFolder)
- {
- PopulateBackdrops(images, files, imagePrefix, "screenshot", "screenshot", isInMixedFolder, ImageType.Screenshot);
- }
-
private void PopulateBackdrops(List images, List 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 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 ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, string outputExtension, CancellationToken cancellationToken)
+ public Task 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 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 ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, bool allowTonemap, string outputExtension, CancellationToken cancellationToken)
+ private async Task 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("ffmpeg image extraction failed for {Path}", inputPath);
- _logger.LogError(msg);
-
- 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 @@
-
-
-
+
+
+
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
+{
+ ///
+ /// The client log event.
+ ///
+ public class ClientLogEvent
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The log timestamp.
+ /// The log level.
+ /// The user id.
+ /// The client name.
+ /// The client version.
+ /// The device id.
+ /// The message.
+ 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;
+ }
+
+ ///
+ /// Gets the event timestamp.
+ ///
+ public DateTime Timestamp { get; }
+
+ ///
+ /// Gets the log level.
+ ///
+ public LogLevel Level { get; }
+
+ ///
+ /// Gets the user id.
+ ///
+ public Guid? UserId { get; }
+
+ ///
+ /// Gets the client name.
+ ///
+ public string ClientName { get; }
+
+ ///
+ /// Gets the client version.
+ ///
+ public string ClientVersion { get; }
+
+ ///
+ ///
+ /// Gets the device id.
+ ///
+ public string DeviceId { get; }
+
+ ///
+ /// Gets the log message.
+ ///
+ 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
///
public bool RequireHttps { get; set; } = false;
- public bool EnableNewOmdbSupport { get; set; } = true;
-
///
/// Gets or sets the filter for remote IP connectivity. Used in conjuntion with .
///
@@ -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.
///
public bool RemoveOldPlugins { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether clients should be allowed to upload logs.
+ ///
+ public bool AllowClientLogUpload { get; set; } = true;
}
}
diff --git a/MediaBrowser.Common/Cryptography/Constants.cs b/MediaBrowser.Model/Cryptography/Constants.cs
similarity index 55%
rename from MediaBrowser.Common/Cryptography/Constants.cs
rename to 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
{
///
/// Class containing global constants for Jellyfin Cryptography.
@@ -8,11 +8,16 @@ namespace MediaBrowser.Common.Cryptography
///
/// The default length for new salts.
///
- public const int DefaultSaltLength = 64;
+ public const int DefaultSaltLength = 128 / 8;
+
+ ///
+ /// The default output length.
+ ///
+ public const int DefaultOutputLength = 512 / 8;
///
/// The default amount of iterations for hashing passwords.
///
- 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 GetSupportedHashMethods();
+ ///
+ /// Creates a new instance.
+ ///
+ /// The password that will be hashed.
+ /// A instance with the hash method, hash, salt and number of iterations.
+ PasswordHash CreatePasswordHash(ReadOnlySpan password);
- byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt);
-
- byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt);
+ bool Verify(PasswordHash hash, ReadOnlySpan password);
byte[] GenerateSalt();
diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Model/Cryptography/PasswordHash.cs
similarity index 99%
rename from MediaBrowser.Common/Cryptography/PasswordHash.cs
rename to 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, 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
similarity index 92%
rename from Jellyfin.Api/Models/DisplayPreferencesDtos/DisplayPreferencesDto.cs
rename to 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
{
///
/// 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();
+ CustomPrefs = new Dictionary();
}
///
@@ -63,10 +63,10 @@ namespace Jellyfin.Api.Models.DisplayPreferencesDtos
public int PrimaryImageWidth { get; set; }
///
- /// Gets the custom prefs.
+ /// Gets or sets the custom prefs.
///
/// The custom prefs.
- public Dictionary CustomPrefs { get; }
+ public Dictionary CustomPrefs { get; set; }
///
/// 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
-{
- ///
- /// Defines the display preferences for any item that supports them (usually Folders).
- ///
- public class DisplayPreferencesDto
- {
- ///
- /// Initializes a new instance of the class.
- ///
- public DisplayPreferencesDto()
- {
- RememberIndexing = false;
- PrimaryImageHeight = 250;
- PrimaryImageWidth = 250;
- ShowBackdrop = true;
- CustomPrefs = new Dictionary();
- }
-
- ///
- /// Gets or sets the user id.
- ///
- /// The user id.
- public string Id { get; set; }
-
- ///
- /// Gets or sets the type of the view.
- ///
- /// The type of the view.
- public string ViewType { get; set; }
-
- ///
- /// Gets or sets the sort by.
- ///
- /// The sort by.
- public string SortBy { get; set; }
-
- ///
- /// Gets or sets the index by.
- ///
- /// The index by.
- public string IndexBy { get; set; }
-
- ///
- /// Gets or sets a value indicating whether [remember indexing].
- ///
- /// true if [remember indexing]; otherwise, false.
- public bool RememberIndexing { get; set; }
-
- ///
- /// Gets or sets the height of the primary image.
- ///
- /// The height of the primary image.
- public int PrimaryImageHeight { get; set; }
-
- ///
- /// Gets or sets the width of the primary image.
- ///
- /// The width of the primary image.
- public int PrimaryImageWidth { get; set; }
-
- ///
- /// Gets or sets the custom prefs.
- ///
- /// The custom prefs.
- public Dictionary CustomPrefs { get; set; }
-
- ///
- /// Gets or sets the scroll direction.
- ///
- /// The scroll direction.
- public ScrollDirection ScrollDirection { get; set; }
-
- ///
- /// Gets or sets a value indicating whether to show backdrops on this item.
- ///
- /// true if showing backdrops; otherwise, false.
- public bool ShowBackdrop { get; set; }
-
- ///
- /// Gets or sets a value indicating whether [remember sorting].
- ///
- /// true if [remember sorting]; otherwise, false.
- public bool RememberSorting { get; set; }
-
- ///
- /// Gets or sets the sort order.
- ///
- /// The sort order.
- public SortOrder SortOrder { get; set; }
-
- ///
- /// Gets or sets a value indicating whether [show sidebar].
- ///
- /// true if [show sidebar]; otherwise, false.
- public bool ShowSidebar { get; set; }
-
- ///
- /// Gets or sets the client.
- ///
- 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
{
///
@@ -48,6 +50,10 @@ namespace MediaBrowser.Model.Entities
///
/// The screenshot.
///
+ ///
+ /// This enum value is obsolete.
+ /// XmlSerializer does not serialize/deserialize objects that are marked as [Obsolete].
+ ///
Screenshot = 8,
///
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 @@
-
-
+
+
-
+
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))
{
- 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, "eac3", StringComparison.OrdinalIgnoreCase))
+ {
+ 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
-{
- ///
- /// Enum NetworkShareType.
- ///
- public enum NetworkShareType
- {
- ///
- /// Disk share.
- ///
- Disk,
-
- ///
- /// Printer share.
- ///
- Printer,
-
- ///
- /// Device share.
- ///
- Device,
-
- ///
- /// IPC share.
- ///
- Ipc,
-
- ///
- /// Special share.
- ///
- 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
{
///
@@ -143,6 +145,7 @@ namespace MediaBrowser.Model.Querying
///
/// The screenshot image tags.
///
+ [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
{
+ ///
+ /// Utilities for managing images attached to items.
+ ///
public class ItemImageProvider
{
private readonly ILogger _logger;
@@ -47,6 +48,12 @@ namespace MediaBrowser.Providers.Manager
ImageType.Thumb
};
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The logger.
+ /// The provider manager for interacting with provider image references.
+ /// The filesystem.
public ItemImageProvider(ILogger logger, IProviderManager providerManager, IFileSystem fileSystem)
{
_logger = logger;
@@ -54,6 +61,13 @@ namespace MediaBrowser.Providers.Manager
_fileSystem = fileSystem;
}
+ ///
+ /// Verifies existing images have valid paths and adds any new local images provided.
+ ///
+ /// The to validate images for.
+ /// The providers to use, must include (s) for local scanning.
+ /// The directory service for s to use.
+ /// true if changes were made to the item; otherwise false.
public bool ValidateImages(BaseItem item, IEnumerable providers, IDirectoryService directoryService)
{
var hasChanges = false;
@@ -73,6 +87,15 @@ namespace MediaBrowser.Providers.Manager
return hasChanges;
}
+ ///
+ /// Refreshes from the providers according to the given options.
+ ///
+ /// The to gather images for.
+ /// The library options.
+ /// The providers to query for images.
+ /// The refresh options.
+ /// The cancellation token.
+ /// The refresh result.
public async Task RefreshImages(
BaseItem item,
LibraryOptions libraryOptions,
@@ -80,14 +103,10 @@ namespace MediaBrowser.Providers.Manager
ImageRefreshOptions refreshOptions,
CancellationToken cancellationToken)
{
+ var oldBackdropImages = Array.Empty();
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();
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;
}
///
- /// Refreshes from provider.
+ /// Refreshes from a dynamic provider.
///
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
/// The images.
/// The saved options.
/// The backdrop limit.
- /// The screenshot limit.
/// true if the specified item contains images; otherwise, false.
- private bool ContainsImages(BaseItem item, List images, TypeOptions savedOptions, int backdropLimit, int screenshotLimit)
+ private bool ContainsImages(BaseItem item, List 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;
}
///
- /// Refreshes from provider.
+ /// Refreshes from a remote provider.
///
/// The item.
/// The provider.
/// The refresh options.
/// The saved options.
/// The backdrop limit.
- /// The screenshot limit.
/// The downloaded images.
/// The result.
/// The cancellation token.
@@ -252,7 +270,6 @@ namespace MediaBrowser.Providers.Manager
ImageRefreshOptions refreshOptions,
TypeOptions savedOptions,
int backdropLimit,
- int screenshotLimit,
ICollection 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();
-
- 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);
}
+ ///
+ /// Merges a list of images into the provided item, validating existing images and replacing them or adding new images as necessary.
+ ///
+ /// The to modify.
+ /// The new images to place in item.
+ /// true if changes were made to the item; otherwise false.
public bool MergeImages(BaseItem item, IReadOnlyList 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 images, int minWidth, CancellationToken cancellationToken)
+ private async Task DownloadMultiImages(BaseItem item, ImageType imageType, ImageRefreshOptions refreshOptions, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable 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 @@
-
-
-
+
+
+
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
{
///
- /// Uses ffmpeg to create video images.
+ /// Uses to extract embedded images.
///
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)
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The media source manager for fetching item streams.
+ /// The media encoder for extracting embedded images.
+ /// The server configuration manager for getting image paths.
+ /// The filesystem.
+ 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");
+ ///
public string Name => "Image Extractor";
+ ///
public IEnumerable GetSupportedImages(BaseItem item)
{
- return new List { ImageType.Primary };
+ return new[] { ImageType.Primary };
}
+ ///
public Task 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 GetImage(Audio item, List imageStreams, CancellationToken cancellationToken)
+ private async Task GetImage(Audio item, List 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);
}
+ ///
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 _logger;
///
/// Initializes a new instance of the class.
///
+ /// The media source manager for fetching item streams and attachments.
/// The media encoder for extracting attached/embedded images.
- public EmbeddedImageProvider(IMediaEncoder mediaEncoder)
+ /// The logger.
+ public EmbeddedImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ILogger logger)
{
+ _mediaSourceManager = mediaSourceManager;
_mediaEncoder = mediaEncoder;
+ _logger = logger;
}
///
@@ -114,22 +123,31 @@ namespace MediaBrowser.Providers.MediaInfo
ImageType.Primary => _primaryImageFileNames,
ImageType.Backdrop => _backdropImageFileNames,
ImageType.Logo => _logoImageFileNames,
- _ => _primaryImageFileNames
+ _ => Array.Empty()
};
+ 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 ExtractAttachment(Video item, CancellationToken cancellationToken, MediaAttachment attachmentStream, MediaSourceInfo mediaSource)
+ private async Task 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
{
+ ///
+ /// Resolves external subtitles for videos.
+ ///
public class SubtitleResolver
{
private readonly ILocalizationManager _localization;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The localization manager.
public SubtitleResolver(ILocalizationManager localization)
{
_localization = localization;
}
+ ///
+ /// Retrieves the external subtitle streams for the provided video.
+ ///
+ /// The video to search from.
+ /// The stream index to start adding subtitle streams at.
+ /// The directory service to search for files.
+ /// True if the directory service cache should be cleared before searching.
+ /// The external subtitle streams located.
public List GetExternalSubtitleStreams(
Video video,
int startIndex,
@@ -56,6 +67,13 @@ namespace MediaBrowser.Providers.MediaInfo
return streams;
}
+ ///
+ /// Locates the external subtitle files for the provided video.
+ ///
+ /// The video to search from.
+ /// The directory service to search for files.
+ /// True if the directory service cache should be cleared before searching.
+ /// The external subtitle file paths located.
public IEnumerable GetExternalSubtitleFiles(
Video video,
IDirectoryService directoryService,
@@ -74,6 +92,13 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
+ ///
+ /// Extracts the subtitle files from the provided list and adds them to the list of streams.
+ ///
+ /// The list of streams to add external subtitles to.
+ /// The path to the video file.
+ /// The stream index to start adding subtitle streams at.
+ /// The files to add if they are subtitles.
public void AddExternalSubtitleStreams(
List 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.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
///
public class VideoImageProvider : IDynamicImageProvider, IHasOrder
{
+ private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
+ /// The media source manager for fetching item streams.
/// The media encoder for capturing images.
/// The logger.
- public VideoImageProvider(IMediaEncoder mediaEncoder, ILogger logger)
+ public VideoImageProvider(IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ILogger 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, 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> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
{
- return _itemProvider.GetSearchResults(searchInfo, "episode", cancellationToken);
+ return _itemProvider.GetSearchResults(searchInfo, cancellationToken);
}
public async Task> GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
{
- var result = new MetadataResult()
+ var result = new MetadataResult
{
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> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var imdbId = item.GetProviderId(MetadataProvider.Imdb);
-
- var list = new List();
-
- var provider = new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager);
-
- if (!string.IsNullOrWhiteSpace(imdbId))
+ if (string.IsNullOrWhiteSpace(imdbId))
{
- var rootObject = await provider.GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
-
- if (!string.IsNullOrEmpty(rootObject.Poster))
- {
- 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)
- });
- }
- }
+ return Enumerable.Empty();
}
- return list;
+ var rootObject = await _omdbProvider.GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
+
+ if (string.IsNullOrEmpty(rootObject.Poster))
+ {
+ return Enumerable.Empty();
+ }
+
+ // the poster url is sometimes higher quality than the poster api
+ return new[]
+ {
+ new RemoteImageInfo
+ {
+ ProviderName = Name,
+ Url = rootObject.Poster
+ }
+ };
}
public Task 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> GetSearchResults(TrailerInfo searchInfo, CancellationToken cancellationToken)
+ {
+ return GetSearchResultsInternal(searchInfo, true, cancellationToken);
+ }
+
public Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
{
- return GetSearchResults(searchInfo, "series", cancellationToken);
+ return GetSearchResultsInternal(searchInfo, true, cancellationToken);
}
public Task> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
{
- return GetSearchResults(searchInfo, "movie", cancellationToken);
+ return GetSearchResultsInternal(searchInfo, true, cancellationToken);
}
- public Task> GetSearchResults(ItemLookupInfo searchInfo, string type, CancellationToken cancellationToken)
+ public Task> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
{
- return GetSearchResultsInternal(searchInfo, type, true, cancellationToken);
+ return GetSearchResultsInternal(searchInfo, true, cancellationToken);
}
- private async Task> GetSearchResultsInternal(ItemLookupInfo searchInfo, string type, bool isSearch, CancellationToken cancellationToken)
+ private async Task> 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 (!string.IsNullOrWhiteSpace(name))
- {
- var parsedName = _libraryManager.ParseName(name);
- var yearInName = parsedName.Year;
- name = parsedName.Name;
- year ??= yearInName;
- }
-
- if (string.IsNullOrWhiteSpace(imdbId))
- {
- if (year.HasValue)
- {
- urlQuery += "&y=" + year.Value.ToString(CultureInfo.InvariantCulture);
- }
-
- // &s means search and returns a list of results as opposed to t
- if (isSearch)
- {
- urlQuery += "&s=" + WebUtility.UrlEncode(name);
- }
- else
- {
- urlQuery += "&t=" + WebUtility.UrlEncode(name);
- }
-
- urlQuery += "&type=" + type;
- }
- else
- {
- urlQuery += "&i=" + imdbId;
- isSearch = false;
- }
-
- if (type == "episode")
- {
if (searchInfo.IndexNumber.HasValue)
{
- urlQuery += string.Format(CultureInfo.InvariantCulture, "&Episode={0}", searchInfo.IndexNumber);
+ urlQuery.Append("&Episode=").Append(searchInfo.IndexNumber.Value);
}
if (searchInfo.ParentIndexNumber.HasValue)
{
- urlQuery += string.Format(CultureInfo.InvariantCulture, "&Season={0}", searchInfo.ParentIndexNumber);
+ urlQuery.Append("&Season=").Append(searchInfo.ParentIndexNumber.Value);
}
}
- var url = OmdbProvider.GetOmdbUrl(urlQuery);
+ if (string.IsNullOrWhiteSpace(imdbId))
+ {
+ var name = searchInfo.Name;
+ var year = searchInfo.Year;
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ var parsedName = _libraryManager.ParseName(name);
+ var yearInName = parsedName.Year;
+ name = parsedName.Name;
+ year ??= yearInName;
+ }
- using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
+ if (year.HasValue)
+ {
+ urlQuery.Append("&y=").Append(year);
+ }
+
+ // &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.Append("&i=")
+ .Append(imdbId);
+ isSearch = false;
+ }
+
+ var url = OmdbProvider.GetOmdbUrl(urlQuery.ToString());
+
+ 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();
if (isSearch)
{
var searchResultList = await JsonSerializer.DeserializeAsync(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