Merge remote-tracking branch 'upstream/master' into hwaccel

This commit is contained in:
Vasily 2020-06-08 14:44:21 +03:00
commit 4999831604
453 changed files with 4808 additions and 2109 deletions

View File

@ -1,6 +1,6 @@
parameters:
LinuxImage: "ubuntu-latest"
RestoreBuildProjects: "Jellyfin.Server/Jellyfin.Server.csproj"
LinuxImage: 'ubuntu-latest'
RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj'
DotNetSdkVersion: 3.1.100
jobs:
@ -13,7 +13,7 @@ jobs:
Debug:
BuildConfiguration: Debug
pool:
vmImage: "${{ parameters.LinuxImage }}"
vmImage: '${{ parameters.LinuxImage }}'
steps:
- checkout: self
clean: true
@ -21,7 +21,7 @@ jobs:
persistCredentials: true
- task: DownloadPipelineArtifact@2
displayName: "Download Web Branch"
displayName: 'Download Web Branch'
condition: in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')
inputs:
path: '$(Agent.TempDirectory)'
@ -32,7 +32,7 @@ jobs:
runBranch: variables['Build.SourceBranch']
- task: DownloadPipelineArtifact@2
displayName: "Download Web Target"
displayName: 'Download Web Target'
condition: eq(variables['Build.Reason'], 'PullRequest')
inputs:
path: '$(Agent.TempDirectory)'
@ -43,51 +43,51 @@ jobs:
runBranch: variables['System.PullRequest.TargetBranch']
- task: ExtractFiles@1
displayName: "Extract Web Client"
displayName: 'Extract Web Client'
inputs:
archiveFilePatterns: '$(Agent.TempDirectory)/*.zip'
destinationFolder: '$(Build.SourcesDirectory)/MediaBrowser.WebDashboard'
cleanDestinationFolder: false
- task: UseDotNet@2
displayName: "Update DotNet"
displayName: 'Update DotNet'
inputs:
packageType: sdk
version: ${{ parameters.DotNetSdkVersion }}
- task: DotNetCoreCLI@2
displayName: "Publish Server"
displayName: 'Publish Server'
inputs:
command: publish
publishWebProjects: false
projects: "${{ parameters.RestoreBuildProjects }}"
arguments: "--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)"
projects: '${{ parameters.RestoreBuildProjects }}'
arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'
zipAfterPublish: false
- task: PublishPipelineArtifact@0
displayName: "Publish Artifact Naming"
displayName: 'Publish Artifact Naming'
condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
inputs:
targetPath: "$(build.ArtifactStagingDirectory)/Jellyfin.Server/Emby.Naming.dll"
artifactName: "Jellyfin.Naming"
targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/Emby.Naming.dll'
artifactName: 'Jellyfin.Naming'
- task: PublishPipelineArtifact@0
displayName: "Publish Artifact Controller"
displayName: 'Publish Artifact Controller'
condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
inputs:
targetPath: "$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Controller.dll"
artifactName: "Jellyfin.Controller"
targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Controller.dll'
artifactName: 'Jellyfin.Controller'
- task: PublishPipelineArtifact@0
displayName: "Publish Artifact Model"
displayName: 'Publish Artifact Model'
condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
inputs:
targetPath: "$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Model.dll"
artifactName: "Jellyfin.Model"
targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Model.dll'
artifactName: 'Jellyfin.Model'
- task: PublishPipelineArtifact@0
displayName: "Publish Artifact Common"
displayName: 'Publish Artifact Common'
condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
inputs:
targetPath: "$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Common.dll"
artifactName: "Jellyfin.Common"
targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Common.dll'
artifactName: 'Jellyfin.Common'

View File

@ -45,6 +45,7 @@ jobs:
- task: SonarCloudPrepare@1
displayName: 'Prepare analysis on SonarCloud'
condition: eq(variables['ImageName'], 'ubuntu-latest')
enabled: false
inputs:
SonarCloud: 'Sonarcloud for Jellyfin'
organization: 'jellyfin'
@ -63,14 +64,17 @@ jobs:
- task: SonarCloudAnalyze@1
displayName: 'Run Code Analysis'
condition: eq(variables['ImageName'], 'ubuntu-latest')
enabled: false
- task: SonarCloudPublish@1
displayName: 'Publish Quality Gate Result'
condition: eq(variables['ImageName'], 'ubuntu-latest')
enabled: false
- task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4
condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
displayName: 'Run ReportGenerator'
enabled: false
inputs:
reports: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
targetdir: "$(Agent.TempDirectory)/merged/"
@ -80,10 +84,10 @@ jobs:
- task: PublishCodeCoverageResults@1
condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
displayName: 'Publish Code Coverage'
enabled: false
inputs:
codeCoverageTool: "cobertura"
#summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2
summaryFileLocation: "$(Agent.TempDirectory)/merged/**.xml"
pathToSources: $(Build.SourcesDirectory)
failIfCoverageEmpty: true

View File

@ -2,9 +2,9 @@ name: $(Date:yyyyMMdd)$(Rev:.r)
variables:
- name: TestProjects
value: "tests/**/*Tests.csproj"
value: 'tests/**/*Tests.csproj'
- name: RestoreBuildProjects
value: "Jellyfin.Server/Jellyfin.Server.csproj"
value: 'Jellyfin.Server/Jellyfin.Server.csproj'
- name: DotNetSdkVersion
value: 3.1.100
@ -17,17 +17,17 @@ trigger:
jobs:
- template: azure-pipelines-main.yml
parameters:
LinuxImage: "ubuntu-latest"
LinuxImage: 'ubuntu-latest'
RestoreBuildProjects: $(RestoreBuildProjects)
- template: azure-pipelines-test.yml
parameters:
ImageNames:
Linux: "ubuntu-latest"
Windows: "windows-latest"
macOS: "macos-latest"
Linux: 'ubuntu-latest'
Windows: 'windows-latest'
macOS: 'macos-latest'
- template: azure-pipelines-compat.yml
- template: azure-pipelines-abi.yml
parameters:
Packages:
Naming:
@ -42,4 +42,4 @@ jobs:
Common:
NugetPackageName: Jellyfin.Common
AssemblyFileName: MediaBrowser.Common.dll
LinuxImage: "ubuntu-latest"
LinuxImage: 'ubuntu-latest'

12
.vscode/tasks.json vendored
View File

@ -10,6 +10,16 @@
"${workspaceFolder}/Jellyfin.Server/Jellyfin.Server.csproj"
],
"problemMatcher": "$msCompile"
},
{
"label": "api tests",
"command": "dotnet",
"type": "process",
"args": [
"test",
"${workspaceFolder}/tests/MediaBrowser.Api.Tests/MediaBrowser.Api.Tests.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
}

View File

@ -6,7 +6,7 @@ namespace DvdLib.Ifo
{
public class Program
{
public readonly List<Cell> Cells;
public IReadOnlyList<Cell> Cells { get; }
public Program(List<Cell> cells)
{

View File

@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
using System.Linq;
using System.Threading.Tasks;
using Emby.Dlna.Service;
using MediaBrowser.Common.Net;
@ -136,12 +137,7 @@ namespace Emby.Dlna.ContentDirectory
}
}
foreach (var user in _userManager.Users)
{
return user;
}
return null;
return _userManager.Users.FirstOrDefault();
}
}
}

View File

@ -133,20 +133,20 @@ namespace Emby.Dlna.Main
{
await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false);
ReloadComponents();
await ReloadComponents().ConfigureAwait(false);
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
_config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
}
void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
{
ReloadComponents();
await ReloadComponents().ConfigureAwait(false);
}
}
private async void ReloadComponents()
private async Task ReloadComponents()
{
var options = _config.GetDlnaConfiguration();

View File

@ -34,7 +34,7 @@ namespace Emby.Dlna.PlayTo
{
get
{
RefreshVolumeIfNeeded();
RefreshVolumeIfNeeded().GetAwaiter().GetResult();
return _volume;
}
set => _volume = value;
@ -76,24 +76,24 @@ namespace Emby.Dlna.PlayTo
private DateTime _lastVolumeRefresh;
private bool _volumeRefreshActive;
private void RefreshVolumeIfNeeded()
private Task RefreshVolumeIfNeeded()
{
if (!_volumeRefreshActive)
{
return;
}
if (DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
if (_volumeRefreshActive
&& DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
{
_lastVolumeRefresh = DateTime.UtcNow;
RefreshVolume(CancellationToken.None);
return RefreshVolume();
}
return Task.CompletedTask;
}
private async void RefreshVolume(CancellationToken cancellationToken)
private async Task RefreshVolume(CancellationToken cancellationToken = default)
{
if (_disposed)
{
return;
}
try
{

View File

@ -146,11 +146,14 @@ namespace Emby.Dlna.PlayTo
{
var positionTicks = GetProgressPositionTicks(streamInfo);
ReportPlaybackStopped(streamInfo, positionTicks);
await ReportPlaybackStopped(streamInfo, positionTicks).ConfigureAwait(false);
}
streamInfo = StreamParams.ParseFromUrl(e.NewMediaInfo.Url, _libraryManager, _mediaSourceManager);
if (streamInfo.Item == null) return;
if (streamInfo.Item == null)
{
return;
}
var newItemProgress = GetProgressInfo(streamInfo);
@ -173,11 +176,14 @@ namespace Emby.Dlna.PlayTo
{
var streamInfo = StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager);
if (streamInfo.Item == null) return;
if (streamInfo.Item == null)
{
return;
}
var positionTicks = GetProgressPositionTicks(streamInfo);
ReportPlaybackStopped(streamInfo, positionTicks);
await ReportPlaybackStopped(streamInfo, positionTicks).ConfigureAwait(false);
var mediaSource = await streamInfo.GetMediaSource(CancellationToken.None).ConfigureAwait(false);
@ -185,7 +191,7 @@ namespace Emby.Dlna.PlayTo
(_device.Duration == null ? (long?)null : _device.Duration.Value.Ticks) :
mediaSource.RunTimeTicks;
var playedToCompletion = (positionTicks.HasValue && positionTicks.Value == 0);
var playedToCompletion = positionTicks.HasValue && positionTicks.Value == 0;
if (!playedToCompletion && duration.HasValue && positionTicks.HasValue)
{
@ -210,7 +216,7 @@ namespace Emby.Dlna.PlayTo
}
}
private async void ReportPlaybackStopped(StreamParams streamInfo, long? positionTicks)
private async Task ReportPlaybackStopped(StreamParams streamInfo, long? positionTicks)
{
try
{
@ -220,7 +226,6 @@ namespace Emby.Dlna.PlayTo
SessionId = _session.Id,
PositionTicks = positionTicks,
MediaSourceId = streamInfo.MediaSourceId
}).ConfigureAwait(false);
}
catch (Exception ex)

View File

@ -100,15 +100,13 @@ namespace Emby.Dlna.Ssdp
var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
var args = new GenericEventArgs<UpnpDeviceInfo>
{
Argument = new UpnpDeviceInfo
var args = new GenericEventArgs<UpnpDeviceInfo>(
new UpnpDeviceInfo
{
Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers,
LocalIpAddress = e.LocalIpAddress
}
};
});
DeviceDiscoveredInternal?.Invoke(this, args);
}
@ -121,14 +119,12 @@ namespace Emby.Dlna.Ssdp
var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
var args = new GenericEventArgs<UpnpDeviceInfo>
{
Argument = new UpnpDeviceInfo
var args = new GenericEventArgs<UpnpDeviceInfo>(
new UpnpDeviceInfo
{
Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers
}
};
});
DeviceLeft?.Invoke(this, args);
}

View File

@ -1,5 +1,6 @@
#pragma warning disable CS1591
using System.Linq;
using System.Xml.Linq;
namespace Emby.Dlna.Ssdp
@ -10,24 +11,17 @@ namespace Emby.Dlna.Ssdp
{
var node = container.Element(name);
return node == null ? null : node.Value;
return node?.Value;
}
public static string GetAttributeValue(this XElement container, XName name)
{
var node = container.Attribute(name);
return node == null ? null : node.Value;
return node?.Value;
}
public static string GetDescendantValue(this XElement container, XName name)
{
foreach (var node in container.Descendants(name))
{
return node.Value;
}
return null;
}
=> container.Descendants(name).FirstOrDefault()?.Value;
}
}

View File

@ -114,7 +114,7 @@ namespace Emby.Drawing
=> _transparentImageTypes.Contains(Path.GetExtension(path));
/// <inheritdoc />
public async Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
public async Task<(string path, string? mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
{
ItemImageInfo originalImage = options.Image;
BaseItem item = options.Item;
@ -230,7 +230,7 @@ namespace Emby.Drawing
return ImageFormat.Jpg;
}
private string GetMimeType(ImageFormat format, string path)
private string? GetMimeType(ImageFormat format, string path)
=> format switch
{
ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"),
@ -313,6 +313,27 @@ namespace Emby.Drawing
public ImageDimensions GetImageDimensions(string path)
=> _imageEncoder.GetImageSize(path);
/// <inheritdoc />
public string GetImageBlurHash(string path)
{
var size = GetImageDimensions(path);
if (size.Width <= 0 || size.Height <= 0)
{
return string.Empty;
}
// We want tiles to be as close to square as possible, and to *mostly* keep under 16 tiles for performance.
// One tile is (width / xComp) x (height / yComp) pixels, which means that ideally yComp = xComp * height / width.
// See more at https://github.com/woltapp/blurhash/#how-do-i-pick-the-number-of-x-and-y-components
float xCompF = MathF.Sqrt(16.0f * size.Width / size.Height);
float yCompF = xCompF * size.Height / size.Width;
int xComp = Math.Min((int)xCompF + 1, 9);
int yComp = Math.Min((int)yCompF + 1, 9);
return _imageEncoder.GetImageBlurHash(xComp, yComp, path);
}
/// <inheritdoc />
public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
=> (item.Path + image.DateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture);

View File

@ -42,5 +42,11 @@ namespace Emby.Drawing
{
throw new NotImplementedException();
}
/// <inheritdoc />
public string GetImageBlurHash(int xComp, int yComp, string path)
{
throw new NotImplementedException();
}
}
}

View File

@ -142,7 +142,7 @@ namespace Emby.Naming.Common
CleanStrings = new[]
{
@"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
@"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
@"(\[.*\])"
};

View File

@ -377,50 +377,50 @@ namespace Emby.Server.Implementations.Activity
}).ConfigureAwait(false);
}
private async void OnPluginUpdated(object sender, GenericEventArgs<(IPlugin, VersionInfo)> e)
private async void OnPluginUpdated(object sender, InstallationInfo e)
{
await CreateLogEntry(new ActivityLog(
string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("PluginUpdatedWithName"),
e.Argument.Item1.Name),
e.Name),
NotificationType.PluginUpdateInstalled.ToString(),
Guid.Empty)
{
ShortOverview = string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("VersionNumber"),
e.Argument.Item2.version),
Overview = e.Argument.Item2.changelog
e.Version),
Overview = e.Changelog
}).ConfigureAwait(false);
}
private async void OnPluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
private async void OnPluginUninstalled(object sender, IPlugin e)
{
await CreateLogEntry(new ActivityLog(
string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("PluginUninstalledWithName"),
e.Argument.Name),
e.Name),
NotificationType.PluginUninstalled.ToString(),
Guid.Empty))
.ConfigureAwait(false);
}
private async void OnPluginInstalled(object sender, GenericEventArgs<VersionInfo> e)
private async void OnPluginInstalled(object sender, InstallationInfo e)
{
await CreateLogEntry(new ActivityLog(
string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("PluginInstalledWithName"),
e.Argument.name),
e.Name),
NotificationType.PluginInstalled.ToString(),
Guid.Empty)
{
ShortOverview = string.Format(
CultureInfo.InvariantCulture,
_localization.GetLocalizedString("VersionNumber"),
e.Argument.version)
e.Version)
}).ConfigureAwait(false);
}

View File

@ -45,6 +45,7 @@ using Emby.Server.Implementations.Services;
using Emby.Server.Implementations.Session;
using Emby.Server.Implementations.TV;
using Emby.Server.Implementations.Updates;
using Emby.Server.Implementations.SyncPlay;
using MediaBrowser.Api;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
@ -78,6 +79,7 @@ using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Controller.TV;
using MediaBrowser.Controller.SyncPlay;
using MediaBrowser.LocalMetadata.Savers;
using MediaBrowser.MediaEncoding.BdInfo;
using MediaBrowser.Model.Configuration;
@ -613,6 +615,8 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
serviceCollection.AddSingleton<LiveTvDtoService>();
serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();

View File

@ -46,14 +46,14 @@ namespace Emby.Server.Implementations.Channels
new ConcurrentDictionary<string, Tuple<DateTime, List<MediaSourceInfo>>>();
private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
/// <summary>
/// Initializes a new instance of the <see cref="ChannelManager"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="dtoService">The dto service.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="logger">The logger.</param>
/// <param name="config">The server configuration manager.</param>
/// <param name="fileSystem">The filesystem.</param>
/// <param name="userDataManager">The user data manager.</param>

View File

@ -90,7 +90,7 @@ namespace Emby.Server.Implementations.Configuration
ValidateMetadataPath(newConfig);
ValidateSslCertificate(newConfig);
ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig });
ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration>(newConfig));
base.ReplaceConfiguration(newConfiguration);
}

View File

@ -1,3 +1,5 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
@ -129,8 +131,6 @@ namespace Emby.Server.Implementations.Cryptography
_randomNumberGenerator.Dispose();
}
_randomNumberGenerator = null;
_disposed = true;
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;
@ -33,7 +35,7 @@ using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
/// <summary>
/// Class SQLiteItemRepository
/// Class SQLiteItemRepository.
/// </summary>
public class SqliteItemRepository : BaseSqliteRepository, IItemRepository
{
@ -1141,24 +1143,24 @@ namespace Emby.Server.Implementations.Data
public string ToValueString(ItemImageInfo image)
{
var delimeter = "*";
const string Delimeter = "*";
var path = image.Path;
if (path == null)
{
path = string.Empty;
}
var path = image.Path ?? string.Empty;
var hash = image.BlurHash ?? string.Empty;
return GetPathToSave(path) +
delimeter +
Delimeter +
image.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) +
delimeter +
Delimeter +
image.Type +
delimeter +
Delimeter +
image.Width.ToString(CultureInfo.InvariantCulture) +
delimeter +
image.Height.ToString(CultureInfo.InvariantCulture);
Delimeter +
image.Height.ToString(CultureInfo.InvariantCulture) +
Delimeter +
// Replace delimiters with other characters.
// This can be removed when we migrate to a proper DB.
hash.Replace('*', '/').Replace('|', '\\');
}
public ItemImageInfo ItemImageInfoFromValueString(string value)
@ -1192,6 +1194,11 @@ namespace Emby.Server.Implementations.Data
image.Width = width;
image.Height = height;
}
if (parts.Length >= 6)
{
image.BlurHash = parts[5].Replace('/', '*').Replace('\\', '|');
}
}
return image;
@ -1971,6 +1978,7 @@ namespace Emby.Server.Implementations.Data
/// Gets the chapter.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="item">The item.</param>
/// <returns>ChapterInfo.</returns>
private ChapterInfo GetChapter(IReadOnlyList<IResultSetValue> reader, BaseItem item)
{

View File

@ -62,13 +62,7 @@ namespace Emby.Server.Implementations.Devices
{
_authRepo.UpdateDeviceOptions(deviceId, options);
if (DeviceOptionsUpdated != null)
{
DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
{
Argument = new Tuple<string, DeviceOptions>(deviceId, options)
});
}
DeviceOptionsUpdated?.Invoke(this, new GenericEventArgs<Tuple<string, DeviceOptions>>(new Tuple<string, DeviceOptions>(deviceId, options)));
}
public DeviceOptions GetDeviceOptions(string deviceId)

View File

@ -605,7 +605,7 @@ namespace Emby.Server.Implementations.Dto
if (dictionary.TryGetValue(person.Name, out Person entity))
{
baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary);
baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture);
list.Add(baseItemPerson);
}
@ -654,6 +654,70 @@ namespace Emby.Server.Implementations.Dto
return _libraryManager.GetGenreId(name);
}
private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ImageType imageType, int imageIndex = 0)
{
var image = item.GetImageInfo(imageType, imageIndex);
if (image != null)
{
return GetTagAndFillBlurhash(dto, item, image);
}
return null;
}
private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ItemImageInfo image)
{
var tag = GetImageCacheTag(item, image);
if (!string.IsNullOrEmpty(image.BlurHash))
{
if (dto.ImageBlurHashes == null)
{
dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
}
if (!dto.ImageBlurHashes.ContainsKey(image.Type))
{
dto.ImageBlurHashes[image.Type] = new Dictionary<string, string>();
}
dto.ImageBlurHashes[image.Type][tag] = image.BlurHash;
}
return tag;
}
private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, int limit)
{
return GetTagsAndFillBlurhashes(dto, item, imageType, item.GetImages(imageType).Take(limit).ToList());
}
private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, List<ItemImageInfo> images)
{
var tags = GetImageTags(item, images);
var hashes = new Dictionary<string, string>();
for (int i = 0; i < images.Count; i++)
{
var img = images[i];
if (!string.IsNullOrEmpty(img.BlurHash))
{
var tag = tags[i];
hashes[tag] = img.BlurHash;
}
}
if (hashes.Count > 0)
{
if (dto.ImageBlurHashes == null)
{
dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
}
dto.ImageBlurHashes[imageType] = hashes;
}
return tags;
}
/// <summary>
/// Sets simple property values on a DTOBaseItem
/// </summary>
@ -674,8 +738,8 @@ namespace Emby.Server.Implementations.Dto
dto.LockData = item.IsLocked;
dto.ForcedSortName = item.ForcedSortName;
}
dto.Container = item.Container;
dto.Container = item.Container;
dto.EndDate = item.EndDate;
if (options.ContainsField(ItemFields.ExternalUrls))
@ -694,10 +758,12 @@ namespace Emby.Server.Implementations.Dto
dto.AspectRatio = hasAspectRatio.AspectRatio;
}
dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
if (backdropLimit > 0)
{
dto.BackdropImageTags = GetImageTags(item, item.GetImages(ImageType.Backdrop).Take(backdropLimit).ToList());
dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
}
if (options.ContainsField(ItemFields.ScreenshotImageTags))
@ -705,7 +771,7 @@ namespace Emby.Server.Implementations.Dto
var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
if (screenshotLimit > 0)
{
dto.ScreenshotImageTags = GetImageTags(item, item.GetImages(ImageType.Screenshot).Take(screenshotLimit).ToList());
dto.ScreenshotImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Screenshot, screenshotLimit);
}
}
@ -721,12 +787,11 @@ namespace Emby.Server.Implementations.Dto
// Prevent implicitly captured closure
var currentItem = item;
foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
.ToList())
foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
{
if (options.GetImageLimit(image.Type) > 0)
{
var tag = GetImageCacheTag(item, image);
var tag = GetTagAndFillBlurhash(dto, item, image);
if (tag != null)
{
@ -871,8 +936,7 @@ namespace Emby.Server.Implementations.Dto
if (albumParent != null)
{
dto.AlbumId = albumParent.Id;
dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
dto.AlbumPrimaryImageTag = GetTagAndFillBlurhash(dto, albumParent, ImageType.Primary);
}
//if (options.ContainsField(ItemFields.MediaSourceCount))
@ -1099,7 +1163,7 @@ namespace Emby.Server.Implementations.Dto
episodeSeries = episodeSeries ?? episode.Series;
if (episodeSeries != null)
{
dto.SeriesPrimaryImageTag = GetImageCacheTag(episodeSeries, ImageType.Primary);
dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary);
}
}
@ -1145,7 +1209,7 @@ namespace Emby.Server.Implementations.Dto
series = series ?? season.Series;
if (series != null)
{
dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
}
}
}
@ -1275,7 +1339,7 @@ namespace Emby.Server.Implementations.Dto
if (image != null)
{
dto.ParentLogoItemId = GetDtoId(parent);
dto.ParentLogoImageTag = GetImageCacheTag(parent, image);
dto.ParentLogoImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
@ -1285,7 +1349,7 @@ namespace Emby.Server.Implementations.Dto
if (image != null)
{
dto.ParentArtItemId = GetDtoId(parent);
dto.ParentArtImageTag = GetImageCacheTag(parent, image);
dto.ParentArtImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
@ -1295,7 +1359,7 @@ namespace Emby.Server.Implementations.Dto
if (image != null)
{
dto.ParentThumbItemId = GetDtoId(parent);
dto.ParentThumbImageTag = GetImageCacheTag(parent, image);
dto.ParentThumbImageTag = GetTagAndFillBlurhash(dto, parent, image);
}
}
if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
@ -1305,7 +1369,7 @@ namespace Emby.Server.Implementations.Dto
if (images.Count > 0)
{
dto.ParentBackdropItemId = GetDtoId(parent);
dto.ParentBackdropImageTags = GetImageTags(parent, images);
dto.ParentBackdropImageTags = GetTagsAndFillBlurhashes(dto, parent, ImageType.Backdrop, images);
}
}

View File

@ -54,6 +54,7 @@
<TargetFramework>netstandard2.1</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release'" >true</TreatWarningsAsErrors>
</PropertyGroup>
<!-- Code Analyzers-->

View File

@ -302,7 +302,7 @@ namespace Emby.Server.Implementations.EntryPoints
.Select(x => x.First())
.ToList();
SendChangeNotifications(_itemsAdded.ToList(), itemsUpdated, _itemsRemoved.ToList(), foldersAddedTo, foldersRemovedFrom, CancellationToken.None);
SendChangeNotifications(_itemsAdded.ToList(), itemsUpdated, _itemsRemoved.ToList(), foldersAddedTo, foldersRemovedFrom, CancellationToken.None).GetAwaiter().GetResult();
if (LibraryUpdateTimer != null)
{
@ -327,7 +327,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// <param name="foldersAddedTo">The folders added to.</param>
/// <param name="foldersRemovedFrom">The folders removed from.</param>
/// <param name="cancellationToken">The cancellation token.</param>
private async void SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, CancellationToken cancellationToken)
private async Task SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, CancellationToken cancellationToken)
{
var userIds = _sessionManager.Sessions
.Select(i => i.UserId)

View File

@ -42,27 +42,27 @@ namespace Emby.Server.Implementations.EntryPoints
return Task.CompletedTask;
}
private void OnLiveTvManagerSeriesTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
private async void OnLiveTvManagerSeriesTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
{
SendMessage("SeriesTimerCreated", e.Argument);
await SendMessage("SeriesTimerCreated", e.Argument).ConfigureAwait(false);
}
private void OnLiveTvManagerTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
private async void OnLiveTvManagerTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
{
SendMessage("TimerCreated", e.Argument);
await SendMessage("TimerCreated", e.Argument).ConfigureAwait(false);
}
private void OnLiveTvManagerSeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
private async void OnLiveTvManagerSeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
{
SendMessage("SeriesTimerCancelled", e.Argument);
await SendMessage("SeriesTimerCancelled", e.Argument).ConfigureAwait(false);
}
private void OnLiveTvManagerTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
private async void OnLiveTvManagerTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs<TimerEventInfo> e)
{
SendMessage("TimerCancelled", e.Argument);
await SendMessage("TimerCancelled", e.Argument).ConfigureAwait(false);
}
private async void SendMessage(string name, TimerEventInfo info)
private async Task SendMessage(string name, TimerEventInfo info)
{
var users = _userManager.Users.Where(i => i.Policy.EnableLiveTvAccess).Select(i => i.Id).ToList();

View File

@ -12,6 +12,7 @@ using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Updates;
namespace Emby.Server.Implementations.EntryPoints
{
@ -85,29 +86,29 @@ namespace Emby.Server.Implementations.EntryPoints
return Task.CompletedTask;
}
private void OnPackageInstalling(object sender, InstallationEventArgs e)
private async void OnPackageInstalling(object sender, InstallationInfo e)
{
SendMessageToAdminSessions("PackageInstalling", e.InstallationInfo);
await SendMessageToAdminSessions("PackageInstalling", e).ConfigureAwait(false);
}
private void OnPackageInstallationCancelled(object sender, InstallationEventArgs e)
private async void OnPackageInstallationCancelled(object sender, InstallationInfo e)
{
SendMessageToAdminSessions("PackageInstallationCancelled", e.InstallationInfo);
await SendMessageToAdminSessions("PackageInstallationCancelled", e).ConfigureAwait(false);
}
private void OnPackageInstallationCompleted(object sender, InstallationEventArgs e)
private async void OnPackageInstallationCompleted(object sender, InstallationInfo e)
{
SendMessageToAdminSessions("PackageInstallationCompleted", e.InstallationInfo);
await SendMessageToAdminSessions("PackageInstallationCompleted", e).ConfigureAwait(false);
}
private void OnPackageInstallationFailed(object sender, InstallationFailedEventArgs e)
private async void OnPackageInstallationFailed(object sender, InstallationFailedEventArgs e)
{
SendMessageToAdminSessions("PackageInstallationFailed", e.InstallationInfo);
await SendMessageToAdminSessions("PackageInstallationFailed", e.InstallationInfo).ConfigureAwait(false);
}
private void OnTaskCompleted(object sender, TaskCompletionEventArgs e)
private async void OnTaskCompleted(object sender, TaskCompletionEventArgs e)
{
SendMessageToAdminSessions("ScheduledTaskEnded", e.Result);
await SendMessageToAdminSessions("ScheduledTaskEnded", e.Result).ConfigureAwait(false);
}
/// <summary>
@ -115,9 +116,9 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void OnPluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
private async void OnPluginUninstalled(object sender, IPlugin e)
{
SendMessageToAdminSessions("PluginUninstalled", e.Argument.GetPluginInfo());
await SendMessageToAdminSessions("PluginUninstalled", e).ConfigureAwait(false);
}
/// <summary>
@ -125,9 +126,9 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void OnHasPendingRestartChanged(object sender, EventArgs e)
private async void OnHasPendingRestartChanged(object sender, EventArgs e)
{
_sessionManager.SendRestartRequiredNotification(CancellationToken.None);
await _sessionManager.SendRestartRequiredNotification(CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
@ -135,11 +136,11 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void OnUserUpdated(object sender, GenericEventArgs<User> e)
private async void OnUserUpdated(object sender, GenericEventArgs<User> e)
{
var dto = _userManager.GetUserDto(e.Argument);
SendMessageToUserSession(e.Argument, "UserUpdated", dto);
await SendMessageToUserSession(e.Argument, "UserUpdated", dto).ConfigureAwait(false);
}
/// <summary>
@ -147,26 +148,26 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void OnUserDeleted(object sender, GenericEventArgs<User> e)
private async void OnUserDeleted(object sender, GenericEventArgs<User> e)
{
SendMessageToUserSession(e.Argument, "UserDeleted", e.Argument.Id.ToString("N", CultureInfo.InvariantCulture));
await SendMessageToUserSession(e.Argument, "UserDeleted", e.Argument.Id.ToString("N", CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
private void OnUserPolicyUpdated(object sender, GenericEventArgs<User> e)
private async void OnUserPolicyUpdated(object sender, GenericEventArgs<User> e)
{
var dto = _userManager.GetUserDto(e.Argument);
SendMessageToUserSession(e.Argument, "UserPolicyUpdated", dto);
await SendMessageToUserSession(e.Argument, "UserPolicyUpdated", dto).ConfigureAwait(false);
}
private void OnUserConfigurationUpdated(object sender, GenericEventArgs<User> e)
private async void OnUserConfigurationUpdated(object sender, GenericEventArgs<User> e)
{
var dto = _userManager.GetUserDto(e.Argument);
SendMessageToUserSession(e.Argument, "UserConfigurationUpdated", dto);
await SendMessageToUserSession(e.Argument, "UserConfigurationUpdated", dto).ConfigureAwait(false);
}
private async void SendMessageToAdminSessions<T>(string name, T data)
private async Task SendMessageToAdminSessions<T>(string name, T data)
{
try
{
@ -178,7 +179,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
private async void SendMessageToUserSession<T>(User user, string name, T data)
private async Task SendMessageToUserSession<T>(User user, string name, T data)
{
try
{

View File

@ -3,6 +3,7 @@ using System.Threading.Tasks;
using Emby.Server.Implementations.Udp;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
@ -22,6 +23,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
private readonly ILogger _logger;
private readonly IServerApplicationHost _appHost;
private readonly IConfiguration _config;
/// <summary>
/// The UDP server.
@ -35,19 +37,21 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
public UdpServerEntryPoint(
ILogger<UdpServerEntryPoint> logger,
IServerApplicationHost appHost)
IServerApplicationHost appHost,
IConfiguration configuration)
{
_logger = logger;
_appHost = appHost;
_config = configuration;
}
/// <inheritdoc />
public async Task RunAsync()
public Task RunAsync()
{
_udpServer = new UdpServer(_logger, _appHost);
_udpServer = new UdpServer(_logger, _appHost, _config);
_udpServer.Start(PortNumber, _cancellationTokenSource.Token);
return Task.CompletedTask;
}
/// <inheritdoc />

View File

@ -56,6 +56,7 @@ namespace Emby.Server.Implementations.HttpServer
/// <summary>
/// Gets the result.
/// </summary>
/// <param name="requestContext">The request context.</param>
/// <param name="content">The content.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="responseHeaders">The response headers.</param>
@ -255,16 +256,20 @@ namespace Emby.Server.Implementations.HttpServer
{
var acceptEncoding = request.Headers[HeaderNames.AcceptEncoding].ToString();
if (string.IsNullOrEmpty(acceptEncoding))
if (!string.IsNullOrEmpty(acceptEncoding))
{
//if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
// if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
// return "br";
if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
if (acceptEncoding.Contains("deflate", StringComparison.OrdinalIgnoreCase))
{
return "deflate";
}
if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
if (acceptEncoding.Contains("gzip", StringComparison.OrdinalIgnoreCase))
{
return "gzip";
}
}
return null;

View File

@ -78,6 +78,9 @@ namespace Emby.Server.Implementations.HttpServer
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
/// <inheritdoc />
public DateTime LastKeepAliveDate { get; set; }
/// <summary>
/// Gets or sets the query string.
/// </summary>
@ -218,7 +221,42 @@ namespace Emby.Server.Implementations.HttpServer
Connection = this
};
await OnReceive(info).ConfigureAwait(false);
if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
{
await SendKeepAliveResponse();
}
else
{
await OnReceive(info).ConfigureAwait(false);
}
}
private Task SendKeepAliveResponse()
{
LastKeepAliveDate = DateTime.UtcNow;
return SendAsync(new WebSocketMessage<string>
{
MessageType = "KeepAlive"
}, CancellationToken.None);
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
_socket.Dispose();
}
}
}
}

View File

@ -1,3 +1,7 @@
#pragma warning disable CS1591
using System;
namespace Emby.Server.Implementations
{
public interface IStartupOptions
@ -36,5 +40,10 @@ namespace Emby.Server.Implementations
/// Gets the value of the --plugin-manifest-url command line option.
/// </summary>
string PluginManifestUrl { get; }
/// <summary>
/// Gets the value of the --published-server-url command line option.
/// </summary>
Uri PublishedServerUrl { get; }
}
}

View File

@ -0,0 +1,60 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Linq;
using Emby.Server.Implementations.Images;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Images
{
/// <summary>
/// Class ArtistImageProvider.
/// </summary>
public class ArtistImageProvider : BaseDynamicImageProvider<MusicArtist>
{
/// <summary>
/// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
public ArtistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
_libraryManager = libraryManager;
}
/// <summary>
/// Get children objects used to create an artist image.
/// </summary>
/// <param name="item">The artist used to create the image.</param>
/// <returns>Any relevant children objects.</returns>
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return Array.Empty<BaseItem>();
// TODO enable this when BaseDynamicImageProvider objects are configurable
// return _libraryManager.GetItemList(new InternalItemsQuery
// {
// ArtistIds = new[] { item.Id },
// IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
// OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
// Limit = 4,
// Recursive = true,
// ImageTypes = new[] { ImageType.Primary },
// DtoOptions = new DtoOptions(false)
// });
}
}
}

View File

@ -194,7 +194,8 @@ namespace Emby.Server.Implementations.Images
return outputPath;
}
protected virtual string CreateImage(BaseItem item,
protected virtual string CreateImage(
BaseItem item,
IReadOnlyCollection<BaseItem> itemsWithImages,
string outputPathWithoutExtension,
ImageType imageType,
@ -214,7 +215,12 @@ namespace Emby.Server.Implementations.Images
if (imageType == ImageType.Primary)
{
if (item is UserView || item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
if (item is UserView
|| item is Playlist
|| item is MusicGenre
|| item is Genre
|| item is PhotoAlbum
|| item is MusicArtist)
{
return CreateSquareCollage(item, itemsWithImages, outputPath);
}
@ -225,7 +231,7 @@ namespace Emby.Server.Implementations.Images
throw new ArgumentException("Unexpected image type", nameof(imageType));
}
public bool HasChanged(BaseItem item, IDirectoryService directoryServicee)
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
if (!Supports(item))
{
@ -236,6 +242,7 @@ namespace Emby.Server.Implementations.Images
{
return true;
}
if (SupportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
{
return true;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.IO;
@ -11,7 +13,7 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.UserViews
namespace Emby.Server.Implementations.Images
{
public class CollectionFolderImageProvider : BaseDynamicImageProvider<CollectionFolder>
{

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.IO;
@ -14,18 +16,16 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.UserViews
namespace Emby.Server.Implementations.Images
{
public class DynamicImageProvider : BaseDynamicImageProvider<UserView>
{
private readonly IUserManager _userManager;
private readonly ILibraryManager _libraryManager;
public DynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, IUserManager userManager, ILibraryManager libraryManager)
public DynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, IUserManager userManager)
: base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
_userManager = userManager;
_libraryManager = libraryManager;
}
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System.Collections.Generic;
using Emby.Server.Implementations.Images;
using MediaBrowser.Common.Configuration;
@ -11,7 +13,7 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.UserViews
namespace Emby.Server.Implementations.Images
{
public abstract class BaseFolderImageProvider<T> : BaseDynamicImageProvider<T>
where T : Folder, new()
@ -75,16 +77,12 @@ namespace Emby.Server.Implementations.UserViews
return false;
}
var folder = item as Folder;
if (folder != null)
if (item is Folder && item.IsTopParent)
{
if (folder.IsTopParent)
{
return false;
}
return false;
}
return true;
//return item.SourceType == SourceType.Library;
}
}

View File

@ -1,6 +1,6 @@
#pragma warning disable CS1591
using System.Collections.Generic;
using System.Linq;
using Emby.Server.Implementations.Images;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
@ -9,66 +9,21 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Querying;
namespace Emby.Server.Implementations.Playlists
namespace Emby.Server.Implementations.Images
{
public class PlaylistImageProvider : BaseDynamicImageProvider<Playlist>
{
public PlaylistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
}
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var playlist = (Playlist)item;
return playlist.GetManageableItems()
.Select(i =>
{
var subItem = i.Item2;
var episode = subItem as Episode;
if (episode != null)
{
var series = episode.Series;
if (series != null && series.HasImage(ImageType.Primary))
{
return series;
}
}
if (subItem.HasImage(ImageType.Primary))
{
return subItem;
}
var parent = subItem.GetOwner() ?? subItem.GetParent();
if (parent != null && parent.HasImage(ImageType.Primary))
{
if (parent is MusicAlbum)
{
return parent;
}
}
return null;
})
.Where(i => i != null)
.GroupBy(x => x.Id)
.Select(x => x.First())
.ToList();
}
}
/// <summary>
/// Class MusicGenreImageProvider.
/// </summary>
public class MusicGenreImageProvider : BaseDynamicImageProvider<MusicGenre>
{
/// <summary>
/// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
public MusicGenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
@ -76,6 +31,11 @@ namespace Emby.Server.Implementations.Playlists
_libraryManager = libraryManager;
}
/// <summary>
/// Get children objects used to create an music genre image.
/// </summary>
/// <param name="item">The music genre used to create the image.</param>
/// <returns>Any relevant children objects.</returns>
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery
@ -91,8 +51,14 @@ namespace Emby.Server.Implementations.Playlists
}
}
/// <summary>
/// Class GenreImageProvider.
/// </summary>
public class GenreImageProvider : BaseDynamicImageProvider<Genre>
{
/// <summary>
/// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
public GenreImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
@ -100,6 +66,11 @@ namespace Emby.Server.Implementations.Playlists
_libraryManager = libraryManager;
}
/// <summary>
/// Get children objects used to create an genre image.
/// </summary>
/// <param name="item">The genre used to create the image.</param>
/// <returns>Any relevant children objects.</returns>
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery

View File

@ -0,0 +1,66 @@
#pragma warning disable CS1591
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.Images
{
public class PlaylistImageProvider : BaseDynamicImageProvider<Playlist>
{
public PlaylistImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
}
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var playlist = (Playlist)item;
return playlist.GetManageableItems()
.Select(i =>
{
var subItem = i.Item2;
var episode = subItem as Episode;
if (episode != null)
{
var series = episode.Series;
if (series != null && series.HasImage(ImageType.Primary))
{
return series;
}
}
if (subItem.HasImage(ImageType.Primary))
{
return subItem;
}
var parent = subItem.GetOwner() ?? subItem.GetParent();
if (parent != null && parent.HasImage(ImageType.Primary))
{
if (parent is MusicAlbum)
{
return parent;
}
}
return null;
})
.Where(i => i != null)
.GroupBy(x => x.Id)
.Select(x => x.First())
.ToList();
}
}
}

View File

@ -135,43 +135,5 @@ namespace Emby.Server.Implementations.Library
? null
: Hex.Encode(PasswordHash.Parse(user.EasyPassword).Hash);
}
/// <summary>
/// Gets the hashed string.
/// </summary>
public string GetHashedString(User user, string str)
{
if (string.IsNullOrEmpty(user.Password))
{
return _cryptographyProvider.CreatePasswordHash(str).ToString();
}
// TODO: make use of iterations parameter?
PasswordHash passwordHash = PasswordHash.Parse(user.Password);
var salt = passwordHash.Salt.ToArray();
return new PasswordHash(
passwordHash.Id,
_cryptographyProvider.ComputeHash(
passwordHash.Id,
Encoding.UTF8.GetBytes(str),
salt),
salt,
passwordHash.Parameters.ToDictionary(x => x.Key, y => y.Value)).ToString();
}
public ReadOnlySpan<byte> GetHashed(User user, string str)
{
if (string.IsNullOrEmpty(user.Password))
{
return _cryptographyProvider.CreatePasswordHash(str).Hash;
}
// TODO: make use of iterations parameter?
PasswordHash passwordHash = PasswordHash.Parse(user.Password);
return _cryptographyProvider.ComputeHash(
passwordHash.Id,
Encoding.UTF8.GetBytes(str),
passwordHash.Salt.ToArray());
}
}
}

View File

@ -21,6 +21,7 @@ using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
@ -35,6 +36,7 @@ using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
@ -50,7 +52,7 @@ using VideoResolver = Emby.Naming.Video.VideoResolver;
namespace Emby.Server.Implementations.Library
{
/// <summary>
/// Class LibraryManager
/// Class LibraryManager.
/// </summary>
public class LibraryManager : ILibraryManager
{
@ -67,6 +69,7 @@ namespace Emby.Server.Implementations.Library
private readonly IFileSystem _fileSystem;
private readonly IItemRepository _itemRepository;
private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
private readonly IImageProcessor _imageProcessor;
private NamingOptions _namingOptions;
private string[] _videoFileExtensions;
@ -135,6 +138,13 @@ namespace Emby.Server.Implementations.Library
/// <param name="userManager">The user manager.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="userDataRepository">The user data repository.</param>
/// <param name="libraryMonitorFactory">The library monitor.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="providerManagerFactory">The provider manager.</param>
/// <param name="userviewManagerFactory">The userview manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
/// <param name="itemRepository">The item repository.</param>
/// <param name="imageProcessor">The image processor.</param>
public LibraryManager(
IServerApplicationHost appHost,
ILogger<LibraryManager> logger,
@ -147,7 +157,8 @@ namespace Emby.Server.Implementations.Library
Lazy<IProviderManager> providerManagerFactory,
Lazy<IUserViewManager> userviewManagerFactory,
IMediaEncoder mediaEncoder,
IItemRepository itemRepository)
IItemRepository itemRepository,
IImageProcessor imageProcessor)
{
_appHost = appHost;
_logger = logger;
@ -161,6 +172,7 @@ namespace Emby.Server.Implementations.Library
_userviewManagerFactory = userviewManagerFactory;
_mediaEncoder = mediaEncoder;
_itemRepository = itemRepository;
_imageProcessor = imageProcessor;
_libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
@ -1815,10 +1827,90 @@ namespace Emby.Server.Implementations.Library
}
}
public void UpdateImages(BaseItem item)
private bool ImageNeedsRefresh(ItemImageInfo image)
{
_itemRepository.SaveImages(item);
if (image.Path != null && image.IsLocalFile)
{
if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
{
return true;
}
try
{
return _fileSystem.GetLastWriteTimeUtc(image.Path) != image.DateModified;
}
catch (Exception ex)
{
_logger.LogError(ex, "Cannot get file info for {0}", image.Path);
return false;
}
}
return image.Path != null && !image.IsLocalFile;
}
public void UpdateImages(BaseItem item, bool forceUpdate = false)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
var outdated = forceUpdate ? item.ImageInfos.Where(i => i.Path != null).ToArray() : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
if (outdated.Length == 0)
{
RegisterItem(item);
return;
}
foreach (var img in outdated)
{
var image = img;
if (!img.IsLocalFile)
{
try
{
var index = item.GetImageIndex(img);
image = ConvertImageToLocal(item, img, index).ConfigureAwait(false).GetAwaiter().GetResult();
}
catch (ArgumentException)
{
_logger.LogWarning("Cannot get image index for {0}", img.Path);
continue;
}
catch (InvalidOperationException)
{
_logger.LogWarning("Cannot fetch image from {0}", img.Path);
continue;
}
}
ImageDimensions size = _imageProcessor.GetImageDimensions(item, image);
image.Width = size.Width;
image.Height = size.Height;
try
{
image.BlurHash = _imageProcessor.GetImageBlurHash(image.Path);
}
catch (Exception ex)
{
_logger.LogError(ex, "Cannot compute blurhash for {0}", image.Path);
image.BlurHash = string.Empty;
}
try
{
image.DateModified = _fileSystem.GetLastWriteTimeUtc(image.Path);
}
catch (Exception ex)
{
_logger.LogError(ex, "Cannot update DateModified for {0}", image.Path);
}
}
_itemRepository.SaveImages(item);
RegisterItem(item);
}
@ -1839,7 +1931,7 @@ namespace Emby.Server.Implementations.Library
item.DateLastSaved = DateTime.UtcNow;
RegisterItem(item);
UpdateImages(item, updateReason >= ItemUpdateType.ImageUpdate);
}
_itemRepository.SaveItems(itemsList, cancellationToken);

View File

@ -521,11 +521,7 @@ namespace Emby.Server.Implementations.Library
SetDefaultAudioAndSubtitleStreamIndexes(item, clone, user);
}
return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse
{
MediaSource = clone
}, liveStream as IDirectStreamProvider);
return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDirectStreamProvider);
}
private static void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio)

View File

@ -240,7 +240,7 @@ namespace Emby.Server.Implementations.Library
{
// Enforce MinResumeDuration
var durationSeconds = TimeSpan.FromTicks(runtimeTicks).TotalSeconds;
if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
if (durationSeconds < _config.Configuration.MinResumeDurationSeconds && !(item is Book))
{
positionTicks = 0;
data.Played = playedToCompletion = true;

View File

@ -126,7 +126,7 @@ namespace Emby.Server.Implementations.Library
/// <param name="user">The user.</param>
private void OnUserUpdated(User user)
{
UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
UserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
}
/// <summary>
@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.Library
/// <param name="user">The user.</param>
private void OnUserDeleted(User user)
{
UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
UserDeleted?.Invoke(this, new GenericEventArgs<User>(user));
}
public NameIdPair[] GetAuthenticationProviders()
@ -608,31 +608,6 @@ namespace Emby.Server.Implementations.Library
return dto;
}
public PublicUserDto GetPublicUserDto(User user, string remoteEndPoint = null)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
IAuthenticationProvider authenticationProvider = GetAuthenticationProvider(user);
bool hasConfiguredPassword = authenticationProvider.HasPassword(user);
bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(authenticationProvider.GetEasyPasswordHash(user));
bool hasPassword = user.Configuration.EnableLocalPassword &&
!string.IsNullOrEmpty(remoteEndPoint) &&
_networkManager.IsInLocalNetwork(remoteEndPoint) ? hasConfiguredEasyPassword : hasConfiguredPassword;
PublicUserDto dto = new PublicUserDto
{
Name = user.Name,
HasPassword = hasPassword,
HasConfiguredPassword = hasConfiguredPassword,
};
return dto;
}
public UserDto GetOfflineUserDto(User user)
{
var dto = GetUserDto(user);
@ -776,7 +751,7 @@ namespace Emby.Server.Implementations.Library
_userRepository.CreateUser(user);
EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User>(user), _logger);
return user;
}
@ -1001,7 +976,7 @@ namespace Emby.Server.Implementations.Library
if (fireEvent)
{
UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User>(user));
}
}
@ -1071,7 +1046,7 @@ namespace Emby.Server.Implementations.Library
if (fireEvent)
{
UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User>(user));
}
}
}

View File

@ -140,11 +140,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
{
OnRecordingFoldersChanged();
await CreateRecordingFolders().ConfigureAwait(false);
}
}
@ -155,11 +155,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return CreateRecordingFolders();
}
private async void OnRecordingFoldersChanged()
{
await CreateRecordingFolders().ConfigureAwait(false);
}
internal async Task CreateRecordingFolders()
{
try
@ -1334,7 +1329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
await CreateRecordingFolders().ConfigureAwait(false);
TriggerRefresh(recordPath);
EnforceKeepUpTo(timer, seriesPath);
await EnforceKeepUpTo(timer, seriesPath).ConfigureAwait(false);
};
await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
@ -1494,7 +1489,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return item;
}
private async void EnforceKeepUpTo(TimerInfo timer, string seriesPath)
private async Task EnforceKeepUpTo(TimerInfo timer, string seriesPath)
{
if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
{

View File

@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
onStarted();
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
_ = StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
_logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
@ -321,7 +321,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
private async void StartStreamingLog(Stream source, Stream target)
private async Task StartStreamingLog(Stream source, Stream target)
{
try
{

View File

@ -109,7 +109,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (startDate < now)
{
TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = item });
TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo>(item));
return;
}
@ -151,7 +151,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase));
if (timer != null)
{
TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = timer });
TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
}
}

View File

@ -10,10 +10,8 @@ using Emby.Server.Implementations.Library;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
@ -148,27 +146,18 @@ namespace Emby.Server.Implementations.LiveTv
{
var timerId = e.Argument;
TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = timerId
}
});
TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(timerId)));
}
private void OnEmbyTvTimerCreated(object sender, GenericEventArgs<TimerInfo> e)
{
var timer = e.Argument;
TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
new TimerEventInfo(timer.Id)
{
ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId),
Id = timer.Id
}
});
ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId)
}));
}
public List<NameIdPair> GetTunerHostTypes()
@ -788,22 +777,12 @@ namespace Emby.Server.Implementations.LiveTv
if (query.OrderBy.Count == 0)
{
if (query.IsAiring ?? false)
// Unless something else was specified, order by start date to take advantage of a specialized index
query.OrderBy = new[]
{
// Unless something else was specified, order by start date to take advantage of a specialized index
query.OrderBy = new[]
{
(ItemSortBy.StartDate, SortOrder.Ascending)
};
}
else
{
// Unless something else was specified, order by start date to take advantage of a specialized index
query.OrderBy = new[]
{
(ItemSortBy.StartDate, SortOrder.Ascending)
};
}
(ItemSortBy.StartDate, SortOrder.Ascending)
};
}
RemoveFields(options);
@ -1734,13 +1713,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!(service is EmbyTV.EmbyTV))
{
TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = id
}
});
TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(id)));
}
}
@ -1757,13 +1730,7 @@ namespace Emby.Server.Implementations.LiveTv
await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = id
}
});
SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>(new TimerEventInfo(id)));
}
public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
@ -2082,14 +2049,11 @@ namespace Emby.Server.Implementations.LiveTv
if (!(service is EmbyTV.EmbyTV))
{
TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
new TimerEventInfo(newTimerId)
{
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
Id = newTimerId
}
});
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId)
}));
}
}
@ -2114,14 +2078,11 @@ namespace Emby.Server.Implementations.LiveTv
await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
}
SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>(
new TimerEventInfo(newTimerId)
{
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
Id = newTimerId
}
});
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId)
}));
}
public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

View File

@ -93,5 +93,12 @@
"HeaderFavoriteSongs": "প্রিয় গানগুলো",
"HeaderFavoriteShows": "প্রিয় শোগুলো",
"TasksLibraryCategory": "গ্রন্থাগার",
"TasksMaintenanceCategory": "রক্ষণাবেক্ষণ"
"TasksMaintenanceCategory": "রক্ষণাবেক্ষণ",
"TaskRefreshLibrary": "স্ক্যান মিডিয়া লাইব্রেরি",
"TaskRefreshChapterImagesDescription": "অধ্যায়গুলিতে থাকা ভিডিওগুলির জন্য থাম্বনেইল তৈরি ।",
"TaskRefreshChapterImages": "অধ্যায়ের চিত্রগুলি বের করুন",
"TaskCleanCacheDescription": "সিস্টেমে আর প্রয়োজন নেই ক্যাশ, ফাইলগুলি মুছে ফেলুন।",
"TaskCleanCache": "ক্লিন ক্যাশ ডিরেক্টরি",
"TasksChannelsCategory": "ইন্টারনেট চ্যানেল",
"TasksApplicationCategory": "আবেদন"
}

View File

@ -92,5 +92,27 @@
"UserStoppedPlayingItemWithValues": "{0} ha parat de reproduir {1}",
"ValueHasBeenAddedToLibrary": "{0} ha sigut afegit a la teva llibreria",
"ValueSpecialEpisodeName": "Especial - {0}",
"VersionNumber": "Versió {0}"
"VersionNumber": "Versió {0}",
"TaskDownloadMissingSubtitlesDescription": "Cerca a internet els subtítols que faltin a partir de la configuració de metadades.",
"TaskDownloadMissingSubtitles": "Descarrega els subtítols que faltin",
"TaskRefreshChannelsDescription": "Actualitza la informació dels canals d'internet.",
"TaskRefreshChannels": "Actualitza Canals",
"TaskCleanTranscodeDescription": "Elimina els arxius temporals de transcodificacions que tinguin més d'un dia.",
"TaskCleanTranscode": "Neteja les transcodificacions",
"TaskUpdatePluginsDescription": "Actualitza les extensions que estan configurades per actualitzar-se automàticament.",
"TaskUpdatePlugins": "Actualitza les extensions",
"TaskRefreshPeopleDescription": "Actualitza les metadades dels actors i directors de la teva mediateca.",
"TaskRefreshPeople": "Actualitza Persones",
"TaskCleanLogsDescription": "Esborra els logs que tinguin més de {0} dies.",
"TaskCleanLogs": "Neteja els registres",
"TaskRefreshLibraryDescription": "Escaneja la mediateca buscant fitxers nous i refresca les metadades.",
"TaskRefreshLibrary": "Escaneja la biblioteca de mitjans",
"TaskRefreshChapterImagesDescription": "Crea les miniatures dels vídeos que tinguin capítols.",
"TaskRefreshChapterImages": "Extreure les imatges dels capítols",
"TaskCleanCacheDescription": "Elimina els arxius temporals que ja no són necessaris per al servidor.",
"TaskCleanCache": "Elimina arxius temporals",
"TasksChannelsCategory": "Canals d'internet",
"TasksApplicationCategory": "Aplicació",
"TasksLibraryCategory": "Biblioteca",
"TasksMaintenanceCategory": "Manteniment"
}

View File

@ -0,0 +1,117 @@
{
"LabelRunningTimeValue": "Duración: {0}",
"ValueSpecialEpisodeName": "Especial - {0}",
"Sync": "Sincronizar",
"Songs": "Canciones",
"Shows": "Programas",
"Playlists": "Listas de reproducción",
"Photos": "Fotos",
"Movies": "Películas",
"HeaderNextUp": "A continuación",
"HeaderLiveTV": "TV en vivo",
"HeaderFavoriteSongs": "Canciones favoritas",
"HeaderFavoriteArtists": "Artistas favoritos",
"HeaderFavoriteAlbums": "Álbumes favoritos",
"HeaderFavoriteEpisodes": "Episodios favoritos",
"HeaderFavoriteShows": "Programas favoritos",
"HeaderContinueWatching": "Continuar viendo",
"HeaderAlbumArtists": "Artistas del álbum",
"Genres": "Géneros",
"Folders": "Carpetas",
"Favorites": "Favoritos",
"Collections": "Colecciones",
"Channels": "Canales",
"Books": "Libros",
"Artists": "Artistas",
"Albums": "Álbumes",
"TaskDownloadMissingSubtitlesDescription": "Busca subtítulos faltantes en Internet basándose en la configuración de metadatos.",
"TaskDownloadMissingSubtitles": "Descargar subtítulos faltantes",
"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",
"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.",
"TaskRefreshPeople": "Actualizar personas",
"TaskCleanLogsDescription": "Elimina archivos de registro con más de {0} días de antigüedad.",
"TaskCleanLogs": "Limpiar directorio de registros",
"TaskRefreshLibraryDescription": "Escanea tu biblioteca de medios por archivos nuevos y actualiza los metadatos.",
"TaskRefreshLibrary": "Escanear biblioteca de medios",
"TaskRefreshChapterImagesDescription": "Crea miniaturas para videos que tienen capítulos.",
"TaskRefreshChapterImages": "Extraer imágenes de los capítulos",
"TaskCleanCacheDescription": "Elimina archivos caché que ya no son necesarios para el sistema.",
"TaskCleanCache": "Limpiar directorio caché",
"TasksChannelsCategory": "Canales de Internet",
"TasksApplicationCategory": "Aplicación",
"TasksLibraryCategory": "Biblioteca",
"TasksMaintenanceCategory": "Mantenimiento",
"VersionNumber": "Versión {0}",
"ValueHasBeenAddedToLibrary": "{0} se ha añadido a tu biblioteca de medios",
"UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
"UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
"UserPolicyUpdatedWithName": "La política de usuario ha sido actualizada para {0}",
"UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
"UserOnlineFromDevice": "{0} está en línea desde {1}",
"UserOfflineFromDevice": "{0} se ha desconectado desde {1}",
"UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
"UserDownloadingItemWithValues": "{0} está descargando {1}",
"UserDeletedWithName": "El usuario {0} ha sido eliminado",
"UserCreatedWithName": "El usuario {0} ha sido creado",
"User": "Usuario",
"TvShows": "Programas de TV",
"System": "Sistema",
"SubtitleDownloadFailureFromForItem": "Falló la descarga de subtítulos desde {0} para {1}",
"StartupEmbyServerIsLoading": "El servidor Jellyfin está cargando. Por favor, intente de nuevo pronto.",
"ServerNameNeedsToBeRestarted": "{0} debe ser reiniciado",
"ScheduledTaskStartedWithName": "{0} iniciado",
"ScheduledTaskFailedWithName": "{0} falló",
"ProviderValue": "Proveedor: {0}",
"PluginUpdatedWithName": "{0} fue actualizado",
"PluginUninstalledWithName": "{0} fue desinstalado",
"PluginInstalledWithName": "{0} fue instalado",
"Plugin": "Complemento",
"NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
"NotificationOptionVideoPlayback": "Reproducción de video iniciada",
"NotificationOptionUserLockedOut": "Usuario bloqueado",
"NotificationOptionTaskFailed": "Falla de tarea programada",
"NotificationOptionServerRestartRequired": "Se necesita reiniciar el servidor",
"NotificationOptionPluginUpdateInstalled": "Actualización de complemento instalada",
"NotificationOptionPluginUninstalled": "Complemento desinstalado",
"NotificationOptionPluginInstalled": "Complemento instalado",
"NotificationOptionPluginError": "Falla de complemento",
"NotificationOptionNewLibraryContent": "Nuevo contenido agregado",
"NotificationOptionInstallationFailed": "Falla de instalación",
"NotificationOptionCameraImageUploaded": "Imagen de la cámara subida",
"NotificationOptionAudioPlaybackStopped": "Reproducción de audio detenida",
"NotificationOptionAudioPlayback": "Reproducción de audio iniciada",
"NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
"NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
"NewVersionIsAvailable": "Una nueva versión del Servidor Jellyfin está disponible para descargar.",
"NameSeasonUnknown": "Temporada desconocida",
"NameSeasonNumber": "Temporada {0}",
"NameInstallFailed": "Falló la instalación de {0}",
"MusicVideos": "Videos musicales",
"Music": "Música",
"MixedContent": "Contenido mezclado",
"MessageServerConfigurationUpdated": "Se ha actualizado la configuración del servidor",
"MessageNamedServerConfigurationUpdatedWithValue": "Se ha actualizado la sección {0} de la configuración del servidor",
"MessageApplicationUpdatedTo": "El servidor Jellyfin ha sido actualizado a {0}",
"MessageApplicationUpdated": "El servidor Jellyfin ha sido actualizado",
"Latest": "Recientes",
"LabelIpAddressValue": "Dirección IP: {0}",
"ItemRemovedWithName": "{0} fue removido de la biblioteca",
"ItemAddedWithName": "{0} fue agregado a la biblioteca",
"Inherit": "Heredar",
"HomeVideos": "Videos caseros",
"HeaderRecordingGroups": "Grupos de grabación",
"HeaderCameraUploads": "Subidas desde la cámara",
"FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión desde {0}",
"DeviceOnlineWithName": "{0} está conectado",
"DeviceOfflineWithName": "{0} se ha desconectado",
"ChapterNameValue": "Capítulo {0}",
"CameraImageUploadedFrom": "Una nueva imagen de cámara ha sido subida desde {0}",
"AuthenticationSucceededWithUserName": "{0} autenticado con éxito",
"Application": "Aplicación",
"AppDeviceValues": "App: {0}, Dispositivo: {1}"
}

View File

@ -5,7 +5,7 @@
"Artists": "Artistes",
"AuthenticationSucceededWithUserName": "{0} authentifié avec succès",
"Books": "Livres",
"CameraImageUploadedFrom": "Une nouvelle photographie a été chargée depuis {0}",
"CameraImageUploadedFrom": "Une photo a été chargée depuis {0}",
"Channels": "Chaînes",
"ChapterNameValue": "Chapitre {0}",
"Collections": "Collections",
@ -15,7 +15,7 @@
"Favorites": "Favoris",
"Folders": "Dossiers",
"Genres": "Genres",
"HeaderAlbumArtists": "Artistes de l'album",
"HeaderAlbumArtists": "Artistes",
"HeaderCameraUploads": "Photos transférées",
"HeaderContinueWatching": "Continuer à regarder",
"HeaderFavoriteAlbums": "Albums favoris",

View File

@ -101,5 +101,18 @@
"TaskRefreshLibrary": "Skann mediebibliotek",
"TaskRefreshChapterImagesDescription": "Lager forhåndsvisningsbilder for videoer som har kapitler.",
"TaskRefreshChapterImages": "Trekk ut Kapittelbilder",
"TaskCleanCacheDescription": "Sletter mellomlagrede filer som ikke lengre trengs av systemet."
"TaskCleanCacheDescription": "Sletter mellomlagrede filer som ikke lengre trengs av systemet.",
"TaskDownloadMissingSubtitlesDescription": "Søker etter manglende underteksting på nett basert på metadatakonfigurasjon.",
"TaskDownloadMissingSubtitles": "Last ned manglende underteksting",
"TaskRefreshChannelsDescription": "Frisker opp internettkanalinformasjon.",
"TaskRefreshChannels": "Oppfrisk kanaler",
"TaskCleanTranscodeDescription": "Sletter omkodede filer som er mer enn én dag gamle.",
"TaskCleanTranscode": "Tøm transkodingmappe",
"TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringer for utvidelser som er stilt inn til å oppdatere automatisk.",
"TaskUpdatePlugins": "Oppdater utvidelser",
"TaskRefreshPeopleDescription": "Oppdaterer metadata for skuespillere og regissører i mediebiblioteket ditt.",
"TaskRefreshPeople": "Oppfrisk personer",
"TaskCleanLogsDescription": "Sletter loggfiler som er eldre enn {0} dager gamle.",
"TaskCleanLogs": "Tøm loggmappe",
"TaskRefreshLibraryDescription": "Skanner mediebibliotekene dine for nye filer og oppdaterer metadata."
}

View File

@ -113,5 +113,6 @@
"TasksChannelsCategory": "Spletni kanali",
"TasksApplicationCategory": "Aplikacija",
"TasksLibraryCategory": "Knjižnica",
"TasksMaintenanceCategory": "Vzdrževanje"
"TasksMaintenanceCategory": "Vzdrževanje",
"TaskDownloadMissingSubtitlesDescription": "Na podlagi nastavitev metapodatkov poišče manjkajoče podnapise na internetu."
}

View File

@ -0,0 +1,99 @@
{
"VersionNumber": "பதிப்பு {0}",
"ValueSpecialEpisodeName": "சிறப்பு - {0}",
"TasksMaintenanceCategory": "பராமரிப்பு",
"TaskCleanCache": "தற்காலிக சேமிப்பு கோப்பகத்தை சுத்தம் செய்யவும்",
"TaskRefreshChapterImages": "அத்தியாயப் படங்களை பிரித்தெடுக்கவும்",
"TaskRefreshPeople": "மக்களைப் புதுப்பிக்கவும்",
"TaskCleanTranscode": "டிரான்ஸ்கோட் கோப்பகத்தை சுத்தம் செய்யவும்",
"TaskRefreshChannelsDescription": "இணையச் சேனல் தகவல்களைப் புதுப்பிக்கிறது.",
"System": "ஒருங்கியம்",
"NotificationOptionTaskFailed": "திட்டமிடப்பட்ட பணி தோல்வியடைந்தது",
"NotificationOptionPluginUpdateInstalled": "உட்செருகி புதுப்பிக்கப்பட்டது",
"NotificationOptionPluginUninstalled": "உட்செருகி நீக்கப்பட்டது",
"NotificationOptionPluginInstalled": "உட்செருகி நிறுவப்பட்டது",
"NotificationOptionPluginError": "உட்செருகி செயலிழந்தது",
"NotificationOptionCameraImageUploaded": "புகைப்படம் பதிவேற்றப்பட்டது",
"MixedContent": "கலப்பு உள்ளடக்கங்கள்",
"MessageServerConfigurationUpdated": "சேவையக அமைப்புகள் புதுப்பிக்கப்பட்டன",
"MessageApplicationUpdatedTo": "ஜெல்லிஃபின் சேவையகம் {0} இற்கு புதுப்பிக்கப்பட்டது",
"MessageApplicationUpdated": "ஜெல்லிஃபின் சேவையகம் புதுப்பிக்கப்பட்டது",
"Inherit": "மரபரிமையாகப் பெறு",
"HeaderRecordingGroups": "பதிவு குழுக்கள்",
"HeaderCameraUploads": "புகைப்பட பதிவேற்றங்கள்",
"Folders": "கோப்புறைகள்",
"FailedLoginAttemptWithUserName": "{0} இலிருந்து உள்நுழைவு முயற்சி தோல்வியடைந்தது",
"DeviceOnlineWithName": "{0} இணைக்கப்பட்டது",
"DeviceOfflineWithName": "{0} துண்டிக்கப்பட்டது",
"Collections": "தொகுப்புகள்",
"CameraImageUploadedFrom": "{0} இலிருந்து புதிய புகைப்படம் பதிவேற்றப்பட்டது",
"AppDeviceValues": "செயலி: {0}, சாதனம்: {1}",
"TaskDownloadMissingSubtitles": "விடுபட்டுபோன வசன வரிகளைப் பதிவிறக்கு",
"TaskRefreshChannels": "சேனல்களை புதுப்பி",
"TaskUpdatePlugins": "உட்செருகிகளை புதுப்பி",
"TaskRefreshLibrary": "மீடியா நூலகத்தை ஆராய்",
"TasksChannelsCategory": "இணைய சேனல்கள்",
"TasksApplicationCategory": "செயலி",
"TasksLibraryCategory": "நூலகம்",
"UserPolicyUpdatedWithName": "பயனர் கொள்கை {0} இற்கு புதுப்பிக்கப்பட்டுள்ளது",
"UserPasswordChangedWithName": "{0} பயனருக்கு கடவுச்சொல் மாற்றப்பட்டுள்ளது",
"UserLockedOutWithName": "பயனர் {0} முடக்கப்பட்டார்",
"UserDownloadingItemWithValues": "{0} ஆல் {1} பதிவிறக்கப்படுகிறது",
"UserDeletedWithName": "பயனர் {0} நீக்கப்பட்டார்",
"UserCreatedWithName": "பயனர் {0} உருவாக்கப்பட்டார்",
"User": "பயனர்",
"TvShows": "தொலைக்காட்சித் தொடர்கள்",
"Sync": "ஒத்திசைவு",
"StartupEmbyServerIsLoading": "ஜெல்லிஃபின் சேவையகம் துவங்குகிறது. சிறிது நேரம் கழித்து முயற்சிக்கவும்.",
"Songs": "பாட்டுகள்",
"Shows": "தொடர்கள்",
"ServerNameNeedsToBeRestarted": "{0} மறுதொடக்கம் செய்யப்பட வேண்டும்",
"ScheduledTaskStartedWithName": "{0} துவங்கியது",
"ScheduledTaskFailedWithName": "{0} தோல்வியடைந்தது",
"ProviderValue": "வழங்குநர்: {0}",
"PluginUpdatedWithName": "{0} புதுப்பிக்கப்பட்டது",
"PluginUninstalledWithName": "{0} நீக்கப்பட்டது",
"PluginInstalledWithName": "{0} நிறுவப்பட்டது",
"Plugin": "உட்செருகி",
"Playlists": "தொடர் பட்டியல்கள்",
"Photos": "புகைப்படங்கள்",
"NotificationOptionVideoPlaybackStopped": "நிகழ்பட ஒளிபரப்பு நிறுத்தப்பட்டது",
"NotificationOptionVideoPlayback": "நிகழ்பட ஒளிபரப்பு துவங்கியது",
"NotificationOptionUserLockedOut": "பயனர் கணக்கு முடக்கப்பட்டது",
"NotificationOptionServerRestartRequired": "சேவையக மறுதொடக்கம் தேவை",
"NotificationOptionNewLibraryContent": "புதிய உள்ளடக்கங்கள் சேர்க்கப்பட்டன",
"NotificationOptionInstallationFailed": "நிறுவல் தோல்வியடைந்தது",
"NotificationOptionAudioPlaybackStopped": "ஒலி இசைத்தல் நிறுத்தப்பட்டது",
"NotificationOptionAudioPlayback": "ஒலி இசைக்கத் துவங்கியுள்ளது",
"NotificationOptionApplicationUpdateInstalled": "செயலி புதுப்பிக்கப்பட்டது",
"NotificationOptionApplicationUpdateAvailable": "செயலியினை புதுப்பிக்கலாம்",
"NameSeasonUnknown": "பருவம் அறியப்படாதவை",
"NameSeasonNumber": "பருவம் {0}",
"NameInstallFailed": "{0} நிறுவல் தோல்வியடைந்தது",
"MusicVideos": "இசைப்படங்கள்",
"Music": "இசை",
"Movies": "திரைப்படங்கள்",
"Latest": "புதியன",
"LabelRunningTimeValue": "ஓடும் நேரம்: {0}",
"LabelIpAddressValue": "ஐபி முகவரி: {0}",
"ItemRemovedWithName": "{0} நூலகத்திலிருந்து அகற்றப்பட்டது",
"ItemAddedWithName": "{0} நூலகத்தில் சேர்க்கப்பட்டது",
"HeaderNextUp": "அடுத்ததாக",
"HeaderLiveTV": "நேரடித் தொலைக்காட்சி",
"HeaderFavoriteSongs": "பிடித்த பாட்டுகள்",
"HeaderFavoriteShows": "பிடித்த தொடர்கள்",
"HeaderFavoriteEpisodes": "பிடித்த அத்தியாயங்கள்",
"HeaderFavoriteArtists": "பிடித்த கலைஞர்கள்",
"HeaderFavoriteAlbums": "பிடித்த ஆல்பங்கள்",
"HeaderContinueWatching": "தொடர்ந்து பார்",
"HeaderAlbumArtists": "இசைக் கலைஞர்கள்",
"Genres": "வகைகள்",
"Favorites": "பிடித்தவை",
"ChapterNameValue": "அத்தியாயம் {0}",
"Channels": "சேனல்கள்",
"Books": "புத்தகங்கள்",
"AuthenticationSucceededWithUserName": "{0} வெற்றிகரமாக அங்கீகரிக்கப்பட்டது",
"Artists": "கலைஞர்கள்",
"Application": "செயலி",
"Albums": "ஆல்பங்கள்"
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Net;
using System.Net.Sockets;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Net;
using System.Net.Sockets;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;
@ -153,10 +155,7 @@ namespace Emby.Server.Implementations.Playlists
});
}
return new PlaylistCreationResult
{
Id = playlist.Id.ToString("N", CultureInfo.InvariantCulture)
};
return new PlaylistCreationResult(playlist.Id.ToString("N", CultureInfo.InvariantCulture));
}
finally
{

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.IO;
using MediaBrowser.Controller;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Globalization;
using System.IO;
@ -51,7 +53,6 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
/// <value>The task manager.</value>
private ITaskManager TaskManager { get; set; }
private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
@ -72,24 +73,28 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// or
/// logger
/// </exception>
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem)
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger)
{
if (scheduledTask == null)
{
throw new ArgumentNullException(nameof(scheduledTask));
}
if (applicationPaths == null)
{
throw new ArgumentNullException(nameof(applicationPaths));
}
if (taskManager == null)
{
throw new ArgumentNullException(nameof(taskManager));
}
if (jsonSerializer == null)
{
throw new ArgumentNullException(nameof(jsonSerializer));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
@ -100,7 +105,6 @@ namespace Emby.Server.Implementations.ScheduledTasks
TaskManager = taskManager;
JsonSerializer = jsonSerializer;
Logger = logger;
_fileSystem = fileSystem;
InitTriggerEvents();
}
@ -392,7 +396,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
((TaskManager)TaskManager).OnTaskExecuting(this);
progress.ProgressChanged += progress_ProgressChanged;
progress.ProgressChanged += OnProgressChanged;
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
@ -426,7 +430,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var startTime = CurrentExecutionStartTime;
var endTime = DateTime.UtcNow;
progress.ProgressChanged -= progress_ProgressChanged;
progress.ProgressChanged -= OnProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
@ -439,16 +443,13 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void progress_ProgressChanged(object sender, double e)
private void OnProgressChanged(object sender, double e)
{
e = Math.Min(e, 100);
CurrentProgress = e;
TaskProgress?.Invoke(this, new GenericEventArgs<double>
{
Argument = e
});
TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
}
/// <summary>
@ -576,6 +577,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="startTime">The start time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="status">The status.</param>
/// <param name="ex">The exception.</param>
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
{
var elapsedTime = endTime - startTime;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -199,7 +201,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="tasks">The tasks.</param>
public void AddTasks(IEnumerable<IScheduledTask> tasks)
{
var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _jsonSerializer, _logger, _fileSystem));
var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _jsonSerializer, _logger));
ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
}
@ -240,10 +242,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="task">The task.</param>
internal void OnTaskExecuting(IScheduledTaskWorker task)
{
TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
{
Argument = task
});
TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
}
/// <summary>
@ -253,11 +252,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="result">The result.</param>
internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
{
TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
{
Result = result,
Task = task
});
TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
ExecuteQueuedTasks();
}

View File

@ -169,18 +169,25 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
}
/// <inheritdoc />
public string Name => _localization.GetLocalizedString("TaskRefreshChapterImages");
/// <inheritdoc />
public string Description => _localization.GetLocalizedString("TaskRefreshChapterImagesDescription");
/// <inheritdoc />
public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
/// <inheritdoc />
public string Key => "RefreshChapterImages";
/// <inheritdoc />
public bool IsHidden => false;
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
public bool IsLogged => true;
}
}

View File

@ -165,18 +165,25 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
}
}
/// <inheritdoc />
public string Name => _localization.GetLocalizedString("TaskCleanCache");
/// <inheritdoc />
public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
/// <inheritdoc />
public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
/// <inheritdoc />
public string Key => "DeleteCacheFiles";
/// <inheritdoc />
public bool IsHidden => false;
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
public bool IsLogged => true;
}
}

View File

@ -28,6 +28,8 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
/// Initializes a new instance of the <see cref="DeleteLogFileTask" /> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="localization">The localization manager.</param>
public DeleteLogFileTask(IConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization)
{
ConfigurationManager = configurationManager;
@ -82,18 +84,25 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
return Task.CompletedTask;
}
/// <inheritdoc />
public string Name => _localization.GetLocalizedString("TaskCleanLogs");
/// <inheritdoc />
public string Description => string.Format(_localization.GetLocalizedString("TaskCleanLogsDescription"), ConfigurationManager.CommonConfiguration.LogFileRetentionDays);
/// <inheritdoc />
public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
/// <inheritdoc />
public string Key => "CleanLogFiles";
/// <inheritdoc />
public bool IsHidden => false;
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
public bool IsLogged => true;
}
}

View File

@ -132,18 +132,25 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
}
}
/// <inheritdoc />
public string Name => _localization.GetLocalizedString("TaskCleanTranscode");
/// <inheritdoc />
public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription");
/// <inheritdoc />
public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
/// <inheritdoc />
public string Key => "DeleteTranscodeFiles";
/// <inheritdoc />
public bool IsHidden => false;
/// <inheritdoc />
public bool IsEnabled => false;
/// <inheritdoc />
public bool IsLogged => true;
}
}

View File

@ -1,8 +1,9 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Globalization;
@ -18,19 +19,16 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// The library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
private readonly IServerApplicationHost _appHost;
private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="PeopleValidationTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
/// <param name="appHost">The server application host</param>
public PeopleValidationTask(ILibraryManager libraryManager, IServerApplicationHost appHost, ILocalizationManager localization)
/// <param name="localization">The localization manager.</param>
public PeopleValidationTask(ILibraryManager libraryManager, ILocalizationManager localization)
{
_libraryManager = libraryManager;
_appHost = appHost;
_localization = localization;
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.IO;
@ -80,11 +82,11 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
catch (HttpException ex)
{
_logger.LogError(ex, "Error downloading {0}", package.name);
_logger.LogError(ex, "Error downloading {0}", package.Name);
}
catch (IOException ex)
{
_logger.LogError(ex, "Error updating {0}", package.name);
_logger.LogError(ex, "Error updating {0}", package.Name);
}
// Update progress

View File

@ -1,9 +1,10 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Library;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Globalization;
@ -16,20 +17,19 @@ namespace Emby.Server.Implementations.ScheduledTasks
public class RefreshMediaLibraryTask : IScheduledTask
{
/// <summary>
/// The _library manager
/// The _library manager.
/// </summary>
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _config;
private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="RefreshMediaLibraryTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
public RefreshMediaLibraryTask(ILibraryManager libraryManager, IServerConfigurationManager config, ILocalizationManager localization)
/// <param name="localization">The localization manager.</param>
public RefreshMediaLibraryTask(ILibraryManager libraryManager, ILocalizationManager localization)
{
_libraryManager = libraryManager;
_config = config;
_localization = localization;
}
@ -61,18 +61,25 @@ namespace Emby.Server.Implementations.ScheduledTasks
return ((LibraryManager)_libraryManager).ValidateMediaLibraryInternal(progress, cancellationToken);
}
/// <inheritdoc />
public string Name => _localization.GetLocalizedString("TaskRefreshLibrary");
/// <inheritdoc />
public string Description => _localization.GetLocalizedString("TaskRefreshLibraryDescription");
/// <inheritdoc />
public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
/// <inheritdoc />
public string Key => "RefreshLibrary";
/// <inheritdoc />
public bool IsHidden => false;
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
public bool IsLogged => true;
}
}

View File

@ -31,6 +31,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// Stars waiting for the trigger action
/// </summary>
/// <param name="lastResult">The last result.</param>
/// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
@ -77,10 +79,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void OnTriggered()
{
if (Triggered != null)
{
Triggered(this, EventArgs.Empty);
}
Triggered?.Invoke(this, EventArgs.Empty);
}
}
}

View File

@ -34,6 +34,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// Stars waiting for the trigger action
/// </summary>
/// <param name="lastResult">The last result.</param>
/// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Threading.Tasks;
using MediaBrowser.Model.Tasks;
@ -6,7 +8,7 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
/// <summary>
/// Class StartupTaskTrigger
/// Class StartupTaskTrigger.
/// </summary>
public class StartupTrigger : ITaskTrigger
{
@ -26,6 +28,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// Stars waiting for the trigger action
/// </summary>
/// <param name="lastResult">The last result.</param>
/// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public async void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{

View File

@ -37,6 +37,8 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// Stars waiting for the trigger action
/// </summary>
/// <param name="lastResult">The last result.</param>
/// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Globalization;
using System.IO;
@ -11,6 +13,9 @@ namespace Emby.Server.Implementations.Serialization
/// </summary>
public class JsonSerializer : IJsonSerializer
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer" /> class.
/// </summary>
public JsonSerializer()
{
ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System.Collections.Generic;
using System.IO;
using System.Net;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.IO;
using System.Threading.Tasks;
@ -43,10 +45,7 @@ namespace Emby.Server.Implementations.Services
private static string GetContentTypeWithoutEncoding(string contentType)
{
return contentType == null
? null
: contentType.Split(';')[0].ToLowerInvariant().Trim();
return contentType?.Split(';')[0].ToLowerInvariant().Trim();
}
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Globalization;
using System.IO;
@ -43,8 +45,7 @@ namespace Emby.Server.Implementations.Services
response.StatusCode = httpResult.Status;
}
var responseOptions = result as IHasHeaders;
if (responseOptions != null)
if (result is IHasHeaders responseOptions)
{
foreach (var responseHeaders in responseOptions.Headers)
{

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Reflection;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
namespace Emby.Server.Implementations.Services

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Reflection;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using MediaBrowser.Common.Extensions;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -25,6 +27,7 @@ using MediaBrowser.Model.Events;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.SyncPlay;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
@ -1153,6 +1156,22 @@ namespace Emby.Server.Implementations.Session
await SendMessageToSession(session, "Play", command, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken)
{
CheckDisposed();
var session = GetSessionToRemoteControl(sessionId);
await SendMessageToSession(session, "SyncPlayCommand", command, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancellationToken)
{
CheckDisposed();
var session = GetSessionToRemoteControl(sessionId);
await SendMessageToSession(session, "SyncPlayGroupUpdate", command, cancellationToken).ConfigureAwait(false);
}
private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user)
{
var item = _libraryManager.GetItemById(id);

View File

@ -1,8 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
@ -13,6 +18,21 @@ namespace Emby.Server.Implementations.Session
/// </summary>
public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
{
/// <summary>
/// The timeout in seconds after which a WebSocket is considered to be lost.
/// </summary>
public const int WebSocketLostTimeout = 60;
/// <summary>
/// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets.
/// </summary>
public const float IntervalFactor = 0.2f;
/// <summary>
/// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
/// </summary>
public const float ForceKeepAliveFactor = 0.75f;
/// <summary>
/// The _session manager
/// </summary>
@ -26,6 +46,26 @@ namespace Emby.Server.Implementations.Session
private readonly IHttpServer _httpServer;
/// <summary>
/// The KeepAlive cancellation token.
/// </summary>
private CancellationTokenSource _keepAliveCancellationToken;
/// <summary>
/// Lock used for accesing the KeepAlive cancellation token.
/// </summary>
private readonly object _keepAliveLock = new object();
/// <summary>
/// The WebSocket watchlist.
/// </summary>
private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>();
/// <summary>
/// Lock used for accesing the WebSockets watchlist.
/// </summary>
private readonly object _webSocketsLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
/// </summary>
@ -47,12 +87,13 @@ namespace Emby.Server.Implementations.Session
httpServer.WebSocketConnected += OnServerManagerWebSocketConnected;
}
private void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
private async void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
{
var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint.ToString());
if (session != null)
{
EnsureController(session, e.Argument);
await KeepAliveWebSocket(e.Argument);
}
else
{
@ -81,6 +122,7 @@ namespace Emby.Server.Implementations.Session
public void Dispose()
{
_httpServer.WebSocketConnected -= OnServerManagerWebSocketConnected;
StopKeepAlive();
}
/// <summary>
@ -99,5 +141,206 @@ namespace Emby.Server.Implementations.Session
var controller = (WebSocketController)controllerInfo.Item1;
controller.AddWebSocket(connection);
}
/// <summary>
/// Called when a WebSocket is closed.
/// </summary>
/// <param name="sender">The WebSocket.</param>
/// <param name="e">The event arguments.</param>
private void OnWebSocketClosed(object sender, EventArgs e)
{
var webSocket = (IWebSocketConnection)sender;
_logger.LogDebug("WebSocket {0} is closed.", webSocket);
RemoveWebSocket(webSocket);
}
/// <summary>
/// Adds a WebSocket to the KeepAlive watchlist.
/// </summary>
/// <param name="webSocket">The WebSocket to monitor.</param>
private async Task KeepAliveWebSocket(IWebSocketConnection webSocket)
{
lock (_webSocketsLock)
{
if (!_webSockets.Add(webSocket))
{
_logger.LogWarning("Multiple attempts to keep alive single WebSocket {0}", webSocket);
return;
}
webSocket.Closed += OnWebSocketClosed;
webSocket.LastKeepAliveDate = DateTime.UtcNow;
StartKeepAlive();
}
// Notify WebSocket about timeout
try
{
await SendForceKeepAlive(webSocket);
}
catch (WebSocketException exception)
{
_logger.LogWarning(exception, "Cannot send ForceKeepAlive message to WebSocket {0}.", webSocket);
}
}
/// <summary>
/// Removes a WebSocket from the KeepAlive watchlist.
/// </summary>
/// <param name="webSocket">The WebSocket to remove.</param>
private void RemoveWebSocket(IWebSocketConnection webSocket)
{
lock (_webSocketsLock)
{
if (!_webSockets.Remove(webSocket))
{
_logger.LogWarning("WebSocket {0} not on watchlist.", webSocket);
}
else
{
webSocket.Closed -= OnWebSocketClosed;
}
}
}
/// <summary>
/// Starts the KeepAlive watcher.
/// </summary>
private void StartKeepAlive()
{
lock (_keepAliveLock)
{
if (_keepAliveCancellationToken == null)
{
_keepAliveCancellationToken = new CancellationTokenSource();
// Start KeepAlive watcher
_ = RepeatAsyncCallbackEvery(
KeepAliveSockets,
TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor),
_keepAliveCancellationToken.Token);
}
}
}
/// <summary>
/// Stops the KeepAlive watcher.
/// </summary>
private void StopKeepAlive()
{
lock (_keepAliveLock)
{
if (_keepAliveCancellationToken != null)
{
_keepAliveCancellationToken.Cancel();
_keepAliveCancellationToken = null;
}
}
lock (_webSocketsLock)
{
foreach (var webSocket in _webSockets)
{
webSocket.Closed -= OnWebSocketClosed;
}
_webSockets.Clear();
}
}
/// <summary>
/// Checks status of KeepAlive of WebSockets.
/// </summary>
private async Task KeepAliveSockets()
{
List<IWebSocketConnection> inactive;
List<IWebSocketConnection> lost;
lock (_webSocketsLock)
{
_logger.LogDebug("Watching {0} WebSockets.", _webSockets.Count);
inactive = _webSockets.Where(i =>
{
var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds;
return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout);
}).ToList();
lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout).ToList();
}
if (inactive.Any())
{
_logger.LogInformation("Sending ForceKeepAlive message to {0} inactive WebSockets.", inactive.Count);
}
foreach (var webSocket in inactive)
{
try
{
await SendForceKeepAlive(webSocket);
}
catch (WebSocketException exception)
{
_logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket.");
lost.Add(webSocket);
}
}
lock (_webSocketsLock)
{
if (lost.Any())
{
_logger.LogInformation("Lost {0} WebSockets.", lost.Count);
foreach (var webSocket in lost)
{
// TODO: handle session relative to the lost webSocket
RemoveWebSocket(webSocket);
}
}
if (!_webSockets.Any())
{
StopKeepAlive();
}
}
}
/// <summary>
/// Sends a ForceKeepAlive message to a WebSocket.
/// </summary>
/// <param name="webSocket">The WebSocket.</param>
/// <returns>Task.</returns>
private Task SendForceKeepAlive(IWebSocketConnection webSocket)
{
return webSocket.SendAsync(new WebSocketMessage<int>
{
MessageType = "ForceKeepAlive",
Data = WebSocketLostTimeout
}, CancellationToken.None);
}
/// <summary>
/// Runs a given async callback once every specified interval time, until cancelled.
/// </summary>
/// <param name="callback">The async callback.</param>
/// <param name="interval">The interval time.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task RepeatAsyncCallbackEvery(Func<Task> callback, TimeSpan interval, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await callback();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
}
}

View File

@ -1,18 +0,0 @@
using System.IO;
using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.SocketSharp
{
public class HttpFile : IHttpFile
{
public string Name { get; set; }
public string FileName { get; set; }
public long ContentLength { get; set; }
public string ContentType { get; set; }
public Stream InputStream { get; set; }
}
}

View File

@ -1,198 +0,0 @@
using System;
using System.IO;
public sealed class HttpPostedFile : IDisposable
{
private string _name;
private string _contentType;
private Stream _stream;
private bool _disposed = false;
internal HttpPostedFile(string name, string content_type, Stream base_stream, long offset, long length)
{
_name = name;
_contentType = content_type;
_stream = new ReadSubStream(base_stream, offset, length);
}
public string ContentType => _contentType;
public int ContentLength => (int)_stream.Length;
public string FileName => _name;
public Stream InputStream => _stream;
/// <summary>
/// Releases the unmanaged resources and disposes of the managed resources used.
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_stream.Dispose();
_stream = null;
_name = null;
_contentType = null;
_disposed = true;
}
private class ReadSubStream : Stream
{
private Stream _stream;
private long _offset;
private long _end;
private long _position;
public ReadSubStream(Stream s, long offset, long length)
{
_stream = s;
_offset = offset;
_end = offset + length;
_position = offset;
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => _end - _offset;
public override long Position
{
get => _position - _offset;
set
{
if (value > Length)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_position = Seek(value, SeekOrigin.Begin);
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int dest_offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (dest_offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(dest_offset), "< 0");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "< 0");
}
int len = buffer.Length;
if (dest_offset > len)
{
throw new ArgumentException("destination offset is beyond array size", nameof(dest_offset));
}
// reordered to avoid possible integer overflow
if (dest_offset > len - count)
{
throw new ArgumentException("Reading would overrun buffer", nameof(count));
}
if (count > _end - _position)
{
count = (int)(_end - _position);
}
if (count <= 0)
{
return 0;
}
_stream.Position = _position;
int result = _stream.Read(buffer, dest_offset, count);
if (result > 0)
{
_position += result;
}
else
{
_position = _end;
}
return result;
}
public override int ReadByte()
{
if (_position >= _end)
{
return -1;
}
_stream.Position = _position;
int result = _stream.ReadByte();
if (result < 0)
{
_position = _end;
}
else
{
_position++;
}
return result;
}
public override long Seek(long d, SeekOrigin origin)
{
long real;
switch (origin)
{
case SeekOrigin.Begin:
real = _offset + d;
break;
case SeekOrigin.End:
real = _end + d;
break;
case SeekOrigin.Current:
real = _position + d;
break;
default:
throw new ArgumentException("Unknown SeekOrigin value", nameof(origin));
}
long virt = real - _offset;
if (virt < 0 || virt > Length)
{
throw new ArgumentException("Invalid position", nameof(d));
}
_position = _stream.Seek(real, SeekOrigin.Begin);
return _position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.IO;
@ -209,7 +211,7 @@ namespace Emby.Server.Implementations.SocketSharp
private static string GetQueryStringContentType(HttpRequest httpReq)
{
ReadOnlySpan<char> format = httpReq.Query["format"].ToString();
if (format == null)
if (format == ReadOnlySpan<char>.Empty)
{
const int FormatMaxLength = 4;
ReadOnlySpan<char> pi = httpReq.Path.ToString();

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
@ -7,6 +9,12 @@ namespace Emby.Server.Implementations.Sorting
{
public class CommunityRatingComparer : IBaseItemComparer
{
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.CommunityRating;
/// <summary>
/// Compares the specified x.
/// </summary>
@ -16,18 +24,16 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y)
{
if (x == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null)
{
throw new ArgumentNullException(nameof(y));
}
return (x.CommunityRating ?? 0).CompareTo(y.CommunityRating ?? 0);
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.CommunityRating;
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@ -26,6 +28,12 @@ namespace Emby.Server.Implementations.Sorting
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.DateLastContentAdded;
/// <summary>
/// Compares the specified x.
/// </summary>
@ -44,9 +52,7 @@ namespace Emby.Server.Implementations.Sorting
/// <returns>DateTime.</returns>
private static DateTime GetDate(BaseItem x)
{
var folder = x as Folder;
if (folder != null)
if (x is Folder folder)
{
if (folder.DateLastMediaAdded.HasValue)
{
@ -56,11 +62,5 @@ namespace Emby.Server.Implementations.Sorting
return DateTime.MinValue;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.DateLastContentAdded;
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@ -13,6 +15,24 @@ namespace Emby.Server.Implementations.Sorting
/// <value>The user.</value>
public User User { get; set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsFavoriteOrLiked;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
/// <summary>
/// Compares the specified x.
/// </summary>
@ -33,23 +53,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsFavoriteOrLiked(User) ? 0 : 1;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsFavoriteOrLiked;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Querying;
@ -6,6 +8,12 @@ namespace Emby.Server.Implementations.Sorting
{
public class IsFolderComparer : IBaseItemComparer
{
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsFolder;
/// <summary>
/// Compares the specified x.
/// </summary>
@ -26,11 +34,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsFolder ? 0 : 1;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsFolder;
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@ -13,6 +15,24 @@ namespace Emby.Server.Implementations.Sorting
/// <value>The user.</value>
public User User { get; set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsUnplayed;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
/// <summary>
/// Compares the specified x.
/// </summary>
@ -33,23 +53,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsPlayed(User) ? 0 : 1;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsUnplayed;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
}
}

View File

@ -1,3 +1,5 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Sorting;
@ -13,6 +15,24 @@ namespace Emby.Server.Implementations.Sorting
/// <value>The user.</value>
public User User { get; set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsUnplayed;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
/// <summary>
/// Compares the specified x.
/// </summary>
@ -33,23 +53,5 @@ namespace Emby.Server.Implementations.Sorting
{
return x.IsUnplayed(User) ? 0 : 1;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.IsUnplayed;
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
public IUserDataManager UserDataRepository { get; set; }
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
public IUserManager UserManager { get; set; }
}
}

Some files were not shown because too many files have changed in this diff Show More