From 5cab79c839d2212ae638db403ec4d7ba0699f9a1 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 4 Dec 2019 21:39:27 +0100 Subject: [PATCH 001/108] Clean up Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs --- .../Library/MediaSourceManager.cs | 4 +- .../LiveTv/EmbyTV/DirectRecorder.cs | 3 +- .../LiveTv/EmbyTV/EmbyTV.cs | 504 ++++++++---------- .../LiveTv/EmbyTV/EpgChannelData.cs | 68 +++ .../EmbyTV/NfoConfigurationExtensions.cs | 19 + .../LiveTv/LiveTvManager.cs | 5 +- .../Playback/BaseStreamingService.cs | 2 +- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- .../Library/IMediaSourceManager.cs | 4 +- .../Subtitles/SubtitleEncoder.cs | 2 +- jellyfin.ruleset | 4 +- 11 files changed, 319 insertions(+), 298 deletions(-) create mode 100644 Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs create mode 100644 Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 7a26e0c37d..059b27e877 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -128,7 +128,7 @@ namespace Emby.Server.Implementations.Library return streams; } - public async Task> GetPlayackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken) + public async Task> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken) { var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user); @@ -290,7 +290,7 @@ namespace Emby.Server.Implementations.Library return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false); } - var sources = await GetPlayackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).ConfigureAwait(false); + var sources = await GetPlaybackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).ConfigureAwait(false); return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 8dee7046e7..84e8c31f95 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; @@ -74,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV DecompressionMethod = CompressionMethod.None }; - using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(httpRequestOptions, HttpMethod.Get).ConfigureAwait(false)) { _logger.LogInformation("Opened recording stream from tuner provider"); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index ef5928e480..420209edaf 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1,3 +1,6 @@ +#pragma warning disable SA1600 +#pragma warning disable CS1591 + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -40,6 +43,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { public class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable { + public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss"; + + private const int TunerDiscoveryDurationMs = 3000; + private readonly IServerApplicationHost _appHost; private readonly ILogger _logger; private readonly IHttpClient _httpClient; @@ -57,19 +64,21 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly IProviderManager _providerManager; private readonly IMediaEncoder _mediaEncoder; private readonly IProcessFactory _processFactory; - private IMediaSourceManager _mediaSourceManager; - - public static EmbyTV Current; - - public event EventHandler> TimerCreated; - public event EventHandler> TimerCancelled; + private readonly IMediaSourceManager _mediaSourceManager; + private readonly IStreamHelper _streamHelper; private readonly ConcurrentDictionary _activeRecordings = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - private readonly IStreamHelper _streamHelper; + private readonly ConcurrentDictionary _epgChannels = + new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1); - public EmbyTV(IServerApplicationHost appHost, + private bool _disposed = false; + + public EmbyTV( + IServerApplicationHost appHost, IStreamHelper streamHelper, IMediaSourceManager mediaSourceManager, ILogger logger, @@ -103,12 +112,40 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json")); _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json")); - _timerProvider.TimerFired += _timerProvider_TimerFired; + _timerProvider.TimerFired += OnTimerProviderTimerFired; - _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated; + _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated; } - private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) + public event EventHandler> TimerCreated; + + public event EventHandler> TimerCancelled; + + public static EmbyTV Current { get; private set; } + + /// + public string Name => "Emby"; + + public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); + + /// + public string HomePageUrl => "https://github.com/jellyfin/jellyfin"; + + private string DefaultRecordingPath => Path.Combine(DataPath, "recordings"); + + private string RecordingPath + { + get + { + var path = GetConfiguration().RecordingPath; + + return string.IsNullOrWhiteSpace(path) + ? DefaultRecordingPath + : path; + } + } + + private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) { if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase)) { @@ -116,11 +153,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - public async Task Start() + public Task Start() { _timerProvider.RestartTimers(); - await CreateRecordingFolders().ConfigureAwait(false); + return CreateRecordingFolders(); } private async void OnRecordingFoldersChanged() @@ -132,8 +169,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - var recordingFolders = GetRecordingFolders(); - + var recordingFolders = GetRecordingFolders().ToArray(); var virtualFolders = _libraryManager.GetVirtualFolders() .ToList(); @@ -241,26 +277,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - public string Name => "Emby"; - - public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); - - private string DefaultRecordingPath => Path.Combine(DataPath, "recordings"); - - private string RecordingPath - { - get - { - var path = GetConfiguration().RecordingPath; - - return string.IsNullOrWhiteSpace(path) - ? DefaultRecordingPath - : path; - } - } - - public string HomePageUrl => "https://github.com/jellyfin/jellyfin"; - public async Task RefreshSeriesTimers(CancellationToken cancellationToken) { var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false); @@ -339,7 +355,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (NotSupportedException) { - } catch (Exception ex) { @@ -351,7 +366,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return list; } - private async Task AddMetadata(IListingsProvider provider, ListingsProviderInfo info, List tunerChannels, bool enableCache, CancellationToken cancellationToken) + private async Task AddMetadata( + IListingsProvider provider, + ListingsProviderInfo info, + IEnumerable tunerChannels, + bool enableCache, + CancellationToken cancellationToken) { var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false); @@ -363,8 +383,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!string.IsNullOrWhiteSpace(epgChannel.Name)) { - //tunerChannel.Name = epgChannel.Name; + // tunerChannel.Name = epgChannel.Name; } + if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl)) { tunerChannel.ImageUrl = epgChannel.ImageUrl; @@ -373,10 +394,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - private readonly ConcurrentDictionary _epgChannels = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - private async Task GetEpgChannels(IListingsProvider provider, ListingsProviderInfo info, bool enableCache, CancellationToken cancellationToken) + private async Task GetEpgChannels( + IListingsProvider provider, + ListingsProviderInfo info, + bool enableCache, + CancellationToken cancellationToken) { if (!enableCache || !_epgChannels.TryGetValue(info.Id, out var result)) { @@ -394,59 +416,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return result; } - private class EpgChannelData - { - public EpgChannelData(List channels) - { - ChannelsById = new Dictionary(StringComparer.OrdinalIgnoreCase); - ChannelsByNumber = new Dictionary(StringComparer.OrdinalIgnoreCase); - ChannelsByName = new Dictionary(StringComparer.OrdinalIgnoreCase); - - foreach (var channel in channels) - { - ChannelsById[channel.Id] = channel; - - if (!string.IsNullOrEmpty(channel.Number)) - { - ChannelsByNumber[channel.Number] = channel; - } - - var normalizedName = NormalizeName(channel.Name ?? string.Empty); - if (!string.IsNullOrWhiteSpace(normalizedName)) - { - ChannelsByName[normalizedName] = channel; - } - } - } - - private Dictionary ChannelsById { get; set; } - private Dictionary ChannelsByNumber { get; set; } - private Dictionary ChannelsByName { get; set; } - - public ChannelInfo GetChannelById(string id) - { - ChannelInfo result = null; - - ChannelsById.TryGetValue(id, out result); - - return result; - } - - public ChannelInfo GetChannelByNumber(string number) - { - ChannelsByNumber.TryGetValue(number, out var result); - - return result; - } - - public ChannelInfo GetChannelByName(string name) - { - ChannelsByName.TryGetValue(name, out var result); - - return result; - } - } - private async Task GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken) { var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false); @@ -463,6 +432,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return mapping.Value; } } + return channelId; } @@ -476,7 +446,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return GetEpgChannelFromTunerChannel(info.ChannelMappings, tunerChannel, epgChannels); } - private ChannelInfo GetEpgChannelFromTunerChannel(NameValuePair[] mappings, ChannelInfo tunerChannel, EpgChannelData epgChannelData) + private ChannelInfo GetEpgChannelFromTunerChannel( + NameValuePair[] mappings, + ChannelInfo tunerChannel, + EpgChannelData epgChannelData) { if (!string.IsNullOrWhiteSpace(tunerChannel.Id)) { @@ -537,7 +510,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (!string.IsNullOrWhiteSpace(tunerChannel.Name)) { - var normalizedName = NormalizeName(tunerChannel.Name); + var normalizedName = EpgChannelData.NormalizeName(tunerChannel.Name); var channel = epgChannelData.GetChannelByName(normalizedName); @@ -550,11 +523,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return null; } - private static string NormalizeName(string value) - { - return value.Replace(" ", string.Empty).Replace("-", string.Empty); - } - public async Task> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken) { var list = new List(); @@ -600,6 +568,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _seriesTimerProvider.Delete(remove); } + return Task.CompletedTask; } @@ -689,6 +658,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { programInfo = GetProgramInfoFromCache(timer); } + if (programInfo == null) { _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); @@ -703,10 +673,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV timer.IsManual = true; _timerProvider.Add(timer); - if (TimerCreated != null) - { - TimerCreated(this, new GenericEventArgs(timer)); - } + TimerCreated?.Invoke(this, new GenericEventArgs(timer)); return Task.FromResult(timer.Id); } @@ -800,7 +767,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } // Only update if not currently active - if (!_activeRecordings.TryGetValue(updatedTimer.Id, out var activeRecordingInfo)) + if (!_activeRecordings.TryGetValue(updatedTimer.Id, out _)) { existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds; existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds; @@ -846,6 +813,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { return info.Path; } + return null; } @@ -870,9 +838,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { return null; } + return recording; } } + return null; } @@ -1061,13 +1031,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV mediaSource.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture) + "_" + mediaSource.Id; - //if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing) - //{ - // var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks; - // ticks = Math.Max(0, ticks); - // mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture); - //} - return mediaSource; } @@ -1091,7 +1054,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (NotImplementedException) { - } } @@ -1142,7 +1104,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return Task.CompletedTask; } - async void _timerProvider_TimerFired(object sender, GenericEventArgs e) + private async void OnTimerProviderTimerFired(object sender, GenericEventArgs e) { var timer = e.Argument; @@ -1177,7 +1139,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (OperationCanceledException) { - } catch (Exception ex) { @@ -1221,7 +1182,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (timer.SeasonNumber.HasValue) { - folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); + folderName = string.Format( + CultureInfo.InvariantCulture, + "Season {0}", + timer.SeasonNumber.Value); recordPath = Path.Combine(recordPath, folderName); } } @@ -1275,6 +1239,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { recordPath = Path.Combine(recordPath, "Sports"); } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim()); } else @@ -1283,6 +1248,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { recordPath = Path.Combine(recordPath, "Other"); } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim()); } @@ -1304,6 +1270,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { programInfo = GetProgramInfoFromCache(timer); } + if (programInfo == null) { _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); @@ -1315,9 +1282,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV CopyProgramInfoToTimerInfo(programInfo, timer); } - string seriesPath = null; var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false); - var recordPath = GetRecordingPath(timer, remoteMetadata, out seriesPath); + var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath); var recordingStatus = RecordingStatus.New; string liveStreamId = null; @@ -1326,19 +1292,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var allMediaSources = await _mediaSourceManager.GetPlayackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false); + var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false); var mediaStreamInfo = allMediaSources[0]; IDirectStreamProvider directStreamProvider = null; if (mediaStreamInfo.RequiresOpening) { - var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal(new LiveStreamRequest - { - ItemId = channelItem.Id, - OpenToken = mediaStreamInfo.OpenToken - - }, CancellationToken.None).ConfigureAwait(false); + var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal( + new LiveStreamRequest + { + ItemId = channelItem.Id, + OpenToken = mediaStreamInfo.OpenToken + }, + CancellationToken.None).ConfigureAwait(false); mediaStreamInfo = liveStreamResponse.Item1.MediaSource; liveStreamId = mediaStreamInfo.LiveStreamId; @@ -1412,12 +1379,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) { - const int retryIntervalSeconds = 60; - _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds); + const int RetryIntervalSeconds = 60; + _logger.LogInformation("Retrying recording in {0} seconds.", RetryIntervalSeconds); timer.Status = RecordingStatus.New; timer.PrePaddingSeconds = 0; - timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds); + timer.StartDate = DateTime.UtcNow.AddSeconds(RetryIntervalSeconds); timer.RetryCount++; _timerProvider.AddOrUpdate(timer); } @@ -1538,6 +1505,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { return; } + if (string.IsNullOrWhiteSpace(seriesPath)) { return; @@ -1576,34 +1544,34 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV DeleteLibraryItemsForTimers(timersToDelete); var librarySeries = _libraryManager.FindByPath(seriesPath, true) as Folder; - if (librarySeries == null) { return; } - var episodesToDelete = (librarySeries.GetItemList(new InternalItemsQuery - { - OrderBy = new[] { new ValueTuple(ItemSortBy.DateCreated, SortOrder.Descending) }, - IsVirtualItem = false, - IsFolder = false, - Recursive = true, - DtoOptions = new DtoOptions(true) - - })) - .Where(i => i.IsFileProtocol && File.Exists(i.Path)) - .Skip(seriesTimer.KeepUpTo - 1) - .ToList(); + var episodesToDelete = librarySeries.GetItemList( + new InternalItemsQuery + { + OrderBy = new[] { new ValueTuple(ItemSortBy.DateCreated, SortOrder.Descending) }, + IsVirtualItem = false, + IsFolder = false, + Recursive = true, + DtoOptions = new DtoOptions(true) + }).Where(i => i.IsFileProtocol && File.Exists(i.Path)) + .Skip(seriesTimer.KeepUpTo - 1) + .ToList(); foreach (var item in episodesToDelete) { try { - _libraryManager.DeleteItem(item, new DeleteOptions - { - DeleteFileLocation = true - - }, true); + _libraryManager.DeleteItem( + item, + new DeleteOptions + { + DeleteFileLocation = true + }, + true); } catch (Exception ex) { @@ -1617,7 +1585,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1); private void DeleteLibraryItemsForTimers(List timers) { foreach (var timer in timers) @@ -1644,22 +1611,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (libraryItem != null) { - _libraryManager.DeleteItem(libraryItem, new DeleteOptions - { - DeleteFileLocation = true - - }, true); + _libraryManager.DeleteItem( + libraryItem, + new DeleteOptions + { + DeleteFileLocation = true + }, + true); } else { - try + if (File.Exists(timer.RecordingPath)) { _fileSystem.DeleteFile(timer.RecordingPath); } - catch (IOException) - { - - } } _timerProvider.Delete(timer); @@ -1690,16 +1655,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return true; } - var hasRecordingAtPath = _activeRecordings + return _activeRecordings .Values .ToList() .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase)); - - if (hasRecordingAtPath) - { - return true; - } - return false; } private IRecorder GetRecorder(MediaSourceInfo mediaSource) @@ -1756,17 +1715,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void Process_Exited(object sender, EventArgs e) { - var process = (IProcess)sender; - try + using (var process = (IProcess)sender) { _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); - } - catch - { + process.Dispose(); } - - process.Dispose(); } private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image) @@ -1776,44 +1730,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false); } - string imageSaveFilenameWithoutExtension = null; - - switch (image.Type) + string imageSaveFilenameWithoutExtension = image.Type switch { - case ImageType.Primary: - - if (program.IsSeries) - { - imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb"; - } - else - { - imageSaveFilenameWithoutExtension = "poster"; - } - - break; - case ImageType.Logo: - imageSaveFilenameWithoutExtension = "logo"; - break; - case ImageType.Thumb: - if (program.IsSeries) - { - imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb"; - } - else - { - imageSaveFilenameWithoutExtension = "landscape"; - } - - break; - case ImageType.Backdrop: - imageSaveFilenameWithoutExtension = "fanart"; - break; - default: - break; - } + ImageType.Primary => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "poster", + ImageType.Logo => "logo", + ImageType.Thumb => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "landscape", + ImageType.Backdrop => "fanart", + _ => null + }; - if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension)) + if (imageSaveFilenameWithoutExtension == null) { return; } @@ -1897,7 +1823,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Limit = 1, ExternalId = timer.ProgramId, DtoOptions = new DtoOptions(true) - }).FirstOrDefault() as LiveTvProgram; // dummy this up @@ -1921,11 +1846,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { program.AddGenre("Sports"); } + if (timer.IsKids) { program.AddGenre("Kids"); program.AddGenre("Children"); } + if (timer.IsNews) { program.AddGenre("News"); @@ -1980,14 +1907,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { writer.WriteElementString("id", id); } + if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out id)) { writer.WriteElementString("imdb_id", id); } + if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Tmdb.ToString(), out id)) { writer.WriteElementString("tmdbid", id); } + if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out id)) { writer.WriteElementString("zap2itid", id); @@ -2014,7 +1944,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss"; private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData) { var nfoPath = Path.ChangeExtension(recordingPath, ".nfo"); @@ -2056,7 +1985,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var formatString = options.ReleaseDateFormat; - writer.WriteElementString("aired", premiereDate.Value.ToLocalTime().ToString(formatString)); + writer.WriteElementString( + "aired", + premiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)); } if (item.IndexNumber.HasValue) @@ -2087,12 +2018,18 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var formatString = options.ReleaseDateFormat; - writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString)); - writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString)); + writer.WriteElementString( + "premiered", + item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)); + writer.WriteElementString( + "releasedate", + item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)); } } - writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat)); + writer.WriteElementString( + "dateadded", + DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat, CultureInfo.InvariantCulture)); if (item.ProductionYear.HasValue) { @@ -2106,7 +2043,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var overview = (item.Overview ?? string.Empty) .StripHtml() - .Replace(""", "'"); + .Replace(""", "'", StringComparison.Ordinal); writer.WriteElementString("plot", overview); @@ -2214,17 +2151,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } private static bool IsPersonType(PersonInfo person, string type) - { - return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase); - } - - private void AddGenre(List genres, string genre) - { - if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase)) - { - genres.Add(genre); - } - } + => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) + || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase); private LiveTvProgram GetProgramInfoFromCache(string programId) { @@ -2283,25 +2211,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return false; } - if (!seriesTimer.RecordAnyTime) + if (!seriesTimer.RecordAnyTime + && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks) { - if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks) - { - return true; - } + return true; } - //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek)) - //{ - // return true; - //} - if (seriesTimer.RecordNewOnly && timer.IsRepeat) { return true; } - if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase)) + if (!seriesTimer.RecordAnyChannel + && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -2346,7 +2268,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var allTimers = GetTimersForSeries(seriesTimer).ToList(); - var enabledTimersForSeries = new List(); foreach (var timer in allTimers) { @@ -2369,10 +2290,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { enabledTimersForSeries.Add(timer); } + _timerProvider.Add(timer); TimerCreated?.Invoke(this, new GenericEventArgs(timer)); } + // Only update if not currently active - test both new timer and existing in case Id's are different // Id's could be different if the timer was created manually prior to series timer creation else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _)) @@ -2508,13 +2431,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel)) { - channel = _libraryManager.GetItemList(new InternalItemsQuery - { - IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name }, - ItemIds = new[] { parent.ChannelId }, - DtoOptions = new DtoOptions() - - }).Cast().FirstOrDefault(); + channel = _libraryManager.GetItemList( + new InternalItemsQuery + { + IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name }, + ItemIds = new[] { parent.ChannelId }, + DtoOptions = new DtoOptions() + }).FirstOrDefault() as LiveTvChannel; if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId)) { @@ -2567,13 +2490,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel)) { - channel = _libraryManager.GetItemList(new InternalItemsQuery - { - IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name }, - ItemIds = new[] { programInfo.ChannelId }, - DtoOptions = new DtoOptions() - - }).Cast().FirstOrDefault(); + channel = _libraryManager.GetItemList( + new InternalItemsQuery + { + IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name }, + ItemIds = new[] { programInfo.ChannelId }, + DtoOptions = new DtoOptions() + }).FirstOrDefault() as LiveTvChannel; if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId)) { @@ -2618,10 +2541,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var providerId in timerInfo.ProviderIds) { - var srch = "Series"; - if (providerId.Key.StartsWith(srch, StringComparison.OrdinalIgnoreCase)) + const string Search = "Series"; + if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase)) { - seriesProviderIds[providerId.Key.Substring(srch.Length)] = providerId.Value; + seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value; } } @@ -2632,12 +2555,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle)) { - var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery - { - IncludeItemTypes = new[] { typeof(Series).Name }, - Name = program.Name - - }).ToArray(); + var seriesIds = _libraryManager.GetItemIds( + new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Series).Name }, + Name = program.Name + }).ToArray(); if (seriesIds.Length == 0) { @@ -2666,59 +2589,70 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return false; } - private bool _disposed; + /// public void Dispose() { - _disposed = true; + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (_disposed) + { + return; + } + + if (disposing) + { + _recordingDeleteSemaphore.Dispose(); + } + foreach (var pair in _activeRecordings.ToList()) { pair.Value.CancellationTokenSource.Cancel(); } + + _disposed = true; } - public List GetRecordingFolders() + public IEnumerable GetRecordingFolders() { - var list = new List(); - var defaultFolder = RecordingPath; var defaultName = "Recordings"; if (Directory.Exists(defaultFolder)) { - list.Add(new VirtualFolderInfo + yield return new VirtualFolderInfo { Locations = new string[] { defaultFolder }, Name = defaultName - }); + }; } var customPath = GetConfiguration().MovieRecordingPath; - if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath)) { - list.Add(new VirtualFolderInfo + yield return new VirtualFolderInfo { Locations = new string[] { customPath }, Name = "Recorded Movies", CollectionType = CollectionType.Movies - }); + }; } customPath = GetConfiguration().SeriesRecordingPath; - if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath)) { - list.Add(new VirtualFolderInfo + yield return new VirtualFolderInfo { Locations = new string[] { customPath }, Name = "Recorded Shows", CollectionType = CollectionType.TvShows - }); + }; } - - return list; } - private const int TunerDiscoveryDurationMs = 3000; - public async Task> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken) { var list = new List(); @@ -2737,6 +2671,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparer.OrdinalIgnoreCase)) .ToList(); } + list.AddRange(discoveredDevices); } @@ -2773,11 +2708,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - private async Task> DiscoverDevices(ITunerHost host, int discoveryDuationMs, CancellationToken cancellationToken) + private async Task> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken) { try { - var discoveredDevices = await host.DiscoverDevices(discoveryDuationMs, cancellationToken).ConfigureAwait(false); + var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false); foreach (var device in discoveredDevices) { @@ -2794,11 +2729,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } } - public static class ConfigurationExtension - { - public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager) - { - return manager.GetConfiguration("xbmcmetadata"); - } - } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs new file mode 100644 index 0000000000..498aa3c266 --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs @@ -0,0 +1,68 @@ +#pragma warning disable SA1600 +#pragma warning disable CS1591 + +using System; +using System.Collections.Generic; +using MediaBrowser.Controller.LiveTv; + +namespace Emby.Server.Implementations.LiveTv.EmbyTV +{ + + internal class EpgChannelData + { + public EpgChannelData(IEnumerable channels) + { + ChannelsById = new Dictionary(StringComparer.OrdinalIgnoreCase); + ChannelsByNumber = new Dictionary(StringComparer.OrdinalIgnoreCase); + ChannelsByName = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var channel in channels) + { + ChannelsById[channel.Id] = channel; + + if (!string.IsNullOrEmpty(channel.Number)) + { + ChannelsByNumber[channel.Number] = channel; + } + + var normalizedName = NormalizeName(channel.Name ?? string.Empty); + if (!string.IsNullOrWhiteSpace(normalizedName)) + { + ChannelsByName[normalizedName] = channel; + } + } + } + + private Dictionary ChannelsById { get; set; } + + private Dictionary ChannelsByNumber { get; set; } + + private Dictionary ChannelsByName { get; set; } + + public ChannelInfo GetChannelById(string id) + { + ChannelsById.TryGetValue(id, out var result); + + return result; + } + + public ChannelInfo GetChannelByNumber(string number) + { + ChannelsByNumber.TryGetValue(number, out var result); + + return result; + } + + public ChannelInfo GetChannelByName(string name) + { + ChannelsByName.TryGetValue(name, out var result); + + return result; + } + + public static string NormalizeName(string value) + { + return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal); + } + } +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs new file mode 100644 index 0000000000..83f5e84131 --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/NfoConfigurationExtensions.cs @@ -0,0 +1,19 @@ +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Configuration; + +namespace Emby.Server.Implementations.LiveTv.EmbyTV +{ + /// + /// Class containing extension methods for working with the nfo configuration. + /// + public static class NfoConfigurationExtensions + { + /// + /// Gets the nfo configuration. + /// + /// The configuration manager. + /// The nfo configuration. + public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager configurationManager) + => configurationManager.GetConfiguration("xbmcmetadata"); + } +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index d4bd598e38..d1f405679d 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable SA1600 +#pragma warning disable CS1591 + using System; using System.Collections.Generic; using System.Globalization; @@ -35,7 +38,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv { /// - /// Class LiveTvManager + /// Class LiveTvManager. /// public class LiveTvManager : ILiveTvManager, IDisposable { diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 4bd729aac8..d6f5bb0c02 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -768,7 +768,7 @@ namespace MediaBrowser.Api.Playback if (mediaSource == null) { - var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(LibraryManager.GetItemById(request.Id), null, false, false, cancellationToken).ConfigureAwait(false)).ToList(); + var mediaSources = (await MediaSourceManager.GetPlaybackMediaSources(LibraryManager.GetItemById(request.Id), null, false, false, cancellationToken).ConfigureAwait(false)).ToList(); mediaSource = string.IsNullOrEmpty(request.MediaSourceId) ? mediaSources[0] diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index da8f99a3dd..ee440f5dbe 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -270,7 +270,7 @@ namespace MediaBrowser.Api.Playback try { // TODO handle supportedLiveMediaTypes ? - mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); + mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs index fbae4edb09..1bf981d79c 100644 --- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs +++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs @@ -39,9 +39,9 @@ namespace MediaBrowser.Controller.Library List GetMediaStreams(MediaStreamQuery query); /// - /// Gets the playack media sources. + /// Gets the playback media sources. /// - Task> GetPlayackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken); + Task> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken); /// /// Gets the static media sources. diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index d5fa76c3ab..67c7fa343a 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -126,7 +126,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw new ArgumentNullException(nameof(mediaSourceId)); } - var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false); + var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false); var mediaSource = mediaSources .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)); diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 75b5573b67..d3d3001ed4 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -31,7 +31,9 @@ - + + + From 35151553e3fc9ddbe352744af8d832b1337491c8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 6 Dec 2019 20:40:06 +0100 Subject: [PATCH 002/108] Add back all old emby tests --- Emby.Naming/Common/NamingOptions.cs | 41 +- Emby.Naming/Video/CleanStringParser.cs | 2 +- Emby.Naming/Video/ExtraResolver.cs | 2 +- Emby.Naming/Video/ExtraResult.cs | 5 +- Emby.Naming/Video/ExtraRule.cs | 5 +- Emby.Naming/Video/StubResolver.cs | 4 +- Emby.Naming/Video/VideoFileInfo.cs | 6 +- Emby.Naming/Video/VideoListResolver.cs | 9 +- Emby.Naming/Video/VideoResolver.cs | 2 +- .../Library/LibraryManager.cs | 31 +- MediaBrowser.Model/Entities/MediaType.cs | 5 +- jellyfin.ruleset | 2 + .../Music/MultiDiscAlbumTests.cs | 57 +++ .../Subtitles/SubtitleParserTests.cs | 40 ++ .../TV/AbsoluteEpisodeNumberTests.cs | 61 +++ .../TV/DailyEpisodeTests.cs | 69 +++ .../TV/EpisodeNumberTests.cs | 421 +++++++++++++++ .../TV/EpisodeNumberWithoutSeasonTests.cs | 127 +++++ .../{ => TV}/EpisodePathParserTest.cs | 6 +- .../TV/EpisodeWithoutSeasonTests.cs | 56 ++ .../TV/MultiEpisodeTests.cs | 105 ++++ .../TV/SeasonFolderTests.cs | 112 ++++ .../TV/SeasonNumberTests.cs | 305 +++++++++++ .../TV/SimpleEpisodeTests.cs | 95 ++++ .../Video/BaseVideoTest.cs | 15 + .../Video/CleanDateTimeTests.cs | 143 ++++++ .../Video/CleanStringTests.cs | 133 +++++ .../Jellyfin.Naming.Tests/Video/ExtraTests.cs | 77 +++ .../Video/Format3DTests.cs | 78 +++ .../Video/MultiVersionTests.cs | 438 ++++++++++++++++ .../Jellyfin.Naming.Tests/Video/StackTests.cs | 478 ++++++++++++++++++ .../Jellyfin.Naming.Tests/Video/StubTests.cs | 55 ++ .../Video/VideoListResolverTests.cs | 457 +++++++++++++++++ .../Video/VideoResolverTests.cs | 275 ++++++++++ 34 files changed, 3653 insertions(+), 64 deletions(-) create mode 100644 tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs rename tests/Jellyfin.Naming.Tests/{ => TV}/EpisodePathParserTest.cs (91%) create mode 100644 tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/StackTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/StubTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs create mode 100644 tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index d37be0e639..f8601c59fd 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -2,6 +2,7 @@ using System; using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Video; +using MediaBrowser.Model.Entities; namespace Emby.Naming.Common { @@ -173,7 +174,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { - @"(.+[^ _\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9][0-9]|20[0-1][0-9])([ _\,\.\(\)\[\]\-][^0-9]|$)" + @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9][0-9]|20[0-1][0-9])([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9][0-9]|20[0-1][0-9])*" }; CleanStrings = new[] @@ -336,7 +337,7 @@ namespace Emby.Naming.Common // *** End Kodi Standard Naming -                // [bar] Foo - 1 [baz] +                // [bar] Foo - 1 [baz] new EpisodeExpression(@".*?(\[.*?\])+.*?(?(\w+\s*?)+?)[-\s_]+(?\d+).*$") { IsNamed = true @@ -420,126 +421,126 @@ namespace Emby.Naming.Common { new ExtraRule { - ExtraType = "trailer", + ExtraType = ExtraType.Trailer, RuleType = ExtraRuleType.Filename, Token = "trailer", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "trailer", + ExtraType = ExtraType.Trailer, RuleType = ExtraRuleType.Suffix, Token = "-trailer", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "trailer", + ExtraType = ExtraType.Trailer, RuleType = ExtraRuleType.Suffix, Token = ".trailer", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "trailer", + ExtraType = ExtraType.Trailer, RuleType = ExtraRuleType.Suffix, Token = "_trailer", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "trailer", + ExtraType = ExtraType.Trailer, RuleType = ExtraRuleType.Suffix, Token = " trailer", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "sample", + ExtraType = ExtraType.Sample, RuleType = ExtraRuleType.Filename, Token = "sample", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "sample", + ExtraType = ExtraType.Sample, RuleType = ExtraRuleType.Suffix, Token = "-sample", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "sample", + ExtraType = ExtraType.Sample, RuleType = ExtraRuleType.Suffix, Token = ".sample", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "sample", + ExtraType = ExtraType.Sample, RuleType = ExtraRuleType.Suffix, Token = "_sample", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "sample", + ExtraType = ExtraType.Sample, RuleType = ExtraRuleType.Suffix, Token = " sample", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "themesong", + ExtraType = ExtraType.ThemeSong, RuleType = ExtraRuleType.Filename, Token = "theme", MediaType = MediaType.Audio }, new ExtraRule { - ExtraType = "scene", + ExtraType = ExtraType.Scene, RuleType = ExtraRuleType.Suffix, Token = "-scene", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "clip", + ExtraType = ExtraType.Clip, RuleType = ExtraRuleType.Suffix, Token = "-clip", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "interview", + ExtraType = ExtraType.Interview, RuleType = ExtraRuleType.Suffix, Token = "-interview", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "behindthescenes", + ExtraType = ExtraType.BehindTheScenes, RuleType = ExtraRuleType.Suffix, Token = "-behindthescenes", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "deletedscene", + ExtraType = ExtraType.DeletedScene, RuleType = ExtraRuleType.Suffix, Token = "-deleted", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "featurette", + ExtraType = ExtraType.Clip, RuleType = ExtraRuleType.Suffix, Token = "-featurette", MediaType = MediaType.Video }, new ExtraRule { - ExtraType = "short", + ExtraType = ExtraType.Clip, RuleType = ExtraRuleType.Suffix, Token = "-short", MediaType = MediaType.Video diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index 02b90310d7..e2da121dbb 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -4,7 +4,7 @@ using System.Text.RegularExpressions; namespace Emby.Naming.Video { /// - /// http://kodi.wiki/view/Advancedsettings.xml#video + /// . /// public class CleanStringParser { diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index 9f70494d01..f83da44a43 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -20,7 +20,7 @@ namespace Emby.Naming.Video { return _options.VideoExtraRules .Select(i => GetExtraInfo(path, i)) - .FirstOrDefault(i => !string.IsNullOrEmpty(i.ExtraType)) ?? new ExtraResult(); + .FirstOrDefault(i => i.ExtraType != null) ?? new ExtraResult(); } private ExtraResult GetExtraInfo(string path, ExtraRule rule) diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs index ff6f20c47f..60d6b80ec5 100644 --- a/Emby.Naming/Video/ExtraResult.cs +++ b/Emby.Naming/Video/ExtraResult.cs @@ -1,3 +1,5 @@ +using MediaBrowser.Model.Entities; + namespace Emby.Naming.Video { public class ExtraResult @@ -6,7 +8,8 @@ namespace Emby.Naming.Video /// Gets or sets the type of the extra. /// /// The type of the extra. - public string ExtraType { get; set; } + public ExtraType? ExtraType { get; set; } + /// /// Gets or sets the rule. /// diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs index b8eb8427e7..62ec701638 100644 --- a/Emby.Naming/Video/ExtraRule.cs +++ b/Emby.Naming/Video/ExtraRule.cs @@ -9,16 +9,19 @@ namespace Emby.Naming.Video /// /// The token. public string Token { get; set; } + /// /// Gets or sets the type of the extra. /// /// The type of the extra. - public string ExtraType { get; set; } + public MediaBrowser.Model.Entities.ExtraType ExtraType { get; set; } + /// /// Gets or sets the type of the rule. /// /// The type of the rule. public ExtraRuleType RuleType { get; set; } + /// /// Gets or sets the type of the media. /// diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index b78244cb33..97f3178e5c 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -11,14 +11,14 @@ namespace Emby.Naming.Video { if (path == null) { - return default(StubResult); + return default; } var extension = Path.GetExtension(path); if (!options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - return default(StubResult); + return default; } var result = new StubResult() diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 2f42f77845..8416821c2a 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,3 +1,5 @@ +using MediaBrowser.Model.Entities; + namespace Emby.Naming.Video { /// @@ -30,10 +32,10 @@ namespace Emby.Naming.Video public int? Year { get; set; } /// - /// Gets or sets the type of the extra, e.g. trailer, theme song, behing the scenes, etc. + /// Gets or sets the type of the extra, e.g. trailer, theme song, behind the scenes, etc. /// /// The type of the extra. - public string ExtraType { get; set; } + public ExtraType? ExtraType { get; set; } /// /// Gets or sets the extra rule. diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 5fa0041e07..e43e920c4c 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Common; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; namespace Emby.Naming.Video @@ -29,7 +30,7 @@ namespace Emby.Naming.Video // Filter out all extras, otherwise they could cause stacks to not be resolved // See the unit test TestStackedWithTrailer var nonExtras = videoInfos - .Where(i => string.IsNullOrEmpty(i.ExtraType)) + .Where(i => i.ExtraType == null) .Select(i => new FileSystemMetadata { FullName = i.Path, @@ -76,7 +77,7 @@ namespace Emby.Naming.Video } var standaloneMedia = remainingFiles - .Where(i => string.IsNullOrEmpty(i.ExtraType)) + .Where(i => i.ExtraType == null) .ToList(); foreach (var media in standaloneMedia) @@ -145,7 +146,7 @@ namespace Emby.Naming.Video if (list.Count == 1) { var trailers = remainingFiles - .Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)) + .Where(i => i.ExtraType == ExtraType.Trailer) .ToList(); list[0].Extras.AddRange(trailers); @@ -226,7 +227,7 @@ namespace Emby.Naming.Video } return remainingFiles - .Where(i => !string.IsNullOrEmpty(i.ExtraType)) + .Where(i => i.ExtraType == null) .Where(i => baseNames.Any(b => i.FileNameWithoutExtension.StartsWith(b, StringComparison.OrdinalIgnoreCase))) .ToList(); } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 91f443500f..05ba0c2e51 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -91,7 +91,7 @@ namespace Emby.Naming.Video { var cleanDateTimeResult = CleanDateTime(name); - if (string.IsNullOrEmpty(extraResult.ExtraType)) + if (extraResult.ExtraType == null) { name = CleanString(cleanDateTimeResult.Name).Name; } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 528636ecd3..8589b1b33c 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2556,7 +2556,7 @@ namespace Emby.Server.Implementations.Library if (currentVideo != null) { - files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path))); + files.AddRange(currentVideo.Extras.Where(i => i.ExtraType == ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path))); } var resolvers = new IItemResolver[] @@ -2606,7 +2606,7 @@ namespace Emby.Server.Implementations.Library if (currentVideo != null) { - files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path))); + files.AddRange(currentVideo.Extras.Where(i => i.ExtraType != ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path))); } return ResolvePaths(files, directoryService, null, new LibraryOptions(), null) @@ -2710,7 +2710,7 @@ namespace Emby.Server.Implementations.Library if (!string.Equals(newPath, path, StringComparison.Ordinal)) { - if (to.IndexOf('/') != -1) + if (to.IndexOf('/', StringComparison.Ordinal) != -1) { newPath = newPath.Replace('\\', '/'); } @@ -2731,30 +2731,7 @@ namespace Emby.Server.Implementations.Library var result = resolver.GetExtraInfo(item.Path); - if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase)) - { - item.ExtraType = ExtraType.DeletedScene; - } - else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase)) - { - item.ExtraType = ExtraType.BehindTheScenes; - } - else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase)) - { - item.ExtraType = ExtraType.Interview; - } - else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase)) - { - item.ExtraType = ExtraType.Scene; - } - else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase)) - { - item.ExtraType = ExtraType.Sample; - } - else - { - item.ExtraType = ExtraType.Clip; - } + item.ExtraType = result.ExtraType; } public List GetPeople(InternalPeopleQuery query) diff --git a/MediaBrowser.Model/Entities/MediaType.cs b/MediaBrowser.Model/Entities/MediaType.cs index c56c8f8f22..d8b02c9eae 100644 --- a/MediaBrowser.Model/Entities/MediaType.cs +++ b/MediaBrowser.Model/Entities/MediaType.cs @@ -3,20 +3,23 @@ namespace MediaBrowser.Model.Entities /// /// Class MediaType /// - public class MediaType + public static class MediaType { /// /// The video /// public const string Video = "Video"; + /// /// The audio /// public const string Audio = "Audio"; + /// /// The photo /// public const string Photo = "Photo"; + /// /// The book /// diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 75b5573b67..1d424a27df 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -24,6 +24,8 @@ + + diff --git a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs new file mode 100644 index 0000000000..eb69d915ca --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs @@ -0,0 +1,57 @@ +using Emby.Naming.Audio; +using Emby.Naming.Common; +using Xunit; + +namespace Jellyfin.Naming.Tests.Music +{ + public class MultiDiscAlbumTests + { + [Fact] + public void TestMultiDiscAlbums() + { + Assert.False(IsMultiDiscAlbumFolder(@"blah blah")); + Assert.False(IsMultiDiscAlbumFolder(@"d:/music\weezer/03 Pinkerton")); + Assert.False(IsMultiDiscAlbumFolder(@"d:/music/michael jackson/Bad (2012 Remaster)")); + + Assert.True(IsMultiDiscAlbumFolder(@"cd1")); + Assert.True(IsMultiDiscAlbumFolder(@"disc1")); + Assert.True(IsMultiDiscAlbumFolder(@"disk1")); + + // Add a space + Assert.True(IsMultiDiscAlbumFolder(@"cd 1")); + Assert.True(IsMultiDiscAlbumFolder(@"disc 1")); + Assert.True(IsMultiDiscAlbumFolder(@"disk 1")); + + Assert.True(IsMultiDiscAlbumFolder(@"cd - 1")); + Assert.True(IsMultiDiscAlbumFolder(@"disc- 1")); + Assert.True(IsMultiDiscAlbumFolder(@"disk - 1")); + + Assert.True(IsMultiDiscAlbumFolder(@"Disc 01 (Hugo Wolf · 24 Lieder)")); + Assert.True(IsMultiDiscAlbumFolder(@"Disc 04 (Encores and Folk Songs)")); + Assert.True(IsMultiDiscAlbumFolder(@"Disc04 (Encores and Folk Songs)")); + Assert.True(IsMultiDiscAlbumFolder(@"Disc 04(Encores and Folk Songs)")); + Assert.True(IsMultiDiscAlbumFolder(@"Disc04(Encores and Folk Songs)")); + + Assert.True(IsMultiDiscAlbumFolder(@"D:/Video/MBTestLibrary/VideoTest/music/.38 special/anth/Disc 2")); + } + + [Fact] + public void TestMultiDiscAlbums1() + { + Assert.False(IsMultiDiscAlbumFolder(@"[1985] Oppurtunities (Let's make lots of money) (1985)")); + } + + [Fact] + public void TestMultiDiscAlbums2() + { + Assert.False(IsMultiDiscAlbumFolder(@"Blah 04(Encores and Folk Songs)")); + } + + private bool IsMultiDiscAlbumFolder(string path) + { + var parser = new AlbumParser(new NamingOptions()); + + return parser.ParseMultiPart(path).IsMultiPart; + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs new file mode 100644 index 0000000000..e8f14cdc45 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -0,0 +1,40 @@ +using Emby.Naming.Common; +using Emby.Naming.Subtitles; +using Xunit; + +namespace Jellyfin.Naming.Tests.Subtitles +{ + public class SubtitleParserTests + { + private SubtitleParser GetParser() + { + var options = new NamingOptions(); + + return new SubtitleParser(options); + } + + [Fact] + public void TestSubtitles() + { + Test("The Skin I Live In (2011).srt", null, false, false); + Test("The Skin I Live In (2011).eng.srt", "eng", false, false); + Test("The Skin I Live In (2011).eng.default.srt", "eng", true, false); + Test("The Skin I Live In (2011).eng.forced.srt", "eng", false, true); + Test("The Skin I Live In (2011).eng.foreign.srt", "eng", false, true); + Test("The Skin I Live In (2011).eng.default.foreign.srt", "eng", true, true); + + Test("The Skin I Live In (2011).default.foreign.eng.srt", "eng", true, true); + } + + private void Test(string input, string language, bool isDefault, bool isForced) + { + var parser = GetParser(); + + var result = parser.ParseFile(input); + + Assert.Equal(language, result.Language, true); + Assert.Equal(isDefault, result.IsDefault); + Assert.Equal(isForced, result.IsForced); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs new file mode 100644 index 0000000000..9abbcc7bf0 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/AbsoluteEpisodeNumberTests.cs @@ -0,0 +1,61 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class AbsoluteEpisodeNumberTests + { + [Fact] + public void TestAbsoluteEpisodeNumber1() + { + Assert.Equal(12, GetEpisodeNumberFromFile(@"The Simpsons/12.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber2() + { + Assert.Equal(12, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 12.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber3() + { + Assert.Equal(82, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 82.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber4() + { + Assert.Equal(112, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 112.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber5() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/Foo_ep_02.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber6() + { + Assert.Equal(889, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 889.avi")); + } + + [Fact] + public void TestAbsoluteEpisodeNumber7() + { + Assert.Equal(101, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 101.avi")); + } + + private int? GetEpisodeNumberFromFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false, null, null, true); + + return result.EpisodeNumber; + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs new file mode 100644 index 0000000000..29daf8cc37 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/DailyEpisodeTests.cs @@ -0,0 +1,69 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class DailyEpisodeTests + { + [Fact] + public void TestDailyEpisode1() + { + Test(@"/server/anything_1996.11.14.mp4", "anything", 1996, 11, 14); + } + + [Fact] + public void TestDailyEpisode2() + { + Test(@"/server/anything_1996-11-14.mp4", "anything", 1996, 11, 14); + } + + // FIXME + // [Fact] + public void TestDailyEpisode3() + { + Test(@"/server/anything_14.11.1996.mp4", "anything", 1996, 11, 14); + } + + // FIXME + // [Fact] + public void TestDailyEpisode4() + { + Test(@"/server/A Daily Show - (2015-01-15) - Episode Name - [720p].mkv", "A Daily Show", 2015, 01, 15); + } + + [Fact] + public void TestDailyEpisode5() + { + Test(@"/server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv", "james.corden", 2017, 04, 20); + } + + [Fact] + public void TestDailyEpisode6() + { + Test(@"/server/ABC News 2018_03_24_19_00_00.mkv", "ABC News", 2018, 03, 24); + } + + // FIXME + // [Fact] + public void TestDailyEpisode7() + { + Test(@"/server/Last Man Standing_KTLADT_2018_05_25_01_28_00.wtv", "Last Man Standing", 2018, 05, 25); + } + + private void Test(string path, string seriesName, int? year, int? month, int? day) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + Assert.Null(result.SeasonNumber); + Assert.Null(result.EpisodeNumber); + Assert.Equal(year, result.Year); + Assert.Equal(month, result.Month); + Assert.Equal(day, result.Day); + Assert.Equal(seriesName, result.SeriesName, true); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs new file mode 100644 index 0000000000..03fae31596 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -0,0 +1,421 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class EpisodeNumberTests + { + [Fact] + public void TestEpisodeNumber1() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/S02E03 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber40() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber41() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/01x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber42() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber43() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01E02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber44() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/Elementary - 02x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber45() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01xE02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber46() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01E02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber47() + { + Assert.Equal(36, GetEpisodeNumberFromFile(@"Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv")); + } + + [Fact] + public void TestEpisodeNumber50() + { + // This convention is not currently supported, just adding in case we want to look at it in the future + Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season s2016e1.mp4")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber51() + { + // This convention is not currently supported, just adding in case we want to look at it in the future + Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season 2016x1.mp4")); + } + + [Fact] + public void TestEpisodeNumber52() + { + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode - 16.avi")); + } + + [Fact] + public void TestEpisodeNumber53() + { + // This is not supported. Expected to fail, although it would be a good one to add support for. + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16.avi")); + } + [Fact] + public void TestEpisodeNumber54() + { + // This is not supported. Expected to fail, although it would be a good one to add support for. + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); + } + [Fact] + public void TestEpisodeNumber55() + { + // This is not supported. Expected to fail, although it would be a good one to add support for. + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); + } + [Fact] + public void TestEpisodeNumber56() + { + // This is not supported. Expected to fail, although it would be a good one to add support for. + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); + } + + [Fact] + public void TestEpisodeNumber57() + { + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 Some Title.avi")); + } + + [Fact] + public void TestEpisodeNumber58() + { + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 - 12 Some Title.avi")); + } + + [Fact] + public void TestEpisodeNumber59() + { + Assert.Equal(7, GetEpisodeNumberFromFile(@"Season 2/7 - 12 Angry Men.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber60() + { + Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 12 Some Title.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber61() + { + Assert.Equal(7, GetEpisodeNumberFromFile(@"Season 2/7 12 Angry Men.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber62() + { + // This is not supported. Expected to fail, although it would be a good one to add support for. + Assert.Equal(3, GetEpisodeNumberFromFile(@"Season 4/Uchuu.Senkan.Yamato.2199.E03.avi")); + } + + [Fact] + public void TestEpisodeNumber63() + { + Assert.Equal(3, GetEpisodeNumberFromFile(@"Season 4/Uchuu.Senkan.Yamato.2199.S04E03.avi")); + } + + [Fact] + public void TestEpisodeNumber64() + { + Assert.Equal(368, GetEpisodeNumberFromFile(@"Running Man/Running Man S2017E368.mkv")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber65() + { + // Not supported yet + Assert.Equal(7, GetEpisodeNumberFromFile(@"/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv")); + } + + [Fact] + public void TestEpisodeNumber30() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber31() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname 01x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber32() + { + Assert.Equal(9, GetEpisodeNumberFromFile(@"Season 25/The Simpsons.S25E09.Steal this episode.mp4")); + } + + [Fact] + public void TestEpisodeNumber33() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber34() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber35() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01xE02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber36() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber37() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber38() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber39() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber20() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber21() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber22() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber23() + { + Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestEpisodeNumber24() + { + Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestEpisodeNumber25() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/2009x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber26() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber27() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009E02 blah.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumber28() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname 2009x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber29() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber11() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber12() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber13() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009xE02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber14() + { + Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestEpisodeNumber15() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009xE02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber16() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber17() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009E02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber18() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber19() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber2() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009x02 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber3() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber4() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber5() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber6() + { + Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestEpisodeNumber7() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/02 - blah-02 a.avi")); + } + + [Fact] + public void TestEpisodeNumber8() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/02 - blah.avi")); + } + + [Fact] + public void TestEpisodeNumber9() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/02 - blah 14 blah.avi")); + } + + [Fact] + public void TestEpisodeNumber10() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/02.avi")); + } + + [Fact] + public void TestEpisodeNumber48() + { + Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/2. Infestation.avi")); + } + + [Fact] + public void TestEpisodeNumber49() + { + Assert.Equal(7, GetEpisodeNumberFromFile(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi")); + } + + private int? GetEpisodeNumberFromFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodePathParser(options) + .Parse(path, false); + + return result.EpisodeNumber; + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs new file mode 100644 index 0000000000..00aa9ee7c2 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberWithoutSeasonTests.cs @@ -0,0 +1,127 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class EpisodeNumberWithoutSeasonTests + { + [Fact] + public void TestEpisodeNumberWithoutSeason1() + { + Assert.Equal(8, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons.S25E08.Steal this episode.mp4")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason2() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons - 02 - Ep Name.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason3() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/02.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason4() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/02 - Ep Name.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason5() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/02-Ep Name.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason6() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/02.EpName.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason7() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons - 02.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason8() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons - 02 Ep Name.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumberWithoutSeason9() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 5 - 02 - Ep Name.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumberWithoutSeason10() + { + Assert.Equal(2, GetEpisodeNumberFromFile(@"The Simpsons/The Simpsons 5 - 02 Ep Name.avi")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumberWithoutSeason11() + { + Assert.Equal(7, GetEpisodeNumberFromFile(@"Seinfeld/Seinfeld 0807 The Checks.avi")); + Assert.Equal(8, GetSeasonNumberFromFile(@"Seinfeld/Seinfeld 0807 The Checks.avi")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason12() + { + Assert.Equal(7, GetEpisodeNumberFromFile(@"GJ Club (2013)/GJ Club - 07.mkv")); + } + + // FIXME + // [Fact] + public void TestEpisodeNumberWithoutSeason13() + { + // This is not supported anymore after removing the episode number 365+ hack from EpisodePathParser + Assert.Equal(13, GetEpisodeNumberFromFile(@"Case Closed (1996-2007)/Case Closed - 13.mkv")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason14() + { + Assert.Equal(3, GetSeasonNumberFromFile(@"Case Closed (1996-2007)/Case Closed - 317.mkv")); + Assert.Equal(17, GetEpisodeNumberFromFile(@"Case Closed (1996-2007)/Case Closed - 317.mkv")); + } + + [Fact] + public void TestEpisodeNumberWithoutSeason15() + { + Assert.Equal(2017, GetSeasonNumberFromFile(@"Running Man/Running Man S2017E368.mkv")); + } + + private int? GetEpisodeNumberFromFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + return result.EpisodeNumber; + } + + private int? GetSeasonNumberFromFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + return result.SeasonNumber; + } + + } +} diff --git a/tests/Jellyfin.Naming.Tests/EpisodePathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs similarity index 91% rename from tests/Jellyfin.Naming.Tests/EpisodePathParserTest.cs rename to tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs index dd1e042155..8e8adb35b3 100644 --- a/tests/Jellyfin.Naming.Tests/EpisodePathParserTest.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs @@ -2,7 +2,7 @@ using Emby.Naming.Common; using Emby.Naming.TV; using Xunit; -namespace Jellyfin.Naming.Tests +namespace Jellyfin.Naming.Tests.TV { public class EpisodePathParserTest { @@ -23,7 +23,7 @@ namespace Jellyfin.Naming.Tests Assert.Equal(episode, res.EpisodeNumber); // testing other paths delimeter - var res2 = p.Parse(path.Replace('/', '\\'), false); + var res2 = p.Parse(path.Replace('/', '/'), false); Assert.True(res2.Success); Assert.Equal(name, res2.SeriesName); Assert.Equal(season, res2.SeasonNumber); @@ -45,7 +45,7 @@ namespace Jellyfin.Naming.Tests Assert.Equal(episode, res.EpisodeNumber); // testing other paths delimeter - var res2 = p.Parse(path.Replace('/', '\\'), false, fillExtendedInfo: false); + var res2 = p.Parse(path.Replace('/', '/'), false, fillExtendedInfo: false); Assert.True(res2.Success); Assert.Equal(name, res2.SeriesName); Assert.Null(res2.SeasonNumber); diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs new file mode 100644 index 0000000000..c2851ccdb1 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeWithoutSeasonTests.cs @@ -0,0 +1,56 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class EpisodeWithoutSeasonTests + { + // FIXME + // [Fact] + public void TestWithoutSeason1() + { + Test(@"/server/anything_ep02.mp4", "anything", null, 2); + } + + // FIXME + // [Fact] + public void TestWithoutSeason2() + { + Test(@"/server/anything_ep_02.mp4", "anything", null, 2); + } + + // FIXME + // [Fact] + public void TestWithoutSeason3() + { + Test(@"/server/anything_part.II.mp4", "anything", null, null); + } + + // FIXME + // [Fact] + public void TestWithoutSeason4() + { + Test(@"/server/anything_pt.II.mp4", "anything", null, null); + } + + // FIXME + // [Fact] + public void TestWithoutSeason5() + { + Test(@"/server/anything_pt_II.mp4", "anything", null, null); + } + + private void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + Assert.Equal(seasonNumber, result.SeasonNumber); + Assert.Equal(episodeNumber, result.EpisodeNumber); + Assert.Equal(seriesName, result.SeriesName, true); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs new file mode 100644 index 0000000000..b15dd6b74c --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs @@ -0,0 +1,105 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class MultiEpisodeTests + { + [Fact] + public void TestGetEndingEpisodeNumberFromFile() + { + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/4x01 – 20 Hours in America (1).mkv")); + + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/01x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/S01x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/S01E02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/S01xE02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/seriesname 01x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/seriesname S01x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/seriesname S01E02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/seriesname S01xE02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2/02x03 - 04 Ep Name.mp4")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2/My show name 02x03 - 04 Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2/02x03-04-15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2/Elementary - 02x03-04-15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/02x03-E15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/Elementary - 02x03-E15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/02x03 - x04 - x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/02x03x04x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 02/Elementary - 02x03x04x15 - Ep Name.mp4")); + Assert.Equal(26, GetEndingEpisodeNumberFromFile(@"Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4")); + Assert.Equal(26, GetEndingEpisodeNumberFromFile(@"Season 1/S01E23-E24-E26 - The Woman.mp4")); + + + // Four Digits seasons + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/2009x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/S2009x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/S2009E02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/S2009xE02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/seriesname 2009x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/seriesname S2009x02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/seriesname S2009E02 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2009/seriesname S2009xE02 blah.avi")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/2009x03-04-15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/2009x03-E15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/2009x03 - x04 - x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/2009x03x04x15 - Ep Name.mp4")); + Assert.Equal(15, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4")); + Assert.Equal(26, GetEndingEpisodeNumberFromFile(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4")); + Assert.Equal(26, GetEndingEpisodeNumberFromFile(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4")); + + // Without season number + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/02 - blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2/02 - blah 14 blah.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/02 - blah-02 a.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2/02.avi")); + + Assert.Equal(3, GetEndingEpisodeNumberFromFile(@"Season 1/02-03 - blah.avi")); + Assert.Equal(4, GetEndingEpisodeNumberFromFile(@"Season 2/02-04 - blah 14 blah.avi")); + Assert.Equal(5, GetEndingEpisodeNumberFromFile(@"Season 1/02-05 - blah-02 a.avi")); + Assert.Equal(4, GetEndingEpisodeNumberFromFile(@"Season 2/02-04.avi")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv")); + + // With format specification that must not be detected as ending episode number + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/series-s09e14-1080p.mkv")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/series-s09e14-720p.mkv")); + Assert.Null(GetEndingEpisodeNumberFromFile(@"Season 1/series-s09e14-720i.mkv")); + Assert.Equal(4, GetEndingEpisodeNumberFromFile(@"Season 1/MOONLIGHTING_s01e01-e04.mkv")); + } + + [Fact] + public void TestGetEndingEpisodeNumberFromFolder() + { + Assert.Equal(4, GetEndingEpisodeNumberFromFolder(@"Season 1/MOONLIGHTING_s01e01-e04")); + } + + private int? GetEndingEpisodeNumberFromFolder(string path) + { + var options = new NamingOptions(); + + var result = new EpisodePathParser(options) + .Parse(path, true); + + return result.EndingEpsiodeNumber; + } + + private int? GetEndingEpisodeNumberFromFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodePathParser(options) + .Parse(path, false); + + return result.EndingEpsiodeNumber; + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs new file mode 100644 index 0000000000..ffa8d34838 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs @@ -0,0 +1,112 @@ +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class SeasonFolderTests + { + [Fact] + public void TestGetSeasonNumberFromPath1() + { + Assert.Equal(1, GetSeasonNumberFromPath(@"/Drive/Season 1")); + } + + [Fact] + public void TestGetSeasonNumberFromPath2() + { + Assert.Equal(2, GetSeasonNumberFromPath(@"/Drive/Season 2")); + } + + [Fact] + public void TestGetSeasonNumberFromPath3() + { + Assert.Equal(2, GetSeasonNumberFromPath(@"/Drive/Season 02")); + } + + [Fact] + public void TestGetSeasonNumberFromPath4() + { + Assert.Equal(1, GetSeasonNumberFromPath(@"/Drive/Season 1")); + } + + [Fact] + public void TestGetSeasonNumberFromPath5() + { + Assert.Equal(2, GetSeasonNumberFromPath(@"/Drive/Seinfeld/S02")); + } + + [Fact] + public void TestGetSeasonNumberFromPath6() + { + Assert.Equal(2, GetSeasonNumberFromPath(@"/Drive/Seinfeld/2")); + } + + [Fact] + public void TestGetSeasonNumberFromPath7() + { + Assert.Equal(2009, GetSeasonNumberFromPath(@"/Drive/Season 2009")); + } + + [Fact] + public void TestGetSeasonNumberFromPath8() + { + Assert.Equal(1, GetSeasonNumberFromPath(@"/Drive/Season1")); + } + + [Fact] + public void TestGetSeasonNumberFromPath9() + { + Assert.Equal(4, GetSeasonNumberFromPath(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH")); + } + + [Fact] + public void TestGetSeasonNumberFromPath10() + { + Assert.Equal(7, GetSeasonNumberFromPath(@"/Drive/Season 7 (2016)")); + } + + [Fact] + public void TestGetSeasonNumberFromPath11() + { + Assert.Equal(7, GetSeasonNumberFromPath(@"/Drive/Staffel 7 (2016)")); + } + + [Fact] + public void TestGetSeasonNumberFromPath12() + { + Assert.Equal(7, GetSeasonNumberFromPath(@"/Drive/Stagione 7 (2016)")); + } + + [Fact] + public void TestGetSeasonNumberFromPath14() + { + Assert.Null(GetSeasonNumberFromPath(@"/Drive/Season (8)")); + } + + [Fact] + public void TestGetSeasonNumberFromPath13() + { + Assert.Equal(3, GetSeasonNumberFromPath(@"/Drive/3.Staffel")); + } + + [Fact] + public void TestGetSeasonNumberFromPath15() + { + Assert.Null(GetSeasonNumberFromPath(@"/Drive/s06e05")); + } + + [Fact] + public void TestGetSeasonNumberFromPath16() + { + Assert.Null(GetSeasonNumberFromPath(@"/Drive/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv")); + } + + private int? GetSeasonNumberFromPath(string path) + { + var result = new SeasonPathParser() + .Parse(path, true, true); + + return result.SeasonNumber; + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs new file mode 100644 index 0000000000..ba3c5ecac9 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs @@ -0,0 +1,305 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class SeasonNumberTests + { + private int? GetSeasonNumberFromEpisodeFile(string path) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + return result.SeasonNumber; + } + + [Fact] + public void TestSeasonNumber1() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"/Show/Season 02/S02E03 blah.avi")); + } + + [Fact] + public void TestSeasonNumber2() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/seriesname S01x02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber3() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/S01x02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber4() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/seriesname S01xE02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber5() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/01x02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber6() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/S01E02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber7() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/S01xE02 blah.avi")); + } + + // FIXME + // [Fact] + public void TestSeasonNumber8() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/seriesname 01x02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber9() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/seriesname S01x02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber10() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/seriesname S01E02 blah.avi")); + } + + [Fact] + public void TestSeasonNumber11() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber12() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber13() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 2/02x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber14() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 2/Elementary - 02x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber15() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/02x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber16() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/Elementary - 02x03-E15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber17() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/02x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber18() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber19() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/02x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber20() + { + Assert.Equal(2, GetSeasonNumberFromEpisodeFile(@"Season 02/Elementary - 02x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestSeasonNumber21() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestSeasonNumber22() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Season 1/S01E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestSeasonNumber23() + { + Assert.Equal(25, GetSeasonNumberFromEpisodeFile(@"Season 25/The Simpsons.S25E09.Steal this episode.mp4")); + } + + [Fact] + public void TestSeasonNumber24() + { + Assert.Equal(25, GetSeasonNumberFromEpisodeFile(@"The Simpsons/The Simpsons.S25E09.Steal this episode.mp4")); + } + + [Fact] + public void TestSeasonNumber25() + { + Assert.Equal(2016, GetSeasonNumberFromEpisodeFile(@"2016/Season s2016e1.mp4")); + } + + // FIXME + // [Fact] + public void TestSeasonNumber26() + { + // This convention is not currently supported, just adding in case we want to look at it in the future + Assert.Equal(2016, GetSeasonNumberFromEpisodeFile(@"2016/Season 2016x1.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber1() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/2009x02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber2() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/S2009x02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber3() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/S2009E02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber4() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/S2009xE02 blah.avi")); + } + + // FIXME + // [Fact] + public void TestFourDigitSeasonNumber5() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/seriesname 2009x02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber6() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/seriesname S2009x02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber7() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/seriesname S2009E02 blah.avi")); + } + + [Fact] + public void TestFourDigitSeasonNumber8() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber9() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber10() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/2009x03-04-15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber11() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber12() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber13() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber14() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber15() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber16() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber17() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber18() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber19() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestFourDigitSeasonNumber20() + { + Assert.Equal(2009, GetSeasonNumberFromEpisodeFile(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4")); + } + + [Fact] + public void TestNoSeriesFolder() + { + Assert.Equal(1, GetSeasonNumberFromEpisodeFile(@"Series/1-12 - The Woman.mp4")); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs new file mode 100644 index 0000000000..c9323c218e --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs @@ -0,0 +1,95 @@ +using Emby.Naming.Common; +using Emby.Naming.TV; +using Xunit; + +namespace Jellyfin.Naming.Tests.TV +{ + public class SimpleEpisodeTests + { + [Fact] + public void TestSimpleEpisodePath1() + { + Test(@"/server/anything_s01e02.mp4", "anything", 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath2() + { + Test(@"/server/anything_s1e2.mp4", "anything", 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath3() + { + Test(@"/server/anything_s01.e02.mp4", "anything", 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath4() + { + Test(@"/server/anything_s01_e02.mp4", "anything", 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath5() + { + Test(@"/server/anything_102.mp4", "anything", 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath6() + { + Test(@"/server/anything_1x02.mp4", "anything", 1, 2); + } + + // FIXME + // [Fact] + public void TestSimpleEpisodePath7() + { + Test(@"/server/The Walking Dead 4x01.mp4", "The Walking Dead", 4, 1); + } + + [Fact] + public void TestSimpleEpisodePath8() + { + Test(@"/server/the_simpsons-s02e01_18536.mp4", "the_simpsons", 2, 1); + } + + + [Fact] + public void TestSimpleEpisodePath9() + { + Test(@"/server/Temp/S01E02 foo.mp4", string.Empty, 1, 2); + } + + [Fact] + public void TestSimpleEpisodePath10() + { + Test(@"Series/4-12 - The Woman.mp4", string.Empty, 4, 12); + } + + [Fact] + public void TestSimpleEpisodePath11() + { + Test(@"Series/4x12 - The Woman.mp4", string.Empty, 4, 12); + } + + [Fact] + public void TestSimpleEpisodePath12() + { + Test(@"Series/LA X, Pt. 1_s06e32.mp4", "LA X, Pt. 1", 6, 32); + } + + private void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber) + { + var options = new NamingOptions(); + + var result = new EpisodeResolver(options) + .Resolve(path, false); + + Assert.Equal(seasonNumber, result.SeasonNumber); + Assert.Equal(episodeNumber, result.EpisodeNumber); + Assert.Equal(seriesName, result.SeriesName, true); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs new file mode 100644 index 0000000000..b993e241c0 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs @@ -0,0 +1,15 @@ +using Emby.Naming.Common; +using Emby.Naming.Video; + +namespace Jellyfin.Naming.Tests.Video +{ + public abstract class BaseVideoTest + { + protected VideoResolver GetParser() + { + var options = new NamingOptions(); + + return new VideoResolver(options); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs new file mode 100644 index 0000000000..bba73ad918 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs @@ -0,0 +1,143 @@ +using System.IO; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class CleanDateTimeTests : BaseVideoTest + { + // FIXME + // [Fact] + public void TestCleanDateTime() + { + Test(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013); + Test(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013); + Test(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013); + Test(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013); + + Test(@"300 (2006).mkv", "300", 2006); + Test(@"d:/movies/300 (2006).mkv", "300", 2006); + Test(@"300 2 (2006).mkv", "300 2", 2006); + Test(@"300 - 2 (2006).mkv", "300 - 2", 2006); + Test(@"300 2001 (2006).mkv", "300 2001", 2006); + + Test(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013); + Test(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013); + + Test(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006); + } + + // FIXME + // [Fact] + public void TestCleanDateTime1() + { + Test(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithoutFileExtension() + { + Test(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013); + Test(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013); + Test(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013); + Test(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013); + + Test(@"300 (2006)", "300", 2006); + Test(@"d:/movies/300 (2006)", "300", 2006); + Test(@"300 2 (2006)", "300 2", 2006); + Test(@"300 - 2 (2006)", "300 - 2", 2006); + Test(@"300 2001 (2006)", "300 2001", 2006); + + Test(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006); + Test(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006); + } + + [Fact] + public void TestCleanDateTimeWithoutDate() + { + Test(@"American.Psycho.mkv", "American.Psycho.mkv", null); + Test(@"American Psycho.mkv", "American Psycho.mkv", null); + } + + [Fact] + public void TestCleanDateTimeWithBracketedName() + { + Test(@"[rec].mkv", "[rec].mkv", null); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithoutExtension() + { + Test(@"St. Vincent (2014)", "St. Vincent", 2014); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithoutDate1() + { + Test("Super movie(2009).mp4", "Super movie", 2009); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithoutParenthesis() + { + Test("Drug War 2013.mp4", "Drug War", 2013); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithMultipleYears() + { + Test("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithYearAndResolution() + { + Test("First Man 2018 1080p.mkv", "First Man", 2018); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithYearAndResolution1() + { + Test("First Man (2018) 1080p.mkv", "First Man", 2018); + } + + // FIXME + // [Fact] + public void TestCleanDateTimeWithSceneRelease() + { + Test("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016); + } + + // FIXME + // [Fact] + public void TestYearInBrackets() + { + Test("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018); + } + + private void Test(string input, string expectedName, int? expectedYear) + { + input = Path.GetFileName(input); + + var result = GetParser().CleanDateTime(input); + + Assert.Equal(expectedName, result.Name, true); + Assert.Equal(expectedYear, result.Year); + } + + // FIXME + // [Fact] + public void TestCleanDateAndStringsSequence() + { + // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again + + Test(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs new file mode 100644 index 0000000000..cd90ac236c --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Globalization; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class CleanStringTests : BaseVideoTest + { + // FIXME + // [Fact] + public void TestCleanString() + { + Test("Super movie 480p.mp4", "Super movie"); + Test("Super movie 480p 2001.mp4", "Super movie"); + Test("Super movie [480p].mp4", "Super movie"); + Test("480 Super movie [tmdbid=12345].mp4", "480 Super movie"); + } + + // FIXME + // [Fact] + public void TestCleanString1() + { + Test("Super movie(2009).mp4", "Super movie(2009).mp4"); + } + + // FIXME + // [Fact] + public void TestCleanString2() + { + Test("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4"); + } + + // FIXME + // [Fact] + public void TestStringWithoutDate() + { + Test(@"American.Psycho.mkv", "American.Psycho.mkv"); + Test(@"American Psycho.mkv", "American Psycho.mkv"); + } + + // FIXME + // [Fact] + public void TestNameWithBrackets() + { + Test(@"[rec].mkv", "[rec].mkv"); + } + + // FIXME + // [Fact] + public void Test4k() + { + Test("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestUltraHd() + { + Test("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestUHd() + { + Test("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestHDR() + { + Test("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestHDC() + { + Test("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestHDC1() + { + Test("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestBDrip() + { + Test("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestBDripHDC() + { + Test("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestMulti() + { + Test("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); + } + + // FIXME + // [Fact] + public void TestLeadingBraces() + { + // Not actually supported, just reported by a user + Test("[0004] - After The Sunset.el.mkv", "After The Sunset"); + } + + // FIXME + // [Fact] + public void TestTrailingBraces() + { + Test("After The Sunset - [0004].mkv", "After The Sunset"); + } + + private void Test(string input, string expectedName) + { + var result = GetParser().CleanString(input).ToString(); + + Assert.Equal(expectedName, result, true); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs new file mode 100644 index 0000000000..1646237a0e --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs @@ -0,0 +1,77 @@ +using Emby.Naming.Common; +using Emby.Naming.Video; +using MediaBrowser.Model.Entities; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class ExtraTests : BaseVideoTest + { + // Requirements + // movie-deleted = ExtraType deletedscene + + // All of the above rules should be configurable through the options objects (ideally, even the ExtraTypes) + + [Fact] + public void TestKodiExtras() + { + var videoOptions = new NamingOptions(); + + Test("trailer.mp4", ExtraType.Trailer, videoOptions); + Test("300-trailer.mp4", ExtraType.Trailer, videoOptions); + + Test("theme.mp3", ExtraType.ThemeSong, videoOptions); + } + + [Fact] + public void TestExpandedExtras() + { + var videoOptions = new NamingOptions(); + + Test("trailer.mp4", ExtraType.Trailer, videoOptions); + Test("trailer.mp3", null, videoOptions); + Test("300-trailer.mp4", ExtraType.Trailer, videoOptions); + + Test("theme.mp3", ExtraType.ThemeSong, videoOptions); + Test("theme.mkv", null, videoOptions); + + Test("300-scene.mp4", ExtraType.Scene, videoOptions); + Test("300-scene2.mp4", ExtraType.Scene, videoOptions); + Test("300-clip.mp4", ExtraType.Clip, videoOptions); + + Test("300-deleted.mp4", ExtraType.DeletedScene, videoOptions); + Test("300-deletedscene.mp4", ExtraType.DeletedScene, videoOptions); + Test("300-interview.mp4", ExtraType.Interview, videoOptions); + Test("300-behindthescenes.mp4", ExtraType.BehindTheScenes, videoOptions); + } + + [Fact] + public void TestSample() + { + var videoOptions = new NamingOptions(); + + Test("300-sample.mp4", ExtraType.Sample, videoOptions); + } + + private void Test(string input, ExtraType? expectedType, NamingOptions videoOptions) + { + var parser = GetExtraTypeParser(videoOptions); + + var extraType = parser.GetExtraInfo(input).ExtraType; + + if (expectedType == null) + { + Assert.Null(extraType); + } + else + { + Assert.Equal(expectedType, extraType); + } + } + + private ExtraResolver GetExtraTypeParser(NamingOptions videoOptions) + { + return new ExtraResolver(videoOptions); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs b/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs new file mode 100644 index 0000000000..ed3112936d --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/Format3DTests.cs @@ -0,0 +1,78 @@ +using Emby.Naming.Common; +using Emby.Naming.Video; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class Format3DTests : BaseVideoTest + { + [Fact] + public void TestKodiFormat3D() + { + var options = new NamingOptions(); + + Test("Super movie.3d.mp4", false, null, options); + Test("Super movie.3d.hsbs.mp4", true, "hsbs", options); + Test("Super movie.3d.sbs.mp4", true, "sbs", options); + Test("Super movie.3d.htab.mp4", true, "htab", options); + Test("Super movie.3d.tab.mp4", true, "tab", options); + Test("Super movie 3d hsbs.mp4", true, "hsbs", options); + } + + [Fact] + public void Test3DName() + { + var result = + GetParser().ResolveFile(@"C:/Users/media/Desktop/Video Test/Movies/Oblivion/Oblivion.3d.hsbs.mkv"); + + Assert.Equal("hsbs", result.Format3D); + Assert.Equal("Oblivion", result.Name); + } + + [Fact] + public void TestExpandedFormat3D() + { + // These were introduced for Media Browser 3 + // Kodi conventions are preferred but these still need to be supported + var options = new NamingOptions(); + + Test("Super movie.3d.mp4", false, null, options); + Test("Super movie.3d.hsbs.mp4", true, "hsbs", options); + Test("Super movie.3d.sbs.mp4", true, "sbs", options); + Test("Super movie.3d.htab.mp4", true, "htab", options); + Test("Super movie.3d.tab.mp4", true, "tab", options); + + Test("Super movie.hsbs.mp4", true, "hsbs", options); + Test("Super movie.sbs.mp4", true, "sbs", options); + Test("Super movie.htab.mp4", true, "htab", options); + Test("Super movie.tab.mp4", true, "tab", options); + Test("Super movie.sbs3d.mp4", true, "sbs3d", options); + Test("Super movie.3d.mvc.mp4", true, "mvc", options); + + Test("Super movie [3d].mp4", false, null, options); + Test("Super movie [hsbs].mp4", true, "hsbs", options); + Test("Super movie [fsbs].mp4", true, "fsbs", options); + Test("Super movie [ftab].mp4", true, "ftab", options); + Test("Super movie [htab].mp4", true, "htab", options); + Test("Super movie [sbs3d].mp4", true, "sbs3d", options); + } + + private void Test(string input, bool is3D, string format3D, NamingOptions options) + { + var parser = new Format3DParser(options); + + var result = parser.Parse(input); + + Assert.Equal(is3D, result.Is3D); + + if (format3D == null) + { + Assert.Null(result.Format3D); + } + else + { + Assert.Equal(format3D, result.Format3D, true); + } + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs new file mode 100644 index 0000000000..b8674ec495 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -0,0 +1,438 @@ +using System.Linq; +using Emby.Naming.Common; +using Emby.Naming.Video; +using MediaBrowser.Model.IO; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class MultiVersionTests + { + // FIXME + // [Fact] + public void TestMultiEdition1() + { + var files = new[] + { + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - 1080p.mkv", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past-trailer.mp4", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - [hsbs].mkv", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [hsbs].mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Single(result[0].Extras); + } + + // FIXME + // [Fact] + public void TestMultiEdition2() + { + var files = new[] + { + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - apple.mkv", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past-trailer.mp4", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past - banana.mkv", + @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [banana].mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Single(result[0].Extras); + Assert.Equal(2, result[0].AlternateVersions.Count); + } + + [Fact] + public void TestMultiEdition3() + { + // This is currently not supported and will fail, but we should try to figure it out + var files = new[] + { + @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1925 version.mkv", + @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1929 version.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Single(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestLetterFolders() + { + var files = new[] + { + @"/movies/M/Movie 1.mkv", + @"/movies/M/Movie 2.mkv", + @"/movies/M/Movie 3.mkv", + @"/movies/M/Movie 4.mkv", + @"/movies/M/Movie 5.mkv", + @"/movies/M/Movie 6.mkv", + @"/movies/M/Movie 7.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(7, result.Count); + Assert.Empty(result[0].Extras); + Assert.Empty(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersionLimit() + { + var files = new[] + { + @"/movies/Movie/Movie.mkv", + @"/movies/Movie/Movie-2.mkv", + @"/movies/Movie/Movie-3.mkv", + @"/movies/Movie/Movie-4.mkv", + @"/movies/Movie/Movie-5.mkv", + @"/movies/Movie/Movie-6.mkv", + @"/movies/Movie/Movie-7.mkv", + @"/movies/Movie/Movie-8.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Equal(7, result[0].AlternateVersions.Count); + } + + // FIXME + // [Fact] + public void TestMultiVersionLimit2() + { + var files = new[] + { + @"/movies/Mo/Movie 1.mkv", + @"/movies/Mo/Movie 2.mkv", + @"/movies/Mo/Movie 3.mkv", + @"/movies/Mo/Movie 4.mkv", + @"/movies/Mo/Movie 5.mkv", + @"/movies/Mo/Movie 6.mkv", + @"/movies/Mo/Movie 7.mkv", + @"/movies/Mo/Movie 8.mkv", + @"/movies/Mo/Movie 9.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(9, result.Count); + Assert.Empty(result[0].Extras); + Assert.Empty(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersion3() + { + var files = new[] + { + @"/movies/Movie/Movie 1.mkv", + @"/movies/Movie/Movie 2.mkv", + @"/movies/Movie/Movie 3.mkv", + @"/movies/Movie/Movie 4.mkv", + @"/movies/Movie/Movie 5.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(5, result.Count); + Assert.Empty(result[0].Extras); + Assert.Empty(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersion4() + { + // Test for false positive + + var files = new[] + { + @"/movies/Iron Man/Iron Man.mkv", + @"/movies/Iron Man/Iron Man (2008).mkv", + @"/movies/Iron Man/Iron Man (2009).mkv", + @"/movies/Iron Man/Iron Man (2010).mkv", + @"/movies/Iron Man/Iron Man (2011).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(5, result.Count); + Assert.Empty(result[0].Extras); + Assert.Empty(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersion5() + { + var files = new[] + { + @"/movies/Iron Man/Iron Man.mkv", + @"/movies/Iron Man/Iron Man-720p.mkv", + @"/movies/Iron Man/Iron Man-test.mkv", + @"/movies/Iron Man/Iron Man-bluray.mkv", + @"/movies/Iron Man/Iron Man-3d.mkv", + @"/movies/Iron Man/Iron Man-3d-hsbs.mkv", + @"/movies/Iron Man/Iron Man-3d.hsbs.mkv", + @"/movies/Iron Man/Iron Man[test].mkv", + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Equal(7, result[0].AlternateVersions.Count); + Assert.False(result[0].AlternateVersions[2].Is3D); + Assert.True(result[0].AlternateVersions[3].Is3D); + Assert.True(result[0].AlternateVersions[4].Is3D); + } + + // FIXME + // [Fact] + public void TestMultiVersion6() + { + var files = new[] + { + @"/movies/Iron Man/Iron Man.mkv", + @"/movies/Iron Man/Iron Man - 720p.mkv", + @"/movies/Iron Man/Iron Man - test.mkv", + @"/movies/Iron Man/Iron Man - bluray.mkv", + @"/movies/Iron Man/Iron Man - 3d.mkv", + @"/movies/Iron Man/Iron Man - 3d-hsbs.mkv", + @"/movies/Iron Man/Iron Man - 3d.hsbs.mkv", + @"/movies/Iron Man/Iron Man [test].mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Equal(7, result[0].AlternateVersions.Count); + Assert.False(result[0].AlternateVersions[3].Is3D); + Assert.True(result[0].AlternateVersions[4].Is3D); + Assert.True(result[0].AlternateVersions[5].Is3D); + } + + // FIXME + // [Fact] + public void TestMultiVersion7() + { + var files = new[] + { + @"/movies/Iron Man/Iron Man - B (2006).mkv", + @"/movies/Iron Man/Iron Man - C (2007).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(2, result.Count); + } + + // FIXME + // [Fact] + public void TestMultiVersion8() + { + // This is not actually supported yet + + var files = new[] + { + @"/movies/Iron Man/Iron Man.mkv", + @"/movies/Iron Man/Iron Man_720p.mkv", + @"/movies/Iron Man/Iron Man_test.mkv", + @"/movies/Iron Man/Iron Man_bluray.mkv", + @"/movies/Iron Man/Iron Man_3d.mkv", + @"/movies/Iron Man/Iron Man_3d-hsbs.mkv", + @"/movies/Iron Man/Iron Man_3d.hsbs.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Equal(6, result[0].AlternateVersions.Count); + Assert.False(result[0].AlternateVersions[2].Is3D); + Assert.True(result[0].AlternateVersions[3].Is3D); + Assert.True(result[0].AlternateVersions[4].Is3D); + } + + // FIXME + // [Fact] + public void TestMultiVersion9() + { + // Test for false positive + + var files = new[] + { + @"/movies/Iron Man/Iron Man (2007).mkv", + @"/movies/Iron Man/Iron Man (2008).mkv", + @"/movies/Iron Man/Iron Man (2009).mkv", + @"/movies/Iron Man/Iron Man (2010).mkv", + @"/movies/Iron Man/Iron Man (2011).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(5, result.Count); + Assert.Empty(result[0].Extras); + Assert.Empty(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersion10() + { + var files = new[] + { + @"/movies/Blade Runner (1982)/Blade Runner (1982) [Final Cut] [1080p HEVC AAC].mkv", + @"/movies/Blade Runner (1982)/Blade Runner (1982) [EE by ADM] [480p HEVC AAC,AAC,AAC].mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Single(result[0].AlternateVersions); + } + + // FIXME + // [Fact] + public void TestMultiVersion11() + { + // Currently not supported but we should probably handle this. + + var files = new[] + { + @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [1080p] Blu-ray.x264.DTS.mkv", + @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [2160p] Blu-ray.x265.AAC.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Single(result[0].AlternateVersions); + } + + private VideoListResolver GetResolver() + { + var options = new NamingOptions(); + return new VideoListResolver(options); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs new file mode 100644 index 0000000000..5faef0e3db --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs @@ -0,0 +1,478 @@ +using Emby.Naming.Common; +using Emby.Naming.Video; +using MediaBrowser.Model.IO; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class StackTests : BaseVideoTest + { + [Fact] + public void TestSimpleStack() + { + var files = new[] + { + "Bad Boys (2006) part1.mkv", + "Bad Boys (2006) part2.mkv", + "Bad Boys (2006) part3.mkv", + "Bad Boys (2006) part4.mkv", + "Bad Boys (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "Bad Boys (2006)", 4); + } + + [Fact] + public void TestFalsePositives() + { + var files = new[] + { + "Bad Boys (2006).mkv", + "Bad Boys (2007).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestFalsePositives2() + { + var files = new[] + { + "Bad Boys 2006.mkv", + "Bad Boys 2007.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestFalsePositives3() + { + var files = new[] + { + "300 (2006).mkv", + "300 (2007).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestFalsePositives4() + { + var files = new[] + { + "300 2006.mkv", + "300 2007.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestFalsePositives5() + { + var files = new[] + { + "Star Trek 1 - The motion picture.mkv", + "Star Trek 2- The wrath of khan.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestFalsePositives6() + { + var files = new[] + { + "Red Riding in the Year of Our Lord 1983 (2009).mkv", + "Red Riding in the Year of Our Lord 1980 (2009).mkv", + "Red Riding in the Year of Our Lord 1974 (2009).mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestStackName() + { + var files = new[] + { + "d:/movies/300 2006 part1.mkv", + "d:/movies/300 2006 part2.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "300 2006", 2); + } + + [Fact] + public void TestDirtyNames() + { + var files = new[] + { + "Bad Boys (2006).part1.stv.unrated.multi.1080p.bluray.x264-rough.mkv", + "Bad Boys (2006).part2.stv.unrated.multi.1080p.bluray.x264-rough.mkv", + "Bad Boys (2006).part3.stv.unrated.multi.1080p.bluray.x264-rough.mkv", + "Bad Boys (2006).part4.stv.unrated.multi.1080p.bluray.x264-rough.mkv", + "Bad Boys (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "Bad Boys (2006).stv.unrated.multi.1080p.bluray.x264-rough", 4); + } + + [Fact] + public void TestNumberedFiles() + { + var files = new[] + { + "Bad Boys (2006).mkv", + "Bad Boys (2006) 1.mkv", + "Bad Boys (2006) 2.mkv", + "Bad Boys (2006) 3.mkv", + "Bad Boys (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestSimpleStackWithNumericName() + { + var files = new[] + { + "300 (2006) part1.mkv", + "300 (2006) part2.mkv", + "300 (2006) part3.mkv", + "300 (2006) part4.mkv", + "300 (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "300 (2006)", 4); + } + + [Fact] + public void TestMixedExpressionsNotAllowed() + { + var files = new[] + { + "Bad Boys (2006) part1.mkv", + "Bad Boys (2006) part2.mkv", + "Bad Boys (2006) part3.mkv", + "Bad Boys (2006) parta.mkv", + "Bad Boys (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "Bad Boys (2006)", 3); + } + + [Fact] + public void TestDualStacks() + { + var files = new[] + { + "Bad Boys (2006) part1.mkv", + "Bad Boys (2006) part2.mkv", + "Bad Boys (2006) part3.mkv", + "Bad Boys (2006) part4.mkv", + "Bad Boys (2006)-trailer.mkv", + "300 (2006) part1.mkv", + "300 (2006) part2.mkv", + "300 (2006) part3.mkv", + "300 (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Equal(2, result.Stacks.Count); + TestStackInfo(result.Stacks[1], "Bad Boys (2006)", 4); + TestStackInfo(result.Stacks[0], "300 (2006)", 3); + } + + [Fact] + public void TestDirectories() + { + var files = new[] + { + "blah blah - cd 1", + "blah blah - cd 2" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveDirectories(files); + + Assert.Single(result.Stacks); + TestStackInfo(result.Stacks[0], "blah blah", 2); + } + + [Fact] + public void TestFalsePositive() + { + var files = new[] + { + "300a.mkv", + "300b.mkv", + "300c.mkv", + "300-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + + TestStackInfo(result.Stacks[0], "300", 3); + } + + [Fact] + public void TestFailSequence() + { + var files = new[] + { + "300 part1.mkv", + "300 part2.mkv", + "Avatar", + "Avengers part1.mkv", + "Avengers part2.mkv", + "Avengers part3.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Equal(2, result.Stacks.Count); + + TestStackInfo(result.Stacks[0], "300", 2); + TestStackInfo(result.Stacks[1], "Avengers", 3); + } + + [Fact] + public void TestMixedExpressions() + { + var files = new[] + { + "Bad Boys (2006) part1.mkv", + "Bad Boys (2006) part2.mkv", + "Bad Boys (2006) part3.mkv", + "Bad Boys (2006) part4.mkv", + "Bad Boys (2006)-trailer.mkv", + "300 (2006) parta.mkv", + "300 (2006) partb.mkv", + "300 (2006) partc.mkv", + "300 (2006) partd.mkv", + "300 (2006)-trailer.mkv", + "300a.mkv", + "300b.mkv", + "300c.mkv", + "300-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Equal(3, result.Stacks.Count); + + TestStackInfo(result.Stacks[0], "300 (2006)", 4); + TestStackInfo(result.Stacks[1], "300", 3); + TestStackInfo(result.Stacks[2], "Bad Boys (2006)", 4); + } + + [Fact] + public void TestAlphaLimitOfFour() + { + var files = new[] + { + "300 (2006) parta.mkv", + "300 (2006) partb.mkv", + "300 (2006) partc.mkv", + "300 (2006) partd.mkv", + "300 (2006) parte.mkv", + "300 (2006) partf.mkv", + "300 (2006) partg.mkv", + "300 (2006)-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + + TestStackInfo(result.Stacks[0], "300 (2006)", 4); + } + + [Fact] + public void TestMixed() + { + var files = new[] + { + new FileSystemMetadata{FullName = "Bad Boys (2006) part1.mkv", IsDirectory = false}, + new FileSystemMetadata{FullName = "Bad Boys (2006) part2.mkv", IsDirectory = false}, + new FileSystemMetadata{FullName = "300 (2006) part2", IsDirectory = true}, + new FileSystemMetadata{FullName = "300 (2006) part3", IsDirectory = true}, + new FileSystemMetadata{FullName = "300 (2006) part1", IsDirectory = true} + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files); + + Assert.Equal(2, result.Stacks.Count); + TestStackInfo(result.Stacks[0], "300 (2006)", 3); + TestStackInfo(result.Stacks[1], "Bad Boys (2006)", 2); + } + + [Fact] + public void TestDirectories2() + { + //TestDirectory(@"blah blah", false, @"blah blah"); + //TestDirectory(@"d:/music/weezer/03 Pinkerton", false, "03 Pinkerton"); + //TestDirectory(@"d:/music/michael jackson/Bad (2012 Remaster)", false, "Bad (2012 Remaster)"); + + //TestDirectory(@"blah blah - cd1", true, "blah blah"); + //TestDirectory(@"blah blah - disc1", true, "blah blah"); + //TestDirectory(@"blah blah - disk1", true, "blah blah"); + //TestDirectory(@"blah blah - pt1", true, "blah blah"); + //TestDirectory(@"blah blah - part1", true, "blah blah"); + //TestDirectory(@"blah blah - dvd1", true, "blah blah"); + + //// Add a space + //TestDirectory(@"blah blah - cd 1", true, "blah blah"); + //TestDirectory(@"blah blah - disc 1", true, "blah blah"); + //TestDirectory(@"blah blah - disk 1", true, "blah blah"); + //TestDirectory(@"blah blah - pt 1", true, "blah blah"); + //TestDirectory(@"blah blah - part 1", true, "blah blah"); + //TestDirectory(@"blah blah - dvd 1", true, "blah blah"); + + //// Not case sensitive + //TestDirectory(@"blah blah - Disc1", true, "blah blah"); + } + + [Fact] + public void TestNamesWithoutParts() + { + // No stacking here because there is no part/disc/etc + var files = new[] + { + "Harry Potter and the Deathly Hallows.mkv", + "Harry Potter and the Deathly Hallows 1.mkv", + "Harry Potter and the Deathly Hallows 2.mkv", + "Harry Potter and the Deathly Hallows 3.mkv", + "Harry Potter and the Deathly Hallows 4.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Empty(result.Stacks); + } + + [Fact] + public void TestNumbersAppearingBeforePartNumber() + { + // No stacking here because there is no part/disc/etc + var files = new[] + { + "Neverland (2011)[720p][PG][Voted 6.5][Family-Fantasy]part1.mkv", + "Neverland (2011)[720p][PG][Voted 6.5][Family-Fantasy]part2.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveFiles(files); + + Assert.Single(result.Stacks); + Assert.Equal(2, result.Stacks[0].Files.Count); + } + + [Fact] + public void TestMultiDiscs() + { + // No stacking here because there is no part/disc/etc + var files = new[] + { + @"M:/Movies (DVD)/Movies (Musical)/The Sound of Music/The Sound of Music (1965) (Disc 01)", + @"M:/Movies (DVD)/Movies (Musical)/The Sound of Music/The Sound of Music (1965) (Disc 02)" + }; + + var resolver = GetResolver(); + + var result = resolver.ResolveDirectories(files); + + Assert.Single(result.Stacks); + Assert.Equal(2, result.Stacks[0].Files.Count); + } + + private void TestStackInfo(FileStack stack, string name, int fileCount) + { + Assert.Equal(fileCount, stack.Files.Count); + Assert.Equal(name, stack.Name); + } + + private StackResolver GetResolver() + { + return new StackResolver(new NamingOptions()); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/StubTests.cs b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs new file mode 100644 index 0000000000..96fa8c5a55 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs @@ -0,0 +1,55 @@ +using System; +using System.Globalization; +using Emby.Naming.Common; +using Emby.Naming.Video; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class StubTests : BaseVideoTest + { + [Fact] + public void TestStubs() + { + Test("video.mkv", false, null); + Test("video.disc", true, null); + Test("video.dvd.disc", true, "dvd"); + Test("video.hddvd.disc", true, "hddvd"); + Test("video.bluray.disc", true, "bluray"); + Test("video.brrip.disc", true, "bluray"); + Test("video.bd25.disc", true, "bluray"); + Test("video.bd50.disc", true, "bluray"); + Test("video.vhs.disc", true, "vhs"); + Test("video.hdtv.disc", true, "tv"); + Test("video.pdtv.disc", true, "tv"); + Test("video.dsr.disc", true, "tv"); + } + + [Fact] + public void TestStubName() + { + var result = + GetParser().ResolveFile(@"C:/Users/media/Desktop/Video Test/Movies/Oblivion/Oblivion.dvd.disc"); + + Assert.Equal("Oblivion", result.Name); + } + + private void Test(string path, bool isStub, string stubType) + { + var options = new NamingOptions(); + + var resultStubType = StubResolver.ResolveFile(path, options); + + Assert.Equal(isStub, resultStubType.IsStub); + + if (stubType == null) + { + Assert.Null(resultStubType.StubType); + } + else + { + Assert.Equal(stubType, resultStubType.StubType, true); + } + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs new file mode 100644 index 0000000000..ef8a178989 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs @@ -0,0 +1,457 @@ +using System.Linq; +using Emby.Naming.Common; +using Emby.Naming.Video; +using MediaBrowser.Model.IO; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class VideoListResolverTests + { + // FIXME + // [Fact] + public void TestStackAndExtras() + { + // No stacking here because there is no part/disc/etc + var files = new[] + { + "Harry Potter and the Deathly Hallows-trailer.mkv", + "Harry Potter and the Deathly Hallows.trailer.mkv", + "Harry Potter and the Deathly Hallows part1.mkv", + "Harry Potter and the Deathly Hallows part2.mkv", + "Harry Potter and the Deathly Hallows part3.mkv", + "Harry Potter and the Deathly Hallows part4.mkv", + "Batman-deleted.mkv", + "Batman-sample.mkv", + "Batman-trailer.mkv", + "Batman part1.mkv", + "Batman part2.mkv", + "Batman part3.mkv", + "Avengers.mkv", + "Avengers-trailer.mkv", + + // Despite having a keyword in the name that will return an ExtraType, there's no original video to match it to + // So this is just a standalone video + "trailer.mkv", + + // Same as above + "WillyWonka-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(5, result.Count); + + Assert.Equal(3, result[1].Files.Count); + Assert.Equal(3, result[1].Extras.Count); + Assert.Equal("Batman", result[1].Name); + + Assert.Equal(4, result[2].Files.Count); + Assert.Equal(2, result[2].Extras.Count); + Assert.Equal("Harry Potter and the Deathly Hallows", result[2].Name); + } + + [Fact] + public void TestWithMetadata() + { + var files = new[] + { + "300.mkv", + "300.nfo" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestWithExtra() + { + var files = new[] + { + "300.mkv", + "300 trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestVariationWithFolderName() + { + var files = new[] + { + "X-Men Days of Future Past - 1080p.mkv", + "X-Men Days of Future Past-trailer.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestTrailer2() + { + var files = new[] + { + "X-Men Days of Future Past - 1080p.mkv", + "X-Men Days of Future Past-trailer.mp4", + "X-Men Days of Future Past-trailer2.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestDifferentNames() + { + var files = new[] + { + "Looper (2012)-trailer.mkv", + "Looper.2012.bluray.720p.x264.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestSeparateFiles() + { + // These should be considered separate, unrelated videos + var files = new[] + { + "My video 1.mkv", + "My video 2.mkv", + "My video 3.mkv", + "My video 4.mkv", + "My video 5.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(5, result.Count); + } + + [Fact] + public void TestMultiDisc() + { + var files = new[] + { + @"M:/Movies (DVD)/Movies (Musical)/Sound of Music (1965)/Sound of Music Disc 1", + @"M:/Movies (DVD)/Movies (Musical)/Sound of Music (1965)/Sound of Music Disc 2" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = true, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestPoundSign() + { + // These should be considered separate, unrelated videos + var files = new[] + { + @"My movie #1.mp4", + @"My movie #2.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = true, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(2, result.Count); + } + + [Fact] + public void TestStackedWithTrailer() + { + var files = new[] + { + @"No (2012) part1.mp4", + @"No (2012) part2.mp4", + @"No (2012) part1-trailer.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestStackedWithTrailer2() + { + var files = new[] + { + @"No (2012) part1.mp4", + @"No (2012) part2.mp4", + @"No (2012)-trailer.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestExtrasByFolderName() + { + var files = new[] + { + @"/Movies/Top Gun (1984)/movie.mp4", + @"/Movies/Top Gun (1984)/Top Gun (1984)-trailer.mp4", + @"/Movies/Top Gun (1984)/Top Gun (1984)-trailer2.mp4", + @"trailer.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestDoubleTags() + { + var files = new[] + { + @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Counterfeit Racks (2011) Disc 1 cd1.avi", + @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Counterfeit Racks (2011) Disc 1 cd2.avi", + @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Disc 2 cd1.avi", + @"/MCFAMILY-PC/Private3$/Heterosexual/Breast In Class 2 Counterfeit Racks (2011)/Breast In Class 2 Disc 2 cd2.avi" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(2, result.Count); + } + + [Fact] + public void TestArgumentOutOfRangeException() + { + var files = new[] + { + @"/nas-markrobbo78/Videos/INDEX HTPC/Movies/Watched/3 - ACTION/Argo (2012)/movie.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestColony() + { + var files = new[] + { + @"The Colony.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestFourSisters() + { + var files = new[] + { + @"Four Sisters and a Wedding - A.avi", + @"Four Sisters and a Wedding - B.avi" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestMovieTrailer() + { + var files = new[] + { + @"/Server/Despicable Me/Despicable Me (2010).mkv", + @"/Server/Despicable Me/movie-trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestTrailerFalsePositives() + { + var files = new[] + { + @"/Server/Despicable Me/Skyscraper (2018) - Big Game Spot.mkv", + @"/Server/Despicable Me/Skyscraper (2018) - Trailer.mkv", + @"/Server/Despicable Me/Baywatch (2017) - Big Game Spot.mkv", + @"/Server/Despicable Me/Baywatch (2017) - Trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Equal(4, result.Count); + } + + [Fact] + public void TestSubfolders() + { + var files = new[] + { + @"/Movies/Despicable Me/Despicable Me.mkv", + @"/Movies/Despicable Me/trailers/trailer.mkv" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + + }).ToList()).ToList(); + + Assert.Single(result); + } + + private VideoListResolver GetResolver() + { + var options = new NamingOptions(); + return new VideoListResolver(options); + } + } +} diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs new file mode 100644 index 0000000000..5a3ce88869 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -0,0 +1,275 @@ +using MediaBrowser.Model.Entities; +using Xunit; + +namespace Jellyfin.Naming.Tests.Video +{ + public class VideoResolverTests : BaseVideoTest + { + // FIXME + // [Fact] + public void TestSimpleFile() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/Brave (2007)/Brave (2006).mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("Brave", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestSimpleFile2() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/Bad Boys (1995)/Bad Boys (1995).mkv"); + + Assert.Equal(1995, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("Bad Boys", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestSimpleFileWithNumericName() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006).mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("300", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestExtra() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/Brave (2007)/Brave (2006)-trailer.mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal(ExtraType.Trailer, result.ExtraType); + Assert.Equal("Brave (2006)-trailer", result.Name); + } + + // FIXME + // [Fact] + public void TestExtraWithNumericName() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006)-trailer.mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("300 (2006)-trailer", result.Name); + Assert.Equal(ExtraType.Trailer, result.ExtraType); + } + + // FIXME + // [Fact] + public void TestStubFileWithNumericName() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006).bluray.disc"); + + Assert.Equal(2006, result.Year); + Assert.True(result.IsStub); + Assert.Equal("bluray", result.StubType); + Assert.False(result.Is3D); + Assert.Equal("300", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestStubFile() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/Brave (2007)/Brave (2006).bluray.disc"); + + Assert.Equal(2006, result.Year); + Assert.True(result.IsStub); + Assert.Equal("bluray", result.StubType); + Assert.False(result.Is3D); + Assert.Equal("Brave", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestExtraStubWithNumericNameNotSupported() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006)-trailer.bluray.disc"); + + Assert.Equal(2006, result.Year); + Assert.True(result.IsStub); + Assert.Equal("bluray", result.StubType); + Assert.False(result.Is3D); + Assert.Equal("300", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestExtraStubNotSupported() + { + // Using a stub for an extra is currently not supported + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/brave (2007)/brave (2006)-trailer.bluray.disc"); + + Assert.Equal(2006, result.Year); + Assert.True(result.IsStub); + Assert.Equal("bluray", result.StubType); + Assert.False(result.Is3D); + Assert.Equal("brave", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void Test3DFileWithNumericName() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006).3d.sbs.mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.True(result.Is3D); + Assert.Equal("sbs", result.Format3D); + Assert.Equal("300", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestBad3DFileWithNumericName() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/300 (2007)/300 (2006).3d1.sbas.mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("300", result.Name); + Assert.Null(result.ExtraType); + Assert.Null(result.Format3D); + } + + // FIXME + // [Fact] + public void Test3DFile() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/brave (2007)/brave (2006).3d.sbs.mkv"); + + Assert.Equal(2006, result.Year); + Assert.False(result.IsStub); + Assert.True(result.Is3D); + Assert.Equal("sbs", result.Format3D); + Assert.Equal("brave", result.Name); + Assert.Null(result.ExtraType); + } + + [Fact] + public void TestNameWithoutDate() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/American Psycho/American.Psycho.mkv"); + + Assert.Null(result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Null(result.Format3D); + Assert.Equal("American.Psycho", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestCleanDateAndStringsSequence() + { + var parser = GetParser(); + + // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again + var result = + parser.ResolveFile(@"/server/Movies/3.Days.to.Kill/3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv"); + + Assert.Equal(2014, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Null(result.Format3D); + Assert.Equal("3.Days.to.Kill", result.Name); + Assert.Null(result.ExtraType); + } + + // FIXME + // [Fact] + public void TestCleanDateAndStringsSequence1() + { + var parser = GetParser(); + + // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again + var result = + parser.ResolveFile(@"/server/Movies/3 days to kill (2005)/3 days to kill (2005).mkv"); + + Assert.Equal(2005, result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Null(result.Format3D); + Assert.Equal("3 days to kill", result.Name); + Assert.Null(result.ExtraType); + } + + [Fact] + public void TestFolderNameWithExtension() + { + var parser = GetParser(); + + var result = + parser.ResolveFile(@"/server/Movies/7 Psychos.mkv/7 Psychos.mkv"); + + Assert.Null(result.Year); + Assert.False(result.IsStub); + Assert.False(result.Is3D); + Assert.Equal("7 Psychos", result.Name); + Assert.Null(result.ExtraType); + } + } +} From 2ef4ffd698fb4ae95754f76238e52cfb6162db24 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 11 Dec 2019 00:13:57 +0100 Subject: [PATCH 003/108] More warnings (removed) --- Emby.Naming/Emby.Naming.csproj | 2 +- Emby.Photos/Emby.Photos.csproj | 7 +- .../Activity/ActivityLogEntryPoint.cs | 1 + .../Activity/ActivityManager.cs | 1 + .../Activity/ActivityRepository.cs | 1 + .../ApplicationHost.cs | 13 +- .../Branding/BrandingConfigurationFactory.cs | 1 + .../ChannelDynamicMediaSourceProvider.cs | 1 + .../Channels/ChannelImageProvider.cs | 1 + .../Channels/ChannelManager.cs | 1 + .../Channels/ChannelPostScanTask.cs | 1 + .../Channels/RefreshChannelsScheduledTask.cs | 1 + .../Collections/CollectionImageProvider.cs | 1 + .../Collections/CollectionManager.cs | 1 + .../Cryptography/CryptographyProvider.cs | 2 +- .../Data/BaseSqliteRepository.cs | 1 + .../Data/CleanDatabaseScheduledTask.cs | 1 + .../Data/ManagedConnection.cs | 1 + .../SqliteDisplayPreferencesRepository.cs | 1 + .../Data/SqliteExtensions.cs | 1 + .../Data/SqliteUserDataRepository.cs | 1 + .../Data/SqliteUserRepository.cs | 1 + .../Devices/DeviceId.cs | 1 + .../Devices/DeviceManager.cs | 1 + .../Diagnostics/CommonProcess.cs | 1 + .../Diagnostics/ProcessFactory.cs | 1 + Emby.Server.Implementations/Dto/DtoService.cs | 1 + .../Emby.Server.Implementations.csproj | 16 +- .../EntryPoints/AutomaticRestartEntryPoint.cs | 1 + .../EntryPoints/ExternalPortForwarding.cs | 1 + .../EntryPoints/LibraryChangedNotifier.cs | 1 + .../EntryPoints/RecordingNotifier.cs | 1 + .../EntryPoints/UserDataChangeNotifier.cs | 1 + .../HttpServer/FileWriter.cs | 1 + .../HttpServer/HttpListenerHost.cs | 2 +- .../HttpServer/HttpResultFactory.cs | 1 + .../HttpServer/IHttpListener.cs | 1 + .../HttpServer/RangeRequestWriter.cs | 1 + .../HttpServer/Security/AuthService.cs | 1 + .../Security/AuthorizationContext.cs | 1 + .../HttpServer/Security/SessionContext.cs | 1 + .../IO/ExtendedFileSystemInfo.cs | 1 + .../IO/FileRefresher.cs | 1 + .../IO/LibraryMonitor.cs | 1 + .../IO/ManagedFileSystem.cs | 1 + .../IO/MbLinkShortcutHandler.cs | 1 + .../IO/StreamHelper.cs | 1 + .../Images/BaseDynamicImageProvider.cs | 1 + .../Library/DefaultAuthenticationProvider.cs | 13 +- .../Library/ExclusiveLiveStream.cs | 1 + .../Library/LibraryManager.cs | 1 + .../Library/LiveStreamHelper.cs | 1 + .../Library/MediaSourceManager.cs | 1 + .../Library/MediaStreamSelector.cs | 1 + .../Library/MusicManager.cs | 1 + .../Library/Resolvers/Audio/AudioResolver.cs | 1 + .../Library/Resolvers/BaseVideoResolver.cs | 1 + .../Library/Resolvers/Books/BookResolver.cs | 1 + .../Library/Resolvers/PhotoResolver.cs | 1 + .../Library/Resolvers/PlaylistResolver.cs | 1 + .../Resolvers/SpecialFolderResolver.cs | 1 + .../Library/Resolvers/TV/SeriesResolver.cs | 1 + .../Library/Resolvers/VideoResolver.cs | 1 + .../Library/SearchEngine.cs | 1 + .../Library/UserDataManager.cs | 1 + .../Library/UserManager.cs | 3 +- .../Library/UserViewManager.cs | 1 + Jellyfin.Api/Jellyfin.Api.csproj | 2 +- Jellyfin.Server/Jellyfin.Server.csproj | 14 +- .../ConfigurationUpdateEventArgs.cs | 1 + .../Configuration/IConfigurationFactory.cs | 1 + .../Configuration/IConfigurationManager.cs | 1 + .../Cryptography/PasswordHash.cs | 25 +-- MediaBrowser.Common/Events/EventHelper.cs | 8 +- .../Extensions/BaseExtensions.cs | 7 +- .../Extensions/CopyToExtensions.cs | 4 +- .../Extensions/MethodNotAllowedException.cs | 26 +++ .../Extensions/RateLimitExceededException.cs | 26 +++ .../Extensions/ResourceNotFoundException.cs | 65 +------- MediaBrowser.Common/Hex.cs | 12 +- MediaBrowser.Common/IApplicationHost.cs | 55 ++++--- .../MediaBrowser.Common.csproj | 17 +- MediaBrowser.Common/Net/CustomHeaderNames.cs | 1 + MediaBrowser.Common/Net/HttpRequestOptions.cs | 28 ++-- MediaBrowser.Common/Net/HttpResponseInfo.cs | 32 ++-- MediaBrowser.Common/Net/IHttpClient.cs | 4 +- MediaBrowser.Common/Net/INetworkManager.cs | 11 +- MediaBrowser.Common/Plugins/BasePlugin.cs | 150 +++++++++--------- MediaBrowser.Common/Plugins/IPlugin.cs | 29 ++-- .../Plugins/IPluginAssembly.cs | 14 ++ .../Progress/ActionableProgress.cs | 1 + .../Providers/SubtitleConfigurationFactory.cs | 1 + MediaBrowser.Common/System/OperatingSystem.cs | 1 + .../Updates/IInstallationManager.cs | 10 +- .../Updates/InstallationEventArgs.cs | 1 + .../Updates/InstallationFailedEventArgs.cs | 1 + .../Authentication/AuthenticationResult.cs | 7 +- MediaBrowser.Controller/Entities/BaseItem.cs | 1 - jellyfin.ruleset | 12 +- 99 files changed, 394 insertions(+), 291 deletions(-) create mode 100644 MediaBrowser.Common/Extensions/MethodNotAllowedException.cs create mode 100644 MediaBrowser.Common/Extensions/RateLimitExceededException.cs create mode 100644 MediaBrowser.Common/Plugins/IPluginAssembly.cs diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 7258beaf49..3be5bbbaf1 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -23,7 +23,7 @@ - + diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index 64692c3703..d3c87edffe 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -22,9 +22,10 @@ - - - + + + + diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index b622a31674..ac8af66a20 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs index a30e939121..b03c4d1824 100644 --- a/Emby.Server.Implementations/Activity/ActivityManager.cs +++ b/Emby.Server.Implementations/Activity/ActivityManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Linq; diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index 7be72319ea..633343bb6d 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 8c625539ab..ae979682e6 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; @@ -180,11 +181,7 @@ namespace Emby.Server.Implementations /// Gets the plugins. /// /// The plugins. - public IPlugin[] Plugins - { - get => _plugins; - protected set => _plugins = value; - } + public IReadOnlyList Plugins => _plugins; /// /// Gets or sets the logger factory. @@ -1051,7 +1048,7 @@ namespace Emby.Server.Implementations } ConfigurationManager.AddParts(GetExports()); - Plugins = GetExports() + _plugins = GetExports() .Select(LoadPlugin) .Where(i => i != null) .ToArray(); @@ -1683,9 +1680,9 @@ namespace Emby.Server.Implementations /// The plugin. public void RemovePlugin(IPlugin plugin) { - var list = Plugins.ToList(); + var list = _plugins.ToList(); list.Remove(plugin); - Plugins = list.ToArray(); + _plugins = list.ToArray(); } /// diff --git a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs index 93000ae127..15aee63a05 100644 --- a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs +++ b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System.Collections.Generic; using MediaBrowser.Common.Configuration; diff --git a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs index 6016fed079..aae416b374 100644 --- a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs +++ b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs index 62aeb9bcb9..fe64f1b157 100644 --- a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs +++ b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System.Collections.Generic; using System.Linq; diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 6e1baddfed..de2e123af3 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs index 2712fc8c5e..36e0e5e26d 100644 --- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Linq; diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs index 5774c04153..039e2c1383 100644 --- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs index 1fa556ec95..8006b86948 100644 --- a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs +++ b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 2b8a5bdc56..5a25b5d3e6 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 776074b728..de83b023d7 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.Cryptography /// /// Releases unmanaged and - optionally - managed resources. /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 0654132f41..b7f6438193 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs index 2a8f2d6b33..8a5387e9b4 100644 --- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs +++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Threading; diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs index 5c094ddd2d..2c2f19cd30 100644 --- a/Emby.Server.Implementations/Data/ManagedConnection.cs +++ b/Emby.Server.Implementations/Data/ManagedConnection.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index d474f1c6ba..8087419ceb 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index c87793072e..55c24ccc05 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 22955850ab..f6c37e4e5b 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index a042320c91..c82c93ffc3 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index f0d43e665b..ff75efa592 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Globalization; diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index 2393f1f458..ef73170506 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs index bfa49ac5ff..f8b7541515 100644 --- a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs +++ b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Diagnostics; diff --git a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs index 02ad3c1a89..219f73c785 100644 --- a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs +++ b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using MediaBrowser.Model.Diagnostics; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 3d622b3fce..fcf0360c79 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index fde4d70599..5ca5087765 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -29,10 +29,10 @@ - - - - + + + + @@ -52,10 +52,10 @@ - - - - + + + + diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs index d69b0909dd..a6eb1152fb 100644 --- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Linq; diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index e290c62e16..4e4ef3be01 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index 5f938e59a8..f85d52dbc1 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index dbb3503c41..e0aa18e895 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Linq; diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index e431da1481..3e22080fc0 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs index c1c8c3eb30..1795651fd7 100644 --- a/Emby.Server.Implementations/HttpServer/FileWriter.cs +++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 2aefc9fe5d..b0126f7fa5 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; @@ -218,7 +219,6 @@ namespace Emby.Server.Implementations.HttpServer case FileNotFoundException _: case ResourceNotFoundException _: return 404; case MethodNotAllowedException _: return 405; - case RemoteServiceUnavailableException _: return 502; default: return 500; } } diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index a62b4e7aff..cefcaa835f 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/HttpServer/IHttpListener.cs b/Emby.Server.Implementations/HttpServer/IHttpListener.cs index 5015937256..1c3496e5d5 100644 --- a/Emby.Server.Implementations/HttpServer/IHttpListener.cs +++ b/Emby.Server.Implementations/HttpServer/IHttpListener.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Threading; diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index 8b9028f6bc..7cb113a58c 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 58421aaf19..03b5b748df 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Linq; diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 129faeaab0..e8884bca04 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index 166952c646..a6a0f5b032 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs index 3150f3367c..5be1444525 100644 --- a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs +++ b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Server.Implementations.IO { diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 4b5b11f01f..cf92ddbcd7 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index b1fb8cc635..7777efc3b1 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 442fbabd17..d8da0888e4 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs index e6696b8c4c..574b63ae63 100644 --- a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs +++ b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.IO; diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs index 40b397edc2..c99018e40c 100644 --- a/Emby.Server.Implementations/IO/StreamHelper.cs +++ b/Emby.Server.Implementations/IO/StreamHelper.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Buffers; diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs index fd50f156af..acf3a3b231 100644 --- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs index 94f60ea621..ab036eca7a 100644 --- a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs +++ b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs @@ -70,9 +70,9 @@ namespace Emby.Server.Implementations.Library byte[] calculatedHash = _cryptographyProvider.ComputeHash( readyHash.Id, passwordbytes, - readyHash.Salt); + readyHash.Salt.ToArray()); - if (calculatedHash.SequenceEqual(readyHash.Hash)) + if (readyHash.Hash.SequenceEqual(calculatedHash)) { success = true; } @@ -148,17 +148,18 @@ namespace Emby.Server.Implementations.Library // 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), - passwordHash.Salt), - passwordHash.Salt, + salt), + salt, passwordHash.Parameters.ToDictionary(x => x.Key, y => y.Value)).ToString(); } - public byte[] GetHashed(User user, string str) + public ReadOnlySpan GetHashed(User user, string str) { if (string.IsNullOrEmpty(user.Password)) { @@ -170,7 +171,7 @@ namespace Emby.Server.Implementations.Library return _cryptographyProvider.ComputeHash( passwordHash.Id, Encoding.UTF8.GetBytes(str), - passwordHash.Salt); + passwordHash.Salt.ToArray()); } } } diff --git a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs index 9a71868988..3eb64c29c6 100644 --- a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs +++ b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Globalization; diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 6942088fe8..d8ef8192ac 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index ed7d8aa402..f28f4a538f 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 22193c997e..0899832a72 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs index 6b9f4d052c..1652ad9747 100644 --- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs +++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs index 1ec5783716..29af6670b4 100644 --- a/Emby.Server.Implementations/Library/MusicManager.cs +++ b/Emby.Server.Implementations/Library/MusicManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 9d4bd9e593..7e3b27a123 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index c4bb861b8d..43302bb3fe 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.IO; diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs index 0b93ebeb81..1e2e0704c1 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.IO; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index a71ae82502..e1eb23652d 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs index a68562fc2c..5e672f221a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.IO; diff --git a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs index 1030ed39d2..eca60b1336 100644 --- a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.IO; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 7cc9eabc8e..e39d85bc9b 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs index 62268fce90..6404d64762 100644 --- a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 11d6c737ac..76ae147206 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 48d33c26c1..5d4f17861e 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index 85bfa154af..c7f6de24f9 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Concurrent; @@ -480,7 +481,7 @@ namespace Emby.Server.Implementations.Library var hash = _cryptoProvider.ComputeHash( passwordHash.Id, Encoding.UTF8.GetBytes(password), - passwordHash.Salt); + passwordHash.Salt.ToArray()); success = passwordHash.Hash.SequenceEqual(hash); } diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index 322819b052..935deb71cc 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index a2818b45da..f4e5337de2 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -19,7 +19,7 @@ - + diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 110028176c..63410f6060 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -24,13 +24,13 @@ - + - - - - + + + + @@ -39,8 +39,8 @@ - - + + diff --git a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs index 344aecf530..828415c185 100644 --- a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs +++ b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; diff --git a/MediaBrowser.Common/Configuration/IConfigurationFactory.cs b/MediaBrowser.Common/Configuration/IConfigurationFactory.cs index 4c4060096d..9b4ed772db 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationFactory.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationFactory.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index caf2edd836..7773596afe 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index 19b8be47a9..3477c1c041 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; @@ -15,24 +16,24 @@ namespace MediaBrowser.Common.Cryptography public class PasswordHash { private readonly Dictionary _parameters; + private readonly byte[] _salt; + private readonly byte[] _hash; public PasswordHash(string id, byte[] hash) : this(id, hash, Array.Empty()) { - } public PasswordHash(string id, byte[] hash, byte[] salt) : this(id, hash, salt, new Dictionary()) { - } public PasswordHash(string id, byte[] hash, byte[] salt, Dictionary parameters) { Id = id; - Hash = hash; - Salt = salt; + _hash = hash; + _salt = salt; _parameters = parameters; } @@ -45,25 +46,24 @@ namespace MediaBrowser.Common.Cryptography /// /// Gets the additional parameters used by the hash function. /// - /// public IReadOnlyDictionary Parameters => _parameters; /// /// Gets the salt used for hashing the password. /// /// Returns the salt used for hashing the password. - public byte[] Salt { get; } + public ReadOnlySpan Salt => _salt; /// /// Gets the hashed password. /// /// Return the hashed password. - public byte[] Hash { get; } + public ReadOnlySpan Hash => _hash; public static PasswordHash Parse(string hashString) { - string[] splitted = hashString.Split('$'); // The string should at least contain the hash function and the hash itself + string[] splitted = hashString.Split('$'); if (splitted.Length < 3) { throw new ArgumentException("String doesn't contain enough segments", nameof(hashString)); @@ -77,7 +77,7 @@ namespace MediaBrowser.Common.Cryptography // Optional parameters Dictionary parameters = new Dictionary(); - if (splitted[index].IndexOf('=') != -1) + if (splitted[index].IndexOf('=', StringComparison.Ordinal) != -1) { foreach (string paramset in splitted[index++].Split(',')) { @@ -98,6 +98,7 @@ namespace MediaBrowser.Common.Cryptography byte[] hash; byte[] salt; + // Check if the string also contains a salt if (splitted.Length - index == 2) { @@ -141,14 +142,14 @@ namespace MediaBrowser.Common.Cryptography .Append(Id); SerializeParameters(str); - if (Salt.Length != 0) + if (_salt.Length != 0) { str.Append('$') - .Append(Hex.Encode(Salt, false)); + .Append(Hex.Encode(_salt, false)); } return str.Append('$') - .Append(Hex.Encode(Hash, false)).ToString(); + .Append(Hex.Encode(_hash, false)).ToString(); } } } diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs index b67315df62..c9d3226ac8 100644 --- a/MediaBrowser.Common/Events/EventHelper.cs +++ b/MediaBrowser.Common/Events/EventHelper.cs @@ -1,15 +1,13 @@ -#pragma warning disable CS1591 - using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace MediaBrowser.Common.Events { - // TODO: @bond Remove /// - /// Class EventHelper + /// Class EventHelper. /// + // TODO: @bond Remove public static class EventHelper { /// @@ -40,7 +38,7 @@ namespace MediaBrowser.Common.Events /// /// Queues the event. /// - /// + /// Argument type for the handler. /// The handler. /// The sender. /// The args. diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs index 33473c2be7..08964420e7 100644 --- a/MediaBrowser.Common/Extensions/BaseExtensions.cs +++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs @@ -1,12 +1,12 @@ using System; +using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; -using System.Security.Cryptography; namespace MediaBrowser.Common.Extensions { /// - /// Class BaseExtensions + /// Class BaseExtensions. /// public static class BaseExtensions { @@ -30,10 +30,13 @@ namespace MediaBrowser.Common.Extensions /// . public static Guid GetMD5(this string str) { +#pragma warning disable CA5351 using (var provider = MD5.Create()) { return new Guid(provider.ComputeHash(Encoding.Unicode.GetBytes(str))); } + +#pragma warning restore CA5351 } } } diff --git a/MediaBrowser.Common/Extensions/CopyToExtensions.cs b/MediaBrowser.Common/Extensions/CopyToExtensions.cs index 78a73f07e0..2ecbc6539b 100644 --- a/MediaBrowser.Common/Extensions/CopyToExtensions.cs +++ b/MediaBrowser.Common/Extensions/CopyToExtensions.cs @@ -5,7 +5,7 @@ namespace MediaBrowser.Common.Extensions /// /// Provides CopyTo extensions methods for . /// - public static class CollectionExtensions + public static class CopyToExtensions { /// /// Copies all the elements of the current collection to the specified list @@ -14,7 +14,7 @@ namespace MediaBrowser.Common.Extensions /// The current collection that is the source of the elements. /// The list that is the destination of the elements copied from the current collection. /// A 32-bit integer that represents the index in destination at which copying begins. - /// + /// The type of the array. public static void CopyTo(this IReadOnlyList source, IList destination, int index = 0) { for (int i = 0; i < source.Count; i++) diff --git a/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs new file mode 100644 index 0000000000..48e758ee4c --- /dev/null +++ b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs @@ -0,0 +1,26 @@ +using System; + +namespace MediaBrowser.Common.Extensions +{ + /// + /// Class MethodNotAllowedException. + /// + public class MethodNotAllowedException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public MethodNotAllowedException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public MethodNotAllowedException(string message) + : base(message) + { + } + } +} diff --git a/MediaBrowser.Common/Extensions/RateLimitExceededException.cs b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs new file mode 100644 index 0000000000..4e5d4e9ca8 --- /dev/null +++ b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs @@ -0,0 +1,26 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + +using System; + +namespace MediaBrowser.Common.Extensions +{ + public class RateLimitExceededException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public RateLimitExceededException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public RateLimitExceededException(string message) + : base(message) + { + } + } +} diff --git a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs index 9b064a40df..22130c5a1e 100644 --- a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs +++ b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs @@ -1,11 +1,9 @@ -#pragma warning disable CS1591 - using System; namespace MediaBrowser.Common.Extensions { /// - /// Class ResourceNotFoundException + /// Class ResourceNotFoundException. /// public class ResourceNotFoundException : Exception { @@ -14,7 +12,6 @@ namespace MediaBrowser.Common.Extensions /// public ResourceNotFoundException() { - } /// @@ -24,66 +21,6 @@ namespace MediaBrowser.Common.Extensions public ResourceNotFoundException(string message) : base(message) { - - } - } - - /// - /// Class MethodNotAllowedException - /// - public class MethodNotAllowedException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public MethodNotAllowedException() - { - - } - - /// - /// Initializes a new instance of the class. - /// - /// The message. - public MethodNotAllowedException(string message) - : base(message) - { - - } - } - - public class RemoteServiceUnavailableException : Exception - { - public RemoteServiceUnavailableException() - { - - } - - public RemoteServiceUnavailableException(string message) - : base(message) - { - - } - } - - public class RateLimitExceededException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public RateLimitExceededException() - { - - } - - /// - /// Initializes a new instance of the class. - /// - /// The message. - public RateLimitExceededException(string message) - : base(message) - { - } } } diff --git a/MediaBrowser.Common/Hex.cs b/MediaBrowser.Common/Hex.cs index b2d9aea3a7..863192809f 100644 --- a/MediaBrowser.Common/Hex.cs +++ b/MediaBrowser.Common/Hex.cs @@ -14,11 +14,11 @@ namespace MediaBrowser.Common internal const int LastHexSymbol = 0x66; // 102: f /// - /// Map from an ASCII char to its hex value shifted, + /// Gets an map from an ASCII char to its hex value shifted, /// e.g. b -> 11. 0xFF means it's not a hex symbol. /// - /// - internal static ReadOnlySpan HexLookup => new byte[] { + internal static ReadOnlySpan HexLookup => new byte[] + { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, @@ -29,10 +29,10 @@ namespace MediaBrowser.Common }; /// - /// Encodes bytes as a hex string. + /// Encodes each element of the specified bytes as its hexadecimal string representation. /// - /// - /// + /// An array of bytes. + /// true to use lowercase hexadecimal characters; otherwise false. /// bytes as a hex string. public static string Encode(ReadOnlySpan bytes, bool lowercase = true) { diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 6668e98aa5..68a24aabaa 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -8,10 +8,15 @@ using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common { /// - /// An interface to be implemented by the applications hosting a kernel + /// An interface to be implemented by the applications hosting a kernel. /// public interface IApplicationHost { + /// + /// Occurs when [has pending restart changed]. + /// + event EventHandler HasPendingRestartChanged; + /// /// Gets the name. /// @@ -25,13 +30,13 @@ namespace MediaBrowser.Common string SystemId { get; } /// - /// Gets or sets a value indicating whether this instance has pending kernel reload. + /// Gets a value indicating whether this instance has pending kernel reload. /// /// true if this instance has pending kernel reload; otherwise, false. bool HasPendingRestart { get; } /// - /// Gets or sets a value indicating whether this instance is currently shutting down. + /// Gets a value indicating whether this instance is currently shutting down. /// /// true if this instance is shutting down; otherwise, false. bool IsShuttingDown { get; } @@ -43,26 +48,11 @@ namespace MediaBrowser.Common bool CanSelfRestart { get; } /// - /// Get the version class of the system. + /// Gets the version class of the system. /// /// or . PackageVersionClass SystemUpdateLevel { get; } - /// - /// Occurs when [has pending restart changed]. - /// - event EventHandler HasPendingRestartChanged; - - /// - /// Notifies the pending restart. - /// - void NotifyPendingRestart(); - - /// - /// Restarts this instance. - /// - void Restart(); - /// /// Gets the application version. /// @@ -87,6 +77,22 @@ namespace MediaBrowser.Common /// string ApplicationUserAgentAddress { get; } + /// + /// Gets the plugins. + /// + /// The plugins. + IReadOnlyList Plugins { get; } + + /// + /// Notifies the pending restart. + /// + void NotifyPendingRestart(); + + /// + /// Restarts this instance. + /// + void Restart(); + /// /// Gets the exports. /// @@ -98,21 +104,16 @@ namespace MediaBrowser.Common /// /// Resolves this instance. /// - /// + /// The Type. /// ``0. T Resolve(); /// /// Shuts down. /// + /// A task. Task Shutdown(); - /// - /// Gets the plugins. - /// - /// The plugins. - IPlugin[] Plugins { get; } - /// /// Removes the plugin. /// @@ -122,6 +123,8 @@ namespace MediaBrowser.Common /// /// Inits this instance. /// + /// The service collection. + /// A task. Task InitAsync(IServiceCollection serviceCollection); /// diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 889fbfa5ab..567fcdda19 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -12,8 +12,8 @@ - - + + @@ -27,9 +27,16 @@ true - - - latest + + + + + + + + + + ../jellyfin.ruleset diff --git a/MediaBrowser.Common/Net/CustomHeaderNames.cs b/MediaBrowser.Common/Net/CustomHeaderNames.cs index 5ca9897eb4..8cc48c55f5 100644 --- a/MediaBrowser.Common/Net/CustomHeaderNames.cs +++ b/MediaBrowser.Common/Net/CustomHeaderNames.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 namespace MediaBrowser.Common.Net { diff --git a/MediaBrowser.Common/Net/HttpRequestOptions.cs b/MediaBrowser.Common/Net/HttpRequestOptions.cs index 18c4b181f5..8207a45f35 100644 --- a/MediaBrowser.Common/Net/HttpRequestOptions.cs +++ b/MediaBrowser.Common/Net/HttpRequestOptions.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; @@ -8,10 +9,21 @@ using Microsoft.Net.Http.Headers; namespace MediaBrowser.Common.Net { /// - /// Class HttpRequestOptions + /// Class HttpRequestOptions. /// public class HttpRequestOptions { + /// + /// Initializes a new instance of the class. + /// + public HttpRequestOptions() + { + RequestHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); + + CacheMode = CacheMode.None; + DecompressionMethod = CompressionMethod.Deflate; + } + /// /// Gets or sets the URL. /// @@ -71,14 +83,17 @@ namespace MediaBrowser.Common.Net public string RequestContentType { get; set; } public string RequestContent { get; set; } + public byte[] RequestContentBytes { get; set; } public bool BufferContent { get; set; } public bool LogErrorResponseBody { get; set; } + public bool EnableKeepAlive { get; set; } public CacheMode CacheMode { get; set; } + public TimeSpan CacheLength { get; set; } public bool EnableDefaultUserAgent { get; set; } @@ -89,17 +104,6 @@ namespace MediaBrowser.Common.Net return value; } - - /// - /// Initializes a new instance of the class. - /// - public HttpRequestOptions() - { - RequestHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - - CacheMode = CacheMode.None; - DecompressionMethod = CompressionMethod.Deflate; - } } public enum CacheMode diff --git a/MediaBrowser.Common/Net/HttpResponseInfo.cs b/MediaBrowser.Common/Net/HttpResponseInfo.cs index 0de034b0ee..d711ad64a4 100644 --- a/MediaBrowser.Common/Net/HttpResponseInfo.cs +++ b/MediaBrowser.Common/Net/HttpResponseInfo.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.IO; using System.Net; @@ -8,10 +6,25 @@ using System.Net.Http.Headers; namespace MediaBrowser.Common.Net { /// - /// Class HttpResponseInfo + /// Class HttpResponseInfo. /// public class HttpResponseInfo : IDisposable { +#pragma warning disable CS1591 +#pragma warning disable SA1600 + public HttpResponseInfo() + { + } + + public HttpResponseInfo(HttpResponseHeaders headers, HttpContentHeaders contentHeader) + { + Headers = headers; + ContentHeaders = contentHeader; + } + +#pragma warning restore CS1591 +#pragma warning restore SA1600 + /// /// Gets or sets the type of the content. /// @@ -60,21 +73,10 @@ namespace MediaBrowser.Common.Net /// The content headers. public HttpContentHeaders ContentHeaders { get; set; } - public HttpResponseInfo() - { - - } - - public HttpResponseInfo(HttpResponseHeaders headers, HttpContentHeaders contentHeader) - { - Headers = headers; - ContentHeaders = contentHeader; - } - /// public void Dispose() { - // Only IDisposable for backwards compatibility + // backwards compatibility } } } diff --git a/MediaBrowser.Common/Net/IHttpClient.cs b/MediaBrowser.Common/Net/IHttpClient.cs index 23ba341738..534e22eddf 100644 --- a/MediaBrowser.Common/Net/IHttpClient.cs +++ b/MediaBrowser.Common/Net/IHttpClient.cs @@ -1,12 +1,12 @@ using System; using System.IO; -using System.Threading.Tasks; using System.Net.Http; +using System.Threading.Tasks; namespace MediaBrowser.Common.Net { /// - /// Interface IHttpClient + /// Interface IHttpClient. /// public interface IHttpClient { diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 0b99dc9103..6bd7dd1d64 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; @@ -11,20 +12,20 @@ namespace MediaBrowser.Common.Net { event EventHandler NetworkChanged; + Func LocalSubnetsFn { get; set; } + /// - /// Gets a random port number that is currently available + /// Gets a random port number that is currently available. /// /// System.Int32. int GetRandomUnusedTcpPort(); int GetRandomUnusedUdpPort(); - Func LocalSubnetsFn { get; set; } - /// - /// Returns MAC Address from first Network Card in Computer + /// Returns the MAC Address from first Network Card in Computer. /// - /// [string] MAC Address + /// The MAC Address. List GetMacAddresses(); /// diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 6ef891d66e..25519ccc0d 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable SA1402 using System; using System.IO; @@ -8,10 +8,13 @@ using MediaBrowser.Model.Serialization; namespace MediaBrowser.Common.Plugins { + /// + /// Provides a common base class for all plugins. + /// public abstract class BasePlugin : IPlugin, IPluginAssembly { /// - /// Gets the name of the plugin + /// Gets the name of the plugin. /// /// The name. public abstract string Name { get; } @@ -29,17 +32,23 @@ namespace MediaBrowser.Common.Plugins public virtual Guid Id { get; private set; } /// - /// Gets the plugin version + /// Gets the plugin version. /// /// The version. public Version Version { get; private set; } /// - /// Gets the path to the assembly file + /// Gets the path to the assembly file. /// /// The assembly file path. public string AssemblyFilePath { get; private set; } + /// + /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed. + /// + /// The data folder path. + public string DataFolderPath { get; private set; } + /// /// Gets the plugin info. /// @@ -62,9 +71,9 @@ namespace MediaBrowser.Common.Plugins /// public virtual void OnUninstalling() { - } + /// public void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion) { AssemblyFilePath = assemblyFilePath; @@ -72,25 +81,48 @@ namespace MediaBrowser.Common.Plugins Version = assemblyVersion; } + /// public void SetId(Guid assemblyId) { Id = assemblyId; } - - /// - /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed - /// - /// The data folder path. - public string DataFolderPath { get; private set; } } /// - /// Provides a common base class for all plugins + /// Provides a common base class for all plugins. /// /// The type of the T configuration type. public abstract class BasePlugin : BasePlugin, IHasPluginConfiguration where TConfigurationType : BasePluginConfiguration { + /// + /// The _configuration sync lock. + /// + private readonly object _configurationSyncLock = new object(); + + /// + /// The _save lock. + /// + private readonly object _configurationSaveLock = new object(); + + private Action _directoryCreateFn; + + /// + /// The _configuration. + /// + private TConfigurationType _configuration; + + /// + /// Initializes a new instance of the class. + /// + /// The application paths. + /// The XML serializer. + protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + { + ApplicationPaths = applicationPaths; + XmlSerializer = xmlSerializer; + } + /// /// Gets the application paths. /// @@ -104,34 +136,19 @@ namespace MediaBrowser.Common.Plugins protected IXmlSerializer XmlSerializer { get; private set; } /// - /// Gets the type of configuration this plugin uses + /// Gets the type of configuration this plugin uses. /// /// The type of the configuration. public Type ConfigurationType => typeof(TConfigurationType); - private Action _directoryCreateFn; - public void SetStartupInfo(Action directoryCreateFn) - { - // hack alert, until the .net core transition is complete - _directoryCreateFn = directoryCreateFn; - } - /// - /// Gets the name the assembly file + /// Gets the name the assembly file. /// /// The name of the assembly file. protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath); /// - /// The _configuration sync lock - /// - private readonly object _configurationSyncLock = new object(); - /// - /// The _configuration - /// - private TConfigurationType _configuration; - /// - /// Gets the plugin's configuration + /// Gets or sets the plugin's configuration. /// /// The configuration. public TConfigurationType Configuration @@ -149,55 +166,54 @@ namespace MediaBrowser.Common.Plugins } } } + return _configuration; } - protected set => _configuration = value; - } - private TConfigurationType LoadConfiguration() - { - var path = ConfigurationFilePath; - - try - { - return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path); - } - catch - { - return (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); - } + protected set => _configuration = value; } /// - /// Gets the name of the configuration file. Subclasses should override + /// Gets the name of the configuration file. Subclasses should override. /// /// The name of the configuration file. public virtual string ConfigurationFileName => Path.ChangeExtension(AssemblyFileName, ".xml"); /// - /// Gets the full path to the configuration file + /// Gets the full path to the configuration file. /// /// The configuration file path. public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); /// - /// Initializes a new instance of the class. + /// Gets the plugin's configuration. /// - /// The application paths. - /// The XML serializer. - protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + /// The configuration. + BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration; + + /// + public void SetStartupInfo(Action directoryCreateFn) { - ApplicationPaths = applicationPaths; - XmlSerializer = xmlSerializer; + // hack alert, until the .net core transition is complete + _directoryCreateFn = directoryCreateFn; } - /// - /// The _save lock - /// - private readonly object _configurationSaveLock = new object(); + private TConfigurationType LoadConfiguration() + { + var path = ConfigurationFilePath; + + try + { + return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path); + } + catch + { + return (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); + } + } /// - /// Saves the current configuration to the file system + /// Saves the current configuration to the file system. /// public virtual void SaveConfiguration() { @@ -209,12 +225,7 @@ namespace MediaBrowser.Common.Plugins } } - /// - /// Completely overwrites the current configuration with a new copy - /// Returns true or false indicating success or failure - /// - /// The configuration. - /// configuration + /// public virtual void UpdateConfiguration(BasePluginConfiguration configuration) { if (configuration == null) @@ -227,12 +238,7 @@ namespace MediaBrowser.Common.Plugins SaveConfiguration(); } - /// - /// Gets the plugin's configuration - /// - /// The configuration. - BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration; - + /// public override PluginInfo GetPluginInfo() { var info = base.GetPluginInfo(); @@ -242,10 +248,4 @@ namespace MediaBrowser.Common.Plugins return info; } } - - public interface IPluginAssembly - { - void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion); - void SetId(Guid assemblyId); - } } diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs index 7bd90c964b..001ca8be8a 100644 --- a/MediaBrowser.Common/Plugins/IPlugin.cs +++ b/MediaBrowser.Common/Plugins/IPlugin.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using MediaBrowser.Model.Plugins; @@ -6,12 +7,12 @@ using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins { /// - /// Interface IPlugin + /// Interface IPlugin. /// public interface IPlugin { /// - /// Gets the name of the plugin + /// Gets the name of the plugin. /// /// The name. string Name { get; } @@ -29,19 +30,19 @@ namespace MediaBrowser.Common.Plugins Guid Id { get; } /// - /// Gets the plugin version + /// Gets the plugin version. /// /// The version. Version Version { get; } /// - /// Gets the path to the assembly file + /// Gets the path to the assembly file. /// /// The assembly file path. string AssemblyFilePath { get; } /// - /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed + /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed. /// /// The data folder path. string DataFolderPath { get; } @@ -61,24 +62,24 @@ namespace MediaBrowser.Common.Plugins public interface IHasPluginConfiguration { /// - /// Gets the type of configuration this plugin uses + /// Gets the type of configuration this plugin uses. /// /// The type of the configuration. Type ConfigurationType { get; } /// - /// Completely overwrites the current configuration with a new copy - /// Returns true or false indicating success or failure + /// Gets the plugin's configuration. /// - /// The configuration. - /// configuration - void UpdateConfiguration(BasePluginConfiguration configuration); + /// The configuration. + BasePluginConfiguration Configuration { get; } /// - /// Gets the plugin's configuration + /// Completely overwrites the current configuration with a new copy + /// Returns true or false indicating success or failure. /// - /// The configuration. - BasePluginConfiguration Configuration { get; } + /// The configuration. + /// configuration is null. + void UpdateConfiguration(BasePluginConfiguration configuration); void SetStartupInfo(Action directoryCreateFn); } diff --git a/MediaBrowser.Common/Plugins/IPluginAssembly.cs b/MediaBrowser.Common/Plugins/IPluginAssembly.cs new file mode 100644 index 0000000000..388ac61ab9 --- /dev/null +++ b/MediaBrowser.Common/Plugins/IPluginAssembly.cs @@ -0,0 +1,14 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + +using System; + +namespace MediaBrowser.Common.Plugins +{ + public interface IPluginAssembly + { + void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion); + + void SetId(Guid assemblyId); + } +} diff --git a/MediaBrowser.Common/Progress/ActionableProgress.cs b/MediaBrowser.Common/Progress/ActionableProgress.cs index af69055aa9..92141ba526 100644 --- a/MediaBrowser.Common/Progress/ActionableProgress.cs +++ b/MediaBrowser.Common/Progress/ActionableProgress.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; diff --git a/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs b/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs index 0445397ad8..a6422e2c80 100644 --- a/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs +++ b/MediaBrowser.Common/Providers/SubtitleConfigurationFactory.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System.Collections.Generic; using MediaBrowser.Common.Configuration; diff --git a/MediaBrowser.Common/System/OperatingSystem.cs b/MediaBrowser.Common/System/OperatingSystem.cs index 7d38ddb6e5..f23af47993 100644 --- a/MediaBrowser.Common/System/OperatingSystem.cs +++ b/MediaBrowser.Common/System/OperatingSystem.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Runtime.InteropServices; diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index e49812f150..a09c1916c5 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; @@ -103,17 +104,16 @@ namespace MediaBrowser.Common.Updates Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken = default); /// - /// Uninstalls a plugin + /// Uninstalls a plugin. /// /// The plugin. - /// void UninstallPlugin(IPlugin plugin); /// - /// Cancels the installation + /// Cancels the installation. /// - /// The id of the package that is being installed - /// Returns true if the install was cancelled + /// The id of the package that is being installed. + /// Returns true if the install was cancelled. bool CancelInstallation(Guid id); } } diff --git a/MediaBrowser.Common/Updates/InstallationEventArgs.cs b/MediaBrowser.Common/Updates/InstallationEventArgs.cs index 36e124ddfc..8bbb231ce1 100644 --- a/MediaBrowser.Common/Updates/InstallationEventArgs.cs +++ b/MediaBrowser.Common/Updates/InstallationEventArgs.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using MediaBrowser.Model.Updates; diff --git a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs index 46f10c84fd..c8967f9dbf 100644 --- a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs +++ b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; diff --git a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs index 3c65156e30..5248ea4c13 100644 --- a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs +++ b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs @@ -1,14 +1,19 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dto; - namespace MediaBrowser.Controller.Authentication { public class AuthenticationResult { public UserDto User { get; set; } + public SessionInfo SessionInfo { get; set; } + public string AccessToken { get; set; } + public string ServerId { get; set; } } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 1fd706857a..cf8f030023 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -19,7 +19,6 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.Library; diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 75b5573b67..b6f5cf01b0 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -31,8 +31,12 @@ + + + + + + + + + + - - From 8723bdbb4fb73ed261ac1ba3b6932773e523d78b Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 18 Dec 2019 11:52:32 +0100 Subject: [PATCH 004/108] Fix tests --- .../TV/EpisodeNumberTests.cs | 7 +++++-- .../TV/EpisodePathParserTest.cs | 20 ++++++------------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 03fae31596..1ae6372817 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -87,19 +87,22 @@ namespace Jellyfin.Naming.Tests.TV // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16.avi")); } + [Fact] public void TestEpisodeNumber54() { // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); } - [Fact] + + // [Fact] public void TestEpisodeNumber55() { // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); } - [Fact] + + // [Fact] public void TestEpisodeNumber56() { // This is not supported. Expected to fail, although it would be a good one to add support for. diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs index 8e8adb35b3..da6e993100 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs @@ -11,6 +11,10 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("/media/Foo - S04E011", "Foo", 4, 11)] [InlineData("/media/Foo/Foo s01x01", "Foo", 1, 1)] [InlineData("/media/Foo (2019)/Season 4/Foo (2019).S04E03", "Foo (2019)", 4, 3)] + [InlineData("D:\\media\\Foo\\Foo-S01E01", "Foo", 1, 1)] + [InlineData("D:\\media\\Foo - S04E011", "Foo", 4, 11)] + [InlineData("D:\\media\\Foo\\Foo s01x01", "Foo", 1, 1)] + [InlineData("D:\\media\\Foo (2019)\\Season 4\\Foo (2019).S04E03", "Foo (2019)", 4, 3)] public void ParseEpisodesCorrectly(string path, string name, int season, int episode) { NamingOptions o = new NamingOptions(); @@ -21,18 +25,13 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(name, res.SeriesName); Assert.Equal(season, res.SeasonNumber); Assert.Equal(episode, res.EpisodeNumber); - - // testing other paths delimeter - var res2 = p.Parse(path.Replace('/', '/'), false); - Assert.True(res2.Success); - Assert.Equal(name, res2.SeriesName); - Assert.Equal(season, res2.SeasonNumber); - Assert.Equal(episode, res2.EpisodeNumber); } [Theory] [InlineData("/media/Foo/Foo 889", "Foo", 889)] [InlineData("/media/Foo/[Bar] Foo Baz - 11 [1080p]", "Foo Baz", 11)] + [InlineData("D:\\media\\Foo\\Foo 889", "Foo", 889)] + [InlineData("D:\\media\\Foo\\[Bar] Foo Baz - 11 [1080p]", "Foo Baz", 11)] public void ParseEpisodeWithoutSeason(string path, string name, int episode) { NamingOptions o = new NamingOptions(); @@ -43,13 +42,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(name, res.SeriesName); Assert.Null(res.SeasonNumber); Assert.Equal(episode, res.EpisodeNumber); - - // testing other paths delimeter - var res2 = p.Parse(path.Replace('/', '/'), false, fillExtendedInfo: false); - Assert.True(res2.Success); - Assert.Equal(name, res2.SeriesName); - Assert.Null(res2.SeasonNumber); - Assert.Equal(episode, res2.EpisodeNumber); } } } From a5cd11735cc0320e576605410b68e4dace6caa05 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 19 Dec 2019 15:50:25 +0100 Subject: [PATCH 005/108] Minor changes to MediaInfoService --- MediaBrowser.Api/Playback/MediaInfoService.cs | 54 +++++++++---------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index c3032416b8..8caa033039 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -102,12 +102,6 @@ namespace MediaBrowser.Api.Playback public object Get(GetBitrateTestBytes request) { var bytes = new byte[request.Size]; - - for (var i = 0; i < bytes.Length; i++) - { - bytes[i] = 0; - } - return ResultFactory.GetResult(null, bytes, "application/octet-stream"); } @@ -166,8 +160,7 @@ namespace MediaBrowser.Api.Playback public void Post(CloseMediaSource request) { - var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId); - Task.WaitAll(task); + _mediaSourceManager.CloseLiveStream(request.LiveStreamId).GetAwaiter().GetResult(); } public async Task GetPlaybackInfo(GetPostedPlaybackInfo request) @@ -176,7 +169,7 @@ namespace MediaBrowser.Api.Playback var profile = request.DeviceProfile; - //Logger.LogInformation("GetPostedPlaybackInfo profile: {profile}", _json.SerializeToString(profile)); + Logger.LogInformation("GetPostedPlaybackInfo profile: {profile}", _json.SerializeToString(profile)); if (profile == null) { @@ -215,9 +208,7 @@ namespace MediaBrowser.Api.Playback StartTimeTicks = request.StartTimeTicks, SubtitleStreamIndex = request.SubtitleStreamIndex, UserId = request.UserId, - OpenToken = mediaSource.OpenToken, - //EnableMediaProbe = request.EnableMediaProbe - + OpenToken = mediaSource.OpenToken }).ConfigureAwait(false); info.MediaSources = new MediaSourceInfo[] { openStreamResult.MediaSource }; @@ -311,7 +302,8 @@ namespace MediaBrowser.Api.Playback return result; } - private void SetDeviceSpecificData(Guid itemId, + private void SetDeviceSpecificData( + Guid itemId, PlaybackInfoResponse result, DeviceProfile profile, AuthorizationInfo auth, @@ -339,7 +331,8 @@ namespace MediaBrowser.Api.Playback SortMediaSources(result, maxBitrate); } - private void SetDeviceSpecificData(BaseItem item, + private void SetDeviceSpecificData( + BaseItem item, MediaSourceInfo mediaSource, DeviceProfile profile, AuthorizationInfo auth, @@ -383,10 +376,12 @@ namespace MediaBrowser.Api.Playback { mediaSource.SupportsDirectPlay = false; } + if (!enableDirectStream) { mediaSource.SupportsDirectStream = false; } + if (!enableTranscoding) { mediaSource.SupportsTranscoding = false; @@ -434,9 +429,9 @@ namespace MediaBrowser.Api.Playback } // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) + ? streamBuilder.BuildAudioItem(options) + : streamBuilder.BuildVideoItem(options); if (streamInfo == null || !streamInfo.IsDirectStream) { @@ -473,9 +468,9 @@ namespace MediaBrowser.Api.Playback } // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) + ? streamBuilder.BuildAudioItem(options) + : streamBuilder.BuildVideoItem(options); if (streamInfo == null || !streamInfo.IsDirectStream) { @@ -493,9 +488,9 @@ namespace MediaBrowser.Api.Playback options.MaxBitrate = GetMaxBitrate(maxBitrate, user); // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) + ? streamBuilder.BuildAudioItem(options) + : streamBuilder.BuildVideoItem(options); if (streamInfo != null) { @@ -510,10 +505,12 @@ namespace MediaBrowser.Api.Playback { mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; } + if (!allowAudioStreamCopy) { mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; } + mediaSource.TranscodingContainer = streamInfo.Container; mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; } @@ -599,14 +596,11 @@ namespace MediaBrowser.Api.Playback }).ThenBy(i => { - switch (i.Protocol) + return i.Protocol switch { - case MediaProtocol.File: - return 0; - default: - return 1; - } - + MediaProtocol.File => 0, + _ => 1, + }; }).ThenBy(i => { if (maxBitrate.HasValue) From bb62dd14c2fee3f7a6fa8cb3d8592500046ed3c9 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 19 Dec 2019 17:46:17 +0100 Subject: [PATCH 006/108] Limit size for playbacktest --- MediaBrowser.Api/Playback/MediaInfoService.cs | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 8caa033039..ac1cba09ab 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -54,7 +55,7 @@ namespace MediaBrowser.Api.Playback public class GetBitrateTestBytes { [ApiMember(Name = "Size", Description = "Size", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")] - public long Size { get; set; } + public int Size { get; set; } public GetBitrateTestBytes() { @@ -101,8 +102,31 @@ namespace MediaBrowser.Api.Playback public object Get(GetBitrateTestBytes request) { - var bytes = new byte[request.Size]; - return ResultFactory.GetResult(null, bytes, "application/octet-stream"); + const int MaxSize = 10_000_000; + + var size = request.Size; + + if (size <= 0) + { + throw new ArgumentException($"The requested size can't be equal or smaller than 0.", nameof(request)); + } + + if (size > MaxSize) + { + throw new ArgumentException($"The requested size can't be larger than the max allowed value ({MaxSize}).", nameof(request)); + } + + byte[] buffer = ArrayPool.Shared.Rent(size); + try + { + // ArrayPool.Shared.Rent doesn't guarantee that the returned buffer is zeroed + Array.Fill(buffer, 0); + return ResultFactory.GetResult(null, buffer, "application/octet-stream"); + } + finally + { + ArrayPool.Shared.Return(buffer); + } } public async Task Get(GetPlaybackInfo request) From 137db45fc7a91d75d81023709b77277f34958ff0 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 19 Dec 2019 22:01:05 +0100 Subject: [PATCH 007/108] Apply suggestions from code review Co-Authored-By: dkanada --- MediaBrowser.Common/Hex.cs | 2 +- MediaBrowser.Common/Plugins/BasePlugin.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Common/Hex.cs b/MediaBrowser.Common/Hex.cs index 863192809f..559109f74f 100644 --- a/MediaBrowser.Common/Hex.cs +++ b/MediaBrowser.Common/Hex.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Common internal const int LastHexSymbol = 0x66; // 102: f /// - /// Gets an map from an ASCII char to its hex value shifted, + /// Gets a map from an ASCII char to its hex value shifted, /// e.g. b -> 11. 0xFF means it's not a hex symbol. /// internal static ReadOnlySpan HexLookup => new byte[] diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 25519ccc0d..b24d10ff10 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -96,19 +96,19 @@ namespace MediaBrowser.Common.Plugins where TConfigurationType : BasePluginConfiguration { /// - /// The _configuration sync lock. + /// The configuration sync lock. /// private readonly object _configurationSyncLock = new object(); /// - /// The _save lock. + /// The save lock. /// private readonly object _configurationSaveLock = new object(); private Action _directoryCreateFn; /// - /// The _configuration. + /// The configuration. /// private TConfigurationType _configuration; From 5751d865363606e2ee1a773adaaf58c2864b08f8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 20 Dec 2019 21:49:16 +0100 Subject: [PATCH 008/108] Fix warnings and move to System.Text.Json --- MediaBrowser.Api/Playback/MediaInfoService.cs | 18 ++++++++++-------- .../Playback/UniversalAudioService.cs | 2 -- .../MediaInfo/PlaybackInfoResponse.cs | 12 ++++++++++-- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index ac1cba09ab..80acdc4554 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -1,7 +1,13 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1402 +#pragma warning disable SA1600 +#pragma warning disable SA1649 + using System; using System.Buffers; using System.Collections.Generic; using System.Globalization; +using System.Text.Json; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -73,7 +79,6 @@ namespace MediaBrowser.Api.Playback private readonly INetworkManager _networkManager; private readonly IMediaEncoder _mediaEncoder; private readonly IUserManager _userManager; - private readonly IJsonSerializer _json; private readonly IAuthorizationContext _authContext; public MediaInfoService( @@ -86,7 +91,6 @@ namespace MediaBrowser.Api.Playback INetworkManager networkManager, IMediaEncoder mediaEncoder, IUserManager userManager, - IJsonSerializer json, IAuthorizationContext authContext) : base(logger, serverConfigurationManager, httpResultFactory) { @@ -96,7 +100,6 @@ namespace MediaBrowser.Api.Playback _networkManager = networkManager; _mediaEncoder = mediaEncoder; _userManager = userManager; - _json = json; _authContext = authContext; } @@ -193,7 +196,7 @@ namespace MediaBrowser.Api.Playback var profile = request.DeviceProfile; - Logger.LogInformation("GetPostedPlaybackInfo profile: {profile}", _json.SerializeToString(profile)); + Logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", profile); if (profile == null) { @@ -266,9 +269,8 @@ namespace MediaBrowser.Api.Playback { // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it // Should we move this directly into MediaSourceManager? - - var json = _json.SerializeToString(obj); - return _json.DeserializeFromString(json); + var json = JsonSerializer.SerializeToUtf8Bytes(obj); + return JsonSerializer.Deserialize(json); } private async Task GetPlaybackInfo(Guid id, Guid userId, string[] supportedLiveMediaTypes, string mediaSourceId = null, string liveStreamId = null) @@ -309,7 +311,7 @@ namespace MediaBrowser.Api.Playback result.MediaSources = new MediaSourceInfo[] { mediaSource }; } - if (result.MediaSources.Length == 0) + if (result.MediaSources.Count == 0) { if (!result.ErrorCode.HasValue) { diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index 9cba9df139..bcac5093e0 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -74,7 +74,6 @@ namespace MediaBrowser.Api.Playback [Authenticated] public class UniversalAudioService : BaseApiService { - private readonly ILoggerFactory _loggerFactory; private readonly EncodingHelper _encodingHelper; public UniversalAudioService( @@ -243,7 +242,6 @@ namespace MediaBrowser.Api.Playback NetworkManager, MediaEncoder, UserManager, - JsonSerializer, AuthorizationContext) { Request = Request diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs index 38638af42c..440818c3ef 100644 --- a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs +++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs @@ -1,15 +1,20 @@ +using System; +using System.Collections.Generic; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; namespace MediaBrowser.Model.MediaInfo { + /// + /// Class PlaybackInfoResponse. + /// public class PlaybackInfoResponse { /// /// Gets or sets the media sources. /// /// The media sources. - public MediaSourceInfo[] MediaSources { get; set; } + public IReadOnlyList MediaSources { get; set; } /// /// Gets or sets the play session identifier. @@ -23,9 +28,12 @@ namespace MediaBrowser.Model.MediaInfo /// The error code. public PlaybackErrorCode? ErrorCode { get; set; } + /// + /// Initializes a new instance of the class. + /// public PlaybackInfoResponse() { - MediaSources = new MediaSourceInfo[] { }; + MediaSources = Array.Empty(); } } } From f47c7959af72a971d1b812194bf03098e671364f Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 09:46:09 +0000 Subject: [PATCH 009/108] Wrote tests to cover CustomAuthenticationHandler --- .../Auth/CustomAuthenticationHandlerTests.cs | 170 ++++++++++++++++++ .../Jellyfin.Api.Tests.csproj | 11 ++ 2 files changed, 181 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs new file mode 100644 index 0000000000..bd23ca869b --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -0,0 +1,170 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Auth; +using Jellyfin.Api.Constants; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Net; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth +{ + public class CustomAuthenticationHandlerTests + { + private readonly IFixture _fixture; + + private readonly Mock _authServiceMock; + private readonly Mock> _optionsMock; + private readonly Mock _clockMock; + private readonly Mock _serviceProviderMock; + private readonly Mock _authenticationServiceMock; + private readonly UrlEncoder _urlEncoder; + private readonly HttpContext _context; + + private readonly CustomAuthenticationHandler _sut; + private readonly AuthenticationScheme _scheme; + + public CustomAuthenticationHandlerTests() + { + _fixture = new Fixture().Customize(new AutoMoqCustomization {ConfigureMembers = true}); + AllowFixtureCircularDependencies(); + + _authServiceMock = _fixture.Freeze>(); + _optionsMock = _fixture.Freeze>>(); + _clockMock = _fixture.Freeze>(); + _serviceProviderMock = _fixture.Freeze>(); + _authenticationServiceMock = _fixture.Freeze>(); + _fixture.Register(() => new NullLoggerFactory()); + + _urlEncoder = UrlEncoder.Default; + + _serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService))) + .Returns(_authenticationServiceMock.Object); + + _optionsMock.Setup(o => o.Get(It.IsAny())) + .Returns(new AuthenticationSchemeOptions + { + ForwardAuthenticate = null + }); + + _context = new DefaultHttpContext + { + RequestServices = _serviceProviderMock.Object + }; + + _scheme = new AuthenticationScheme( + _fixture.Create(), + null, + typeof(CustomAuthenticationHandler)); + + _sut = _fixture.Create(); + _sut.InitializeAsync(_scheme, _context).Wait(); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldFailWithNullUser() + { + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Returns((User) null); + + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.False(authenticateResult.Succeeded); + Assert.Equal("Invalid user", authenticateResult.Failure.Message); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldFailOnSecurityException() + { + var errorMessage = _fixture.Create(); + + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Throws(new SecurityException(errorMessage)); + + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.False(authenticateResult.Succeeded); + Assert.Equal(errorMessage, authenticateResult.Failure.Message); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldSucceedWithUser() + { + SetupUser(); + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.True(authenticateResult.Succeeded); + Assert.Null(authenticateResult.Failure); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldAssignNameClaim() + { + var user = SetupUser(); + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, user.Name)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin) + { + var user = SetupUser(isAdmin); + var authenticateResult = await _sut.AuthenticateAsync(); + + var expectedRole = user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User; + Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole)); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldAssignTicketCorrectScheme() + { + SetupUser(); + var authenticatedResult = await _sut.AuthenticateAsync(); + + Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme); + } + + private User SetupUser(bool isAdmin=false) + { + var user = _fixture.Create(); + user.Policy.IsAdministrator = isAdmin; + + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Returns(user); + + return user; + } + + private void AllowFixtureCircularDependencies() + { + // A circular dependency exists in the User entity around parent folders, + // this allows Autofixture to generate a User regardless, rather than throw + // an error. + _fixture.Behaviors.OfType().ToList() + .ForEach(b => _fixture.Behaviors.Remove(b)); + _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + } + } +} diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 1671b8d797..77c58040e4 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -6,6 +6,10 @@ + + + + @@ -15,6 +19,13 @@ + + + + + + ..\..\..\..\..\..\usr\local\share\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.0.0\ref\netcoreapp3.0\Microsoft.AspNetCore.Authentication.dll + From 57aec873d08159d0e5ffb43ecf1e0a05f43038be Mon Sep 17 00:00:00 2001 From: Waldemar Tomme Date: Sun, 22 Dec 2019 13:01:18 +0100 Subject: [PATCH 010/108] Add check if output container supports "global_header" flag --- .../MediaEncoding/EncodingHelper.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 020f0553ed..424dd0dbe8 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2750,6 +2750,8 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -mpegts_m2ts_mode 1"; } + var supportsGlobalHeaderFlag = state.OutputContainer != "mkv"; + if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null @@ -2770,7 +2772,12 @@ namespace MediaBrowser.Controller.MediaEncoding if (!state.RunTimeTicks.HasValue) { - args += " -flags -global_header -fflags +genpts"; + if(supportsGlobalHeaderFlag) + { + args += " -flags -global_header"; + } + + args += " -fflags +genpts"; } } else @@ -2816,7 +2823,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " " + qualityParam.Trim(); } - if (!state.RunTimeTicks.HasValue) + if (supportsGlobalHeaderFlag && !state.RunTimeTicks.HasValue) { args += " -flags -global_header"; } From 8c4e679ff4c78e5361d14f151bf4d40b2312478c Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:36:11 +0000 Subject: [PATCH 011/108] PR style comments --- .../Auth/CustomAuthenticationHandlerTests.cs | 9 +++++++-- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index bd23ca869b..f202f59e61 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -36,7 +36,12 @@ namespace Jellyfin.Api.Tests.Auth public CustomAuthenticationHandlerTests() { - _fixture = new Fixture().Customize(new AutoMoqCustomization {ConfigureMembers = true}); + var fixtureCustomizations = new AutoMoqCustomization + { + ConfigureMembers = true + }; + + _fixture = new Fixture().Customize(fixtureCustomizations); AllowFixtureCircularDependencies(); _authServiceMock = _fixture.Freeze>(); @@ -143,7 +148,7 @@ namespace Jellyfin.Api.Tests.Auth Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme); } - private User SetupUser(bool isAdmin=false) + private User SetupUser(bool isAdmin = false) { var user = _fixture.Create(); user.Policy.IsAdministrator = isAdmin; diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 77c58040e4..208a7bb30d 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -19,7 +19,7 @@ - + From 8d06d0dbdf7bbb156df0c002f2f0af6806be2b8b Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:39:29 +0000 Subject: [PATCH 012/108] Removed unneeded dependency --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 208a7bb30d..ac54cb26e3 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,10 +22,4 @@ - - - ..\..\..\..\..\..\usr\local\share\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.0.0\ref\netcoreapp3.0\Microsoft.AspNetCore.Authentication.dll - - - From ef75455178dda5542cbe9b32cafc4705de299723 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:54:46 +0000 Subject: [PATCH 013/108] Test RequiresElevationHandler for all roles --- .../RequiresElevationHandlerTests.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs new file mode 100644 index 0000000000..e2beea1ad8 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using Jellyfin.Api.Auth.RequiresElevationPolicy; +using Jellyfin.Api.Constants; +using Microsoft.AspNetCore.Authorization; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth.RequiresElevationPolicy +{ + public class RequiresElevationHandlerTests + { + private readonly RequiresElevationHandler _sut; + + public RequiresElevationHandlerTests() + { + _sut = new RequiresElevationHandler(); + } + + [Theory] + [InlineData(UserRoles.Administrator, true)] + [InlineData(UserRoles.User, false)] + [InlineData(UserRoles.Guest, false)] + public async Task ShouldHandleRolesCorrectly(string role, bool shouldSucceed) + { + var requirements = new List {new RequiresElevationRequirement()}; + + var claims = new[] {new Claim(ClaimTypes.Role, role)}; + var identity = new ClaimsIdentity(claims); + var user = new ClaimsPrincipal(identity); + + var context = new AuthorizationHandlerContext(requirements, user, null); + + await _sut.HandleAsync(context); + Assert.Equal(shouldSucceed, context.HasSucceeded); + } + } +} From 00c6d392a13bb6a54b27c4c8c177eac5d8de5652 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 23:18:42 +0000 Subject: [PATCH 014/108] Added tests for FirstTimeSetupOrElevatedHandler --- .../FirstTimeSetupOrElevatedHandlerTests.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs new file mode 100644 index 0000000000..84cdbe360d --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy; +using Jellyfin.Api.Constants; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Configuration; +using Microsoft.AspNetCore.Authorization; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth.FirstTimeSetupOrElevatedPolicy +{ + public class FirstTimeSetupOrElevatedHandlerTests + { + private readonly Mock _configurationManagerMock; + private readonly List _requirements; + private readonly FirstTimeSetupOrElevatedHandler _sut; + + public FirstTimeSetupOrElevatedHandlerTests() + { + var fixture = new Fixture().Customize(new AutoMoqCustomization()); + _configurationManagerMock = fixture.Freeze>(); + _requirements = new List {new FirstTimeSetupOrElevatedRequirement()}; + + _sut = fixture.Create(); + } + + [Theory] + [InlineData(UserRoles.Administrator)] + [InlineData(UserRoles.Guest)] + [InlineData(UserRoles.User)] + public async Task ShouldSucceedIfStartupWizardIncomplete(string userRole) + { + SetupConfigurationManager(false); + var user = SetupUser(userRole); + var context = new AuthorizationHandlerContext(_requirements, user, null); + + await _sut.HandleAsync(context); + Assert.True(context.HasSucceeded); + } + + [Theory] + [InlineData(UserRoles.Administrator, true)] + [InlineData(UserRoles.Guest, false)] + [InlineData(UserRoles.User, false)] + public async Task ShouldRequireAdministratorIfStartupWizardComplete(string userRole, bool shouldSucceed) + { + SetupConfigurationManager(true); + var user = SetupUser(userRole); + var context = new AuthorizationHandlerContext(_requirements, user, null); + + await _sut.HandleAsync(context); + Assert.Equal(shouldSucceed, context.HasSucceeded); + } + + private static ClaimsPrincipal SetupUser(string role) + { + var claims = new[] {new Claim(ClaimTypes.Role, role)}; + var identity = new ClaimsIdentity(claims); + return new ClaimsPrincipal(identity); + } + + private void SetupConfigurationManager(bool startupWizardCompleted) + { + var commonConfiguration = new BaseApplicationConfiguration + { + IsStartupWizardCompleted = startupWizardCompleted + }; + + _configurationManagerMock.Setup(c => c.CommonConfiguration) + .Returns(commonConfiguration); + } + } +} From d1461b4238cdaee32137787e1eef5c3a7db697fa Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 23:21:20 +0000 Subject: [PATCH 015/108] Changed cast style as suggested, improved some member names to make them less ambiguous --- .../Auth/CustomAuthenticationHandlerTests.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index f202f59e61..a2f5c25016 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -23,8 +23,8 @@ namespace Jellyfin.Api.Tests.Auth { private readonly IFixture _fixture; - private readonly Mock _authServiceMock; - private readonly Mock> _optionsMock; + private readonly Mock _jellyfinAuthServiceMock; + private readonly Mock> _optionsMonitorMock; private readonly Mock _clockMock; private readonly Mock _serviceProviderMock; private readonly Mock _authenticationServiceMock; @@ -44,8 +44,8 @@ namespace Jellyfin.Api.Tests.Auth _fixture = new Fixture().Customize(fixtureCustomizations); AllowFixtureCircularDependencies(); - _authServiceMock = _fixture.Freeze>(); - _optionsMock = _fixture.Freeze>>(); + _jellyfinAuthServiceMock = _fixture.Freeze>(); + _optionsMonitorMock = _fixture.Freeze>>(); _clockMock = _fixture.Freeze>(); _serviceProviderMock = _fixture.Freeze>(); _authenticationServiceMock = _fixture.Freeze>(); @@ -56,7 +56,7 @@ namespace Jellyfin.Api.Tests.Auth _serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService))) .Returns(_authenticationServiceMock.Object); - _optionsMock.Setup(o => o.Get(It.IsAny())) + _optionsMonitorMock.Setup(o => o.Get(It.IsAny())) .Returns(new AuthenticationSchemeOptions { ForwardAuthenticate = null @@ -79,11 +79,11 @@ namespace Jellyfin.Api.Tests.Auth [Fact] public async Task HandleAuthenticateAsyncShouldFailWithNullUser() { - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) - .Returns((User) null); + .Returns((User)null); var authenticateResult = await _sut.AuthenticateAsync(); @@ -96,7 +96,7 @@ namespace Jellyfin.Api.Tests.Auth { var errorMessage = _fixture.Create(); - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) @@ -153,7 +153,7 @@ namespace Jellyfin.Api.Tests.Auth var user = _fixture.Create(); user.Policy.IsAdministrator = isAdmin; - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) From 167549f5f1563c5d7bcb4808b08231be0f924528 Mon Sep 17 00:00:00 2001 From: gnattu Date: Tue, 31 Dec 2019 22:33:14 -0500 Subject: [PATCH 016/108] Let HLS fallback to mpegts in case device reported unsupported container --- MediaBrowser.Api/Playback/UniversalAudioService.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index 9cba9df139..563e09ae69 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -300,6 +300,9 @@ namespace MediaBrowser.Api.Playback var transcodingProfile = deviceProfile.TranscodingProfiles[0]; + //HLS Segment container can only be mpegts or fmp4 per ffmpeg documentation + var supoortedHLSContainer = new string[] { "mpegts", "fmp4" }; + var newRequest = new GetMasterHlsAudioPlaylist { AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)), @@ -312,7 +315,8 @@ namespace MediaBrowser.Api.Playback PlaySessionId = playbackInfoResult.PlaySessionId, StartTimeTicks = request.StartTimeTicks, Static = isStatic, - SegmentContainer = request.TranscodingContainer, + //fallback to mpegts if device reports some wierd value that is not supported by HLS + SegmentContainer = Array.Exists(supoortedHLSContainer, element => element == request.TranscodingContainer) ? request.TranscodingContainer : "mpegts", AudioSampleRate = request.MaxAudioSampleRate, MaxAudioBitDepth = request.MaxAudioBitDepth, BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames, From 43c76b48c9f90afc34a5fd40aa1a28c8ae7b736a Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Wed, 8 Jan 2020 22:52:33 +0000 Subject: [PATCH 017/108] Added a test to prevent a regression of the issue seen in #1874. This issue was fixed in PR#2240 --- MediaBrowser.sln | 9 +++++- .../Emby.Server.Implementations.Tests.csproj | 23 ++++++++++++++ .../IO/ManagedFileSystemTests.cs | 31 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj create mode 100644 tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 416a434f47..cf1bab11c6 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,4 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 @@ -58,6 +58,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Naming.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Api.Tests", "tests\Jellyfin.Api.Tests\Jellyfin.Api.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Server.Implementations.Tests", "tests\Emby.Server.Implementations.Tests\Emby.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -164,6 +166,10 @@ Global {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Debug|Any CPU.Build.0 = Debug|Any CPU {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.Build.0 = Release|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -194,5 +200,6 @@ Global {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection EndGlobal diff --git a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj b/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj new file mode 100644 index 0000000000..c635a90f17 --- /dev/null +++ b/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj @@ -0,0 +1,23 @@ + + + + netcoreapp3.1 + + false + + + + + + + + + + + + + + + + + diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs new file mode 100644 index 0000000000..586c50db6a --- /dev/null +++ b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -0,0 +1,31 @@ +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.IO; +using Xunit; + +namespace Emby.Server.Implementations.Tests.IO +{ + public class ManagedFileSystemTests + { + private readonly IFixture _fixture; + private readonly ManagedFileSystem _sut; + + public ManagedFileSystemTests() + { + _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }); + _sut = _fixture.Create(); + } + + [Theory] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")] + public void MakeAbsolutePathCorrectlyHandlesRelativeFilePaths( + string folderPath, + string filePath, + string expectedAbsolutePath) + { + var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath); + Assert.Equal(expectedAbsolutePath, generatedPath); + } + } +} From 140673fcf6186c559c97829a14991f7f81d22430 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Wed, 8 Jan 2020 23:03:17 +0000 Subject: [PATCH 018/108] Add a test case which doesn't specify the parent directory. --- .../IO/ManagedFileSystemTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 586c50db6a..0044196a7f 100644 --- a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -19,6 +19,7 @@ namespace Emby.Server.Implementations.Tests.IO [Theory] [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")] [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Playlists/Beethoven/Misc/Moonlight Sonata.mp3")] public void MakeAbsolutePathCorrectlyHandlesRelativeFilePaths( string folderPath, string filePath, From d5204f572a1e1c377edfd14e680f438ac104e967 Mon Sep 17 00:00:00 2001 From: gnattu Date: Thu, 9 Jan 2020 02:25:05 -0500 Subject: [PATCH 019/108] Fix typo and plural --- MediaBrowser.Api/Playback/UniversalAudioService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index 563e09ae69..c9d29f8ef6 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -300,8 +300,8 @@ namespace MediaBrowser.Api.Playback var transcodingProfile = deviceProfile.TranscodingProfiles[0]; - //HLS Segment container can only be mpegts or fmp4 per ffmpeg documentation - var supoortedHLSContainer = new string[] { "mpegts", "fmp4" }; + // hls segment container can only be mpegts or fmp4 per ffmpeg documentation + var supportedHLSContainers = new string[] { "mpegts", "fmp4" }; var newRequest = new GetMasterHlsAudioPlaylist { @@ -315,8 +315,8 @@ namespace MediaBrowser.Api.Playback PlaySessionId = playbackInfoResult.PlaySessionId, StartTimeTicks = request.StartTimeTicks, Static = isStatic, - //fallback to mpegts if device reports some wierd value that is not supported by HLS - SegmentContainer = Array.Exists(supoortedHLSContainer, element => element == request.TranscodingContainer) ? request.TranscodingContainer : "mpegts", + // fallback to mpegts if device reports some weird value unsupported by hls + SegmentContainer = Array.Exists(supportedHLSContainers, element => element == request.TranscodingContainer) ? request.TranscodingContainer : "mpegts", AudioSampleRate = request.MaxAudioSampleRate, MaxAudioBitDepth = request.MaxAudioBitDepth, BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames, From 1fecb9efb2bec4fccfa39bb0b04ad2206cbb7c86 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:17:52 +0100 Subject: [PATCH 020/108] Fix the VSTest runner --- .ci/azure-pipelines.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 143873266d..6cedf32fd4 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -132,7 +132,7 @@ jobs: inputs: packageFeedSelector: 'nugetOrg' # Options: nugetOrg, customFeed, netShare versionSelector: 'latestPreRelease' # Required when packageFeedSelector == NugetOrg || PackageFeedSelector == CustomFeed# Options: latestPreRelease, latestStable, specificVersion - + - task: VSTest@2 inputs: testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun @@ -147,6 +147,7 @@ jobs: codeCoverageEnabled: True # Optional configuration: 'Debug' # Optional publishRunAttachments: true # Optional + otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal" ' - job: main_build_win displayName: Publish Windows From 1ea613a9bd4fd5d1fa4cb556fe238ecd4720e1e0 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:26:42 +0100 Subject: [PATCH 021/108] Update Jellyfin.Api.Test to 3.1 --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 1671b8d797..e0deeeabb8 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -1,7 +1,7 @@ - netcoreapp3.0 + netcoreapp3.1 false From 6792fa111ec8bed026a2c30afe2dc39ca2b02245 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:27:48 +0100 Subject: [PATCH 022/108] Fix the test selection glob. --- .ci/azure-pipelines.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 6cedf32fd4..4905a6fdb9 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -137,7 +137,7 @@ jobs: inputs: testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun testAssemblyVer2: | # Required when testSelector == TestAssemblies - **\bin\$(BuildConfiguration)\**\*test*.dll + **\bin\$(BuildConfiguration)\**\*test.dll !**\obj\** !**\xunit.runner.visualstudio.testadapter.dll !**\xunit.runner.visualstudio.dotnetcore.testadapter.dll @@ -147,6 +147,7 @@ jobs: codeCoverageEnabled: True # Optional configuration: 'Debug' # Optional publishRunAttachments: true # Optional + testRunTitle: $(Agent.JobName) otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal" ' - job: main_build_win From d328fc51cf72a2231b8b16d68c416214e12ed093 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:28:20 +0100 Subject: [PATCH 023/108] Apply suggestions from code review Co-Authored-By: Bond-009 Co-Authored-By: dkanada --- .ci/azure-pipelines.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 4905a6fdb9..b69195fcce 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -132,7 +132,6 @@ jobs: inputs: packageFeedSelector: 'nugetOrg' # Options: nugetOrg, customFeed, netShare versionSelector: 'latestPreRelease' # Required when packageFeedSelector == NugetOrg || PackageFeedSelector == CustomFeed# Options: latestPreRelease, latestStable, specificVersion - - task: VSTest@2 inputs: testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun @@ -148,7 +147,7 @@ jobs: configuration: 'Debug' # Optional publishRunAttachments: true # Optional testRunTitle: $(Agent.JobName) - otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal" ' + otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal"' - job: main_build_win displayName: Publish Windows From 654336990f8109c12ce1383d94dcdc84e7a3c5b6 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:31:44 +0100 Subject: [PATCH 024/108] Added plural glob for test assemblies --- .ci/azure-pipelines.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index b69195fcce..3adc6f85c3 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -136,6 +136,7 @@ jobs: inputs: testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun testAssemblyVer2: | # Required when testSelector == TestAssemblies + **\bin\$(BuildConfiguration)\**\*tests.dll **\bin\$(BuildConfiguration)\**\*test.dll !**\obj\** !**\xunit.runner.visualstudio.testadapter.dll From 312987aea57d5a7f1366a07220ed1aae27e235a6 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 9 Jan 2020 17:39:17 +0100 Subject: [PATCH 025/108] Build all test projects using a wildcard --- .ci/azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 3adc6f85c3..7bcaed70cd 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -2,7 +2,7 @@ name: $(Date:yyyyMMdd)$(Rev:.r) variables: - name: TestProjects - value: 'tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj' + value: 'tests/**/*Tests.csproj' - name: RestoreBuildProjects value: 'Jellyfin.Server/Jellyfin.Server.csproj' From 64baca9facae83832fc45f627f9249b38e37d168 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Thu, 9 Jan 2020 22:03:57 +0000 Subject: [PATCH 026/108] Renamed project and namespace --- MediaBrowser.sln | 2 +- .../IO/ManagedFileSystemTests.cs | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj} | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) rename tests/{Emby.Server.Implementations.Tests => Jellyfin.Server.Implementations.Tests}/IO/ManagedFileSystemTests.cs (96%) rename tests/{Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj => Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj} (91%) diff --git a/MediaBrowser.sln b/MediaBrowser.sln index cf1bab11c6..50570deecf 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -58,7 +58,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Naming.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Api.Tests", "tests\Jellyfin.Api.Tests\Jellyfin.Api.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Server.Implementations.Tests", "tests\Emby.Server.Implementations.Tests\Emby.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Implementations.Tests", "tests\Jellyfin.Server.Implementations.Tests\Jellyfin.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs similarity index 96% rename from tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs rename to tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 0044196a7f..f2a8e447fa 100644 --- a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -3,7 +3,7 @@ using AutoFixture.AutoMoq; using Emby.Server.Implementations.IO; using Xunit; -namespace Emby.Server.Implementations.Tests.IO +namespace Jellyfin.Server.Implementations.Tests.IO { public class ManagedFileSystemTests { diff --git a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj similarity index 91% rename from tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj rename to tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index c635a90f17..bb2afea168 100644 --- a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -4,6 +4,8 @@ netcoreapp3.1 false + + Jellyfin.Server.Implementations.Tests From c3ff4e0b9f52827872d50b890ea4e4fbab22b604 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Fri, 10 Jan 2020 19:42:07 +0900 Subject: [PATCH 027/108] fixes dockerfile building on recent linux installations --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 53a4252627..1cd864e0b3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,9 @@ FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 -RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" +# because of changes in docker and systemd we need to not build in parallel at the moment +# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting +RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" FROM jellyfin/ffmpeg:${FFMPEG_VERSION} as ffmpeg FROM debian:buster-slim From 0a92200c6fe0adc6c28294e0c7dca7029973d1b7 Mon Sep 17 00:00:00 2001 From: keitaro62 Date: Thu, 9 Jan 2020 10:54:06 +0000 Subject: [PATCH 028/108] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index e1dce82ffe..d6d5bba72d 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -5,7 +5,7 @@ "Artists": "Artistes", "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès", "Books": "Livres", - "CameraImageUploadedFrom": "Une nouvelle image de caméra a été chargée depuis {0}", + "CameraImageUploadedFrom": "Une nouvelle image d'appareil photo a été chargée depuis {0}", "Channels": "Chaînes", "ChapterNameValue": "Chapitre {0}", "Collections": "Collections", From 81ae6d8afda06a77f5e3a8647c9432959bd191a6 Mon Sep 17 00:00:00 2001 From: Philmo67 Date: Fri, 10 Jan 2020 15:17:02 +0000 Subject: [PATCH 029/108] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index d6d5bba72d..6b25e3df0f 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -5,7 +5,7 @@ "Artists": "Artistes", "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès", "Books": "Livres", - "CameraImageUploadedFrom": "Une nouvelle image d'appareil photo a été chargée depuis {0}", + "CameraImageUploadedFrom": "Une nouvelle photo a été chargée depuis {0}", "Channels": "Chaînes", "ChapterNameValue": "Chapitre {0}", "Collections": "Collections", From 0a39e54984ae2eb7ab9ec3382a9122a6de9e56b1 Mon Sep 17 00:00:00 2001 From: archon eleven Date: Fri, 10 Jan 2020 06:34:37 +0000 Subject: [PATCH 030/108] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- .../Localization/Core/ms.json | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index c10fbe58f6..b91c98ca0c 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -1,23 +1,23 @@ { "Albums": "Album-album", "AppDeviceValues": "App: {0}, Device: {1}", - "Application": "Application", + "Application": "Aplikasi", "Artists": "Artis-artis", "AuthenticationSucceededWithUserName": "{0} successfully authenticated", "Books": "Buku-buku", "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}", - "Channels": "Channels", + "Channels": "Saluran", "ChapterNameValue": "Chapter {0}", - "Collections": "Collections", + "Collections": "Koleksi", "DeviceOfflineWithName": "{0} has disconnected", "DeviceOnlineWithName": "{0} is connected", - "FailedLoginAttemptWithUserName": "Failed login attempt from {0}", + "FailedLoginAttemptWithUserName": "Cubaan log masuk gagal dari {0}", "Favorites": "Favorites", "Folders": "Folders", - "Genres": "Genres", + "Genres": "Genre-genre", "HeaderAlbumArtists": "Album Artists", - "HeaderCameraUploads": "Camera Uploads", - "HeaderContinueWatching": "Continue Watching", + "HeaderCameraUploads": "Muatnaik Kamera", + "HeaderContinueWatching": "Terus Menonton", "HeaderFavoriteAlbums": "Favorite Albums", "HeaderFavoriteArtists": "Favorite Artists", "HeaderFavoriteEpisodes": "Favorite Episodes", @@ -39,8 +39,8 @@ "MessageServerConfigurationUpdated": "Server configuration has been updated", "MixedContent": "Mixed content", "Movies": "Movies", - "Music": "Music", - "MusicVideos": "Music videos", + "Music": "Muzik", + "MusicVideos": "Video muzik", "NameInstallFailed": "{0} installation failed", "NameSeasonNumber": "Season {0}", "NameSeasonUnknown": "Season Unknown", @@ -68,8 +68,8 @@ "PluginUninstalledWithName": "{0} was uninstalled", "PluginUpdatedWithName": "{0} was updated", "ProviderValue": "Provider: {0}", - "ScheduledTaskFailedWithName": "{0} failed", - "ScheduledTaskStartedWithName": "{0} started", + "ScheduledTaskFailedWithName": "{0} gagal", + "ScheduledTaskStartedWithName": "{0} bermula", "ServerNameNeedsToBeRestarted": "{0} needs to be restarted", "Shows": "Series", "Songs": "Songs", @@ -78,7 +78,7 @@ "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}", "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}", "Sync": "Sync", - "System": "System", + "System": "Sistem", "TvShows": "TV Shows", "User": "User", "UserCreatedWithName": "User {0} has been created", @@ -92,6 +92,6 @@ "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}", "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}", "ValueHasBeenAddedToLibrary": "{0} has been added to your media library", - "ValueSpecialEpisodeName": "Special - {0}", - "VersionNumber": "Version {0}" + "ValueSpecialEpisodeName": "Khas - {0}", + "VersionNumber": "Versi {0}" } From e95239e28132b4d6486ee9272d20ec5ada46b66c Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Sat, 11 Jan 2020 01:36:25 +0800 Subject: [PATCH 031/108] add support for AMD h264_amf & hevc_amf --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 1feca0ec92..993cd3f747 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -55,7 +55,9 @@ namespace MediaBrowser.MediaEncoding.Encoder "h264_vaapi", "hevc_vaapi", "h264_v4l2m2m", - "ac3" + "ac3", + "h264_amf", + "hevc_amf" }; // Try and use the individual library versions to determine a FFmpeg version From d9ec502ff985918cf94326780b41c6382b9e8937 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 10 Jan 2020 21:25:45 +0100 Subject: [PATCH 032/108] Address comments --- MediaBrowser.Api/Playback/MediaInfoService.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 80acdc4554..3d8231a2ab 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -111,19 +111,18 @@ namespace MediaBrowser.Api.Playback if (size <= 0) { - throw new ArgumentException($"The requested size can't be equal or smaller than 0.", nameof(request)); + throw new ArgumentException($"The requested size ({size}) is equal to or smaller than 0.", nameof(request)); } if (size > MaxSize) { - throw new ArgumentException($"The requested size can't be larger than the max allowed value ({MaxSize}).", nameof(request)); + throw new ArgumentException($"The requested size ({size}) is larger than the max allowed value ({MaxSize}).", nameof(request)); } byte[] buffer = ArrayPool.Shared.Rent(size); try { - // ArrayPool.Shared.Rent doesn't guarantee that the returned buffer is zeroed - Array.Fill(buffer, 0); + new Random().NextBytes(buffer); return ResultFactory.GetResult(null, buffer, "application/octet-stream"); } finally From fa1aeeb18a766fd7b2265dc0352ee100d8377163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Slobodan=20Simi=C4=87?= Date: Fri, 10 Jan 2020 20:27:17 +0000 Subject: [PATCH 033/108] Added translation using Weblate (Serbian) --- Emby.Server.Implementations/Localization/Core/sr.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/sr.json diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -0,0 +1 @@ +{} From 0d6a4c2909632229b3c6a0f1b65f03c48d0f9eb2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 00:08:47 +0100 Subject: [PATCH 034/108] Fix build --- MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index c371e8b946..c530c9fd81 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -59,7 +59,7 @@ namespace MediaBrowser.MediaEncoding.Attachments throw new ArgumentNullException(nameof(mediaSourceId)); } - var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false); + var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false); var mediaSource = mediaSources .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)); if (mediaSource == null) @@ -196,7 +196,7 @@ namespace MediaBrowser.MediaEncoding.Attachments var exitCode = ranToCompletion ? process.ExitCode : -1; process.Dispose(); - + var failed = false; if (exitCode != 0) From 801c356d668069240e9197deb4ff648908c4ddbd Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 00:23:14 +0100 Subject: [PATCH 035/108] Fix regex for movies released after 2019 --- Emby.Naming/Common/NamingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index f3f70d3fed..a2105889b9 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -177,7 +177,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { - @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9][0-9]|20[0-1][0-9])([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9][0-9]|20[0-1][0-9])*" + @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](\d{4})([ _\,\.\(\)\[\]\-][^\d]|).*(\d{4})*" }; CleanStrings = new[] From a647dc57052182a6171dae9ffba3026b66b26be7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 19:39:11 +0100 Subject: [PATCH 036/108] Cleanup tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- .../Jellyfin.Naming.Tests/Video/StackTests.cs | 26 ------------------- 2 files changed, 1 insertion(+), 27 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index a2105889b9..71521e1fd8 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -340,7 +340,7 @@ namespace Emby.Naming.Common // *** End Kodi Standard Naming -                // [bar] Foo - 1 [baz] + // [bar] Foo - 1 [baz] new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[-\s_]+(?\d+).*$") { IsNamed = true diff --git a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs index 5faef0e3db..5c121d7387 100644 --- a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs @@ -382,32 +382,6 @@ namespace Jellyfin.Naming.Tests.Video TestStackInfo(result.Stacks[1], "Bad Boys (2006)", 2); } - [Fact] - public void TestDirectories2() - { - //TestDirectory(@"blah blah", false, @"blah blah"); - //TestDirectory(@"d:/music/weezer/03 Pinkerton", false, "03 Pinkerton"); - //TestDirectory(@"d:/music/michael jackson/Bad (2012 Remaster)", false, "Bad (2012 Remaster)"); - - //TestDirectory(@"blah blah - cd1", true, "blah blah"); - //TestDirectory(@"blah blah - disc1", true, "blah blah"); - //TestDirectory(@"blah blah - disk1", true, "blah blah"); - //TestDirectory(@"blah blah - pt1", true, "blah blah"); - //TestDirectory(@"blah blah - part1", true, "blah blah"); - //TestDirectory(@"blah blah - dvd1", true, "blah blah"); - - //// Add a space - //TestDirectory(@"blah blah - cd 1", true, "blah blah"); - //TestDirectory(@"blah blah - disc 1", true, "blah blah"); - //TestDirectory(@"blah blah - disk 1", true, "blah blah"); - //TestDirectory(@"blah blah - pt 1", true, "blah blah"); - //TestDirectory(@"blah blah - part 1", true, "blah blah"); - //TestDirectory(@"blah blah - dvd 1", true, "blah blah"); - - //// Not case sensitive - //TestDirectory(@"blah blah - Disc1", true, "blah blah"); - } - [Fact] public void TestNamesWithoutParts() { From b1dc595be1a7cf331702fd645b1441ac86afa464 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 20:25:06 +0100 Subject: [PATCH 037/108] Fix a couple of tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- Emby.Naming/Video/CleanDateTimeParser.cs | 6 +- Emby.Naming/Video/CleanStringParser.cs | 4 +- Emby.Naming/Video/VideoResolver.cs | 2 +- .../Video/BaseVideoTest.cs | 8 +- .../Video/CleanDateTimeTests.cs | 172 +++++------------- .../Video/CleanStringTests.cs | 154 +++------------- .../Video/MultiVersionTests.cs | 1 - 8 files changed, 83 insertions(+), 266 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 71521e1fd8..07259e00a1 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -182,7 +182,7 @@ namespace Emby.Naming.Common CleanStrings = new[] { - @"[ _\,\.\(\)\[\]\-](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|\[.*\])([ _\,\.\(\)\[\]\-]|$)", + @"[ _\,\.\(\)\[\]\-](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|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"(\[.*\])" }; diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index a9db4ccccd..9edb14a074 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -53,7 +53,7 @@ namespace Emby.Naming.Video } // Make a second pass, running clean string first - var cleanStringResult = new CleanStringParser().Clean(name, _options.CleanStringRegexes); + var cleanStringResult = CleanStringParser.Clean(name, _options.CleanStringRegexes); if (!cleanStringResult.HasChanged) { @@ -72,12 +72,12 @@ namespace Emby.Naming.Video var match = expression.Match(name); if (match.Success - && match.Groups.Count == 4 + && match.Groups.Count == 5 && match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) { - name = match.Groups[1].Value; + name = match.Groups[1].Value.TrimEnd(); result.Year = year; result.HasChanged = true; } diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index fcd4b65c75..fe2a91bdb9 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -9,9 +9,9 @@ namespace Emby.Naming.Video /// /// . /// - public class CleanStringParser + public static class CleanStringParser { - public CleanStringResult Clean(string name, IEnumerable expressions) + public static CleanStringResult Clean(string name, IEnumerable expressions) { var hasChanged = false; diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 41b79697cc..97f59121b1 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -132,7 +132,7 @@ namespace Emby.Naming.Video public CleanStringResult CleanString(string name) { - return new CleanStringParser().Clean(name, _options.CleanStringRegexes); + return CleanStringParser.Clean(name, _options.CleanStringRegexes); } public CleanDateTimeResult CleanDateTime(string name) diff --git a/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs index b993e241c0..0c2978aca9 100644 --- a/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs +++ b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs @@ -5,11 +5,9 @@ namespace Jellyfin.Naming.Tests.Video { public abstract class BaseVideoTest { - protected VideoResolver GetParser() - { - var options = new NamingOptions(); + private readonly NamingOptions _namingOptions = new NamingOptions(); - return new VideoResolver(options); - } + protected VideoResolver GetParser() + => new VideoResolver(_namingOptions); } } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs index bba73ad918..a2ef2dcd64 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs @@ -1,143 +1,59 @@ using System.IO; +using Emby.Naming.Common; +using Emby.Naming.Video; using Xunit; namespace Jellyfin.Naming.Tests.Video { - public class CleanDateTimeTests : BaseVideoTest + public sealed class CleanDateTimeTests { - // FIXME - // [Fact] - public void TestCleanDateTime() - { - Test(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013); - Test(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013); - Test(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013); - Test(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013); - - Test(@"300 (2006).mkv", "300", 2006); - Test(@"d:/movies/300 (2006).mkv", "300", 2006); - Test(@"300 2 (2006).mkv", "300 2", 2006); - Test(@"300 - 2 (2006).mkv", "300 - 2", 2006); - Test(@"300 2001 (2006).mkv", "300 2001", 2006); - - Test(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013); - Test(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013); - - Test(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006); - } - - // FIXME - // [Fact] - public void TestCleanDateTime1() - { - Test(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutFileExtension() - { - Test(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013); - Test(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013); - Test(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013); - Test(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013); - - Test(@"300 (2006)", "300", 2006); - Test(@"d:/movies/300 (2006)", "300", 2006); - Test(@"300 2 (2006)", "300 2", 2006); - Test(@"300 - 2 (2006)", "300 - 2", 2006); - Test(@"300 2001 (2006)", "300 2001", 2006); - - Test(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006); - Test(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006); - } - - [Fact] - public void TestCleanDateTimeWithoutDate() - { - Test(@"American.Psycho.mkv", "American.Psycho.mkv", null); - Test(@"American Psycho.mkv", "American Psycho.mkv", null); - } - - [Fact] - public void TestCleanDateTimeWithBracketedName() - { - Test(@"[rec].mkv", "[rec].mkv", null); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutExtension() - { - Test(@"St. Vincent (2014)", "St. Vincent", 2014); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutDate1() - { - Test("Super movie(2009).mp4", "Super movie", 2009); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutParenthesis() - { - Test("Drug War 2013.mp4", "Drug War", 2013); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithMultipleYears() - { - Test("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithYearAndResolution() - { - Test("First Man 2018 1080p.mkv", "First Man", 2018); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithYearAndResolution1() - { - Test("First Man (2018) 1080p.mkv", "First Man", 2018); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithSceneRelease() - { - Test("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016); - } - - // FIXME - // [Fact] - public void TestYearInBrackets() - { - Test("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018); - } - - private void Test(string input, string expectedName, int? expectedYear) + private readonly NamingOptions _namingOptions = new NamingOptions(); + + [Theory] + [InlineData(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013)] + [InlineData(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013)] + [InlineData(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013)] + [InlineData(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013)] + [InlineData(@"300 (2006).mkv", "300", 2006)] + [InlineData(@"d:/movies/300 (2006).mkv", "300", 2006)] + [InlineData(@"300 2 (2006).mkv", "300 2", 2006)] + [InlineData(@"300 - 2 (2006).mkv", "300 - 2", 2006)] + [InlineData(@"300 2001 (2006).mkv", "300 2001", 2006)] + [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013)] + [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006)] + [InlineData(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016)] + [InlineData(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013)] + [InlineData(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013)] + [InlineData(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013)] + [InlineData(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013)] + [InlineData(@"300 (2006)", "300", 2006)] + [InlineData(@"d:/movies/300 (2006)", "300", 2006)] + [InlineData(@"300 2 (2006)", "300 2", 2006)] + [InlineData(@"300 - 2 (2006)", "300 - 2", 2006)] + [InlineData(@"300 2001 (2006)", "300 2001", 2006)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006)] + [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv", null)] + [InlineData(@"American Psycho.mkv", "American Psycho.mkv", null)] + [InlineData(@"[rec].mkv", "[rec].mkv", null)] + [InlineData(@"St. Vincent (2014)", "St. Vincent", 2014)] + [InlineData("Super movie(2009).mp4", "Super movie", 2009)] + // FIXME: [InlineData("Drug War 2013.mp4", "Drug War", 2013)] + [InlineData("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997)] + // FIXME: [InlineData("First Man 2018 1080p.mkv", "First Man", 2018)] + [InlineData("First Man (2018) 1080p.mkv", "First Man", 2018)] + // FIXME: [InlineData("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016)] + // FIXME: [InlineData("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018)] + [InlineData(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014)] // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again + public void CleanDateTimeTest(string input, string expectedName, int? expectedYear) { input = Path.GetFileName(input); - var result = GetParser().CleanDateTime(input); + var result = new VideoResolver(_namingOptions).CleanDateTime(input); Assert.Equal(expectedName, result.Name, true); Assert.Equal(expectedYear, result.Year); } - - // FIXME - // [Fact] - public void TestCleanDateAndStringsSequence() - { - // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again - - Test(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014); - } } } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index cd90ac236c..7c3270ebcc 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -1,133 +1,37 @@ -using System; -using System.Globalization; +using Emby.Naming.Common; +using Emby.Naming.Video; using Xunit; namespace Jellyfin.Naming.Tests.Video { - public class CleanStringTests : BaseVideoTest + public sealed class CleanStringTests { - // FIXME - // [Fact] - public void TestCleanString() - { - Test("Super movie 480p.mp4", "Super movie"); - Test("Super movie 480p 2001.mp4", "Super movie"); - Test("Super movie [480p].mp4", "Super movie"); - Test("480 Super movie [tmdbid=12345].mp4", "480 Super movie"); - } - - // FIXME - // [Fact] - public void TestCleanString1() - { - Test("Super movie(2009).mp4", "Super movie(2009).mp4"); - } - - // FIXME - // [Fact] - public void TestCleanString2() - { - Test("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4"); - } - - // FIXME - // [Fact] - public void TestStringWithoutDate() - { - Test(@"American.Psycho.mkv", "American.Psycho.mkv"); - Test(@"American Psycho.mkv", "American Psycho.mkv"); - } - - // FIXME - // [Fact] - public void TestNameWithBrackets() - { - Test(@"[rec].mkv", "[rec].mkv"); - } - - // FIXME - // [Fact] - public void Test4k() - { - Test("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestUltraHd() - { - Test("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestUHd() - { - Test("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDR() - { - Test("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDC() - { - Test("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDC1() - { - Test("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestBDrip() - { - Test("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestBDripHDC() - { - Test("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestMulti() - { - Test("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestLeadingBraces() - { - // Not actually supported, just reported by a user - Test("[0004] - After The Sunset.el.mkv", "After The Sunset"); - } - - // FIXME - // [Fact] - public void TestTrailingBraces() - { - Test("After The Sunset - [0004].mkv", "After The Sunset"); - } - - private void Test(string input, string expectedName) - { - var result = GetParser().CleanString(input).ToString(); - - Assert.Equal(expectedName, result, true); + private readonly NamingOptions _namingOptions = new NamingOptions(); + + [Theory] + [InlineData("Super movie 480p.mp4", "Super movie")] + [InlineData("Super movie 480p 2001.mp4", "Super movie")] + [InlineData("Super movie [480p].mp4", "Super movie")] + [InlineData("480 Super movie [tmdbid=12345].mp4", "480 Super movie")] + [InlineData("Super movie(2009).mp4", "Super movie(2009).mp4")] + [InlineData("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4")] + [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv")] + [InlineData(@"American Psycho.mkv", "American Psycho.mkv")] + [InlineData(@"[rec].mkv", "[rec].mkv")] + [InlineData("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] + public void CleanStringTest(string input, string expectedName) + { + var result = new VideoResolver(_namingOptions).CleanString(input); + Assert.Equal(expectedName, result.Name); } } } diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index b8674ec495..b8fbb2cb25 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -62,7 +62,6 @@ namespace Jellyfin.Naming.Tests.Video [Fact] public void TestMultiEdition3() { - // This is currently not supported and will fail, but we should try to figure it out var files = new[] { @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1925 version.mkv", From dd254eddac4b805f0020e5899fb903ef10714527 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 20:31:59 +0100 Subject: [PATCH 038/108] Simplify CleanDateTimeParser --- Emby.Naming/Video/CleanDateTimeParser.cs | 44 ++---------------------- 1 file changed, 2 insertions(+), 42 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 9edb14a074..9723fb71a3 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,9 +1,7 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 -using System; using System.Globalization; -using System.IO; using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Common; @@ -23,47 +21,9 @@ namespace Emby.Naming.Video } public CleanDateTimeResult Clean(string name) - { - var originalName = name; - - try - { - var extension = Path.GetExtension(name) ?? string.Empty; - // Check supported extensions - if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) - && !_options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) - { - // Dummy up a file extension because the expressions will fail without one - // This is tricky because we can't just check Path.GetExtension for empty - // If the input is "St. Vincent (2014)", it will produce ". Vincent (2014)" as the extension - name += ".mkv"; - } - } - catch (ArgumentException) - { - } - - var result = _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) + => _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) .FirstOrDefault(i => i.HasChanged) ?? - new CleanDateTimeResult { Name = originalName }; - - if (result.HasChanged) - { - return result; - } - - // Make a second pass, running clean string first - var cleanStringResult = CleanStringParser.Clean(name, _options.CleanStringRegexes); - - if (!cleanStringResult.HasChanged) - { - return result; - } - - return _options.CleanDateTimeRegexes.Select(i => Clean(cleanStringResult.Name, i)) - .FirstOrDefault(i => i.HasChanged) ?? - result; - } + new CleanDateTimeResult { Name = name }; private static CleanDateTimeResult Clean(string name, Regex expression) { From cd0592ea8f4a373a4318d2aba42349a1b89d4b32 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:16:36 +0100 Subject: [PATCH 039/108] Improve parsers --- Emby.Naming/Common/NamingOptions.cs | 3 +- Emby.Naming/Video/CleanDateTimeParser.cs | 36 +++++++++++------ Emby.Naming/Video/CleanDateTimeResult.cs | 29 ++++++++------ Emby.Naming/Video/CleanStringParser.cs | 39 ++++++++----------- Emby.Naming/Video/CleanStringResult.cs | 20 ---------- Emby.Naming/Video/VideoResolver.cs | 9 +++-- .../Video/CleanStringTests.cs | 14 +++++-- 7 files changed, 75 insertions(+), 75 deletions(-) delete mode 100644 Emby.Naming/Video/CleanStringResult.cs diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 07259e00a1..41060426fa 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -182,8 +182,7 @@ namespace Emby.Naming.Common CleanStrings = new[] { - @"[ _\,\.\(\)\[\]\-](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|\[.*\])([ _\,\.\(\)\[\]\-]|$)", + @"[ _\,\.\(\)\[\]\-](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|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"(\[.*\])" }; diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 9723fb71a3..8638dddd42 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,8 +1,8 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System.Globalization; -using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Common; @@ -21,14 +21,28 @@ namespace Emby.Naming.Video } public CleanDateTimeResult Clean(string name) - => _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) - .FirstOrDefault(i => i.HasChanged) ?? - new CleanDateTimeResult { Name = name }; - - private static CleanDateTimeResult Clean(string name, Regex expression) { - var result = new CleanDateTimeResult(); + var regexes = _options.CleanDateTimeRegexes; + var len = regexes.Length; + CleanDateTimeResult result = new CleanDateTimeResult(name); + if (len == 0) + { + return result; + } + + for (int i = 0; i < len; i++) + { + if (TryClean(name, regexes[i], ref result)) + { + return result; + } + } + return result; + } + + private static bool TryClean(string name, Regex expression, ref CleanDateTimeResult result) + { var match = expression.Match(name); if (match.Success @@ -37,13 +51,11 @@ namespace Emby.Naming.Video && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) { - name = match.Groups[1].Value.TrimEnd(); - result.Year = year; - result.HasChanged = true; + result = new CleanDateTimeResult(match.Groups[1].Value.TrimEnd(), year); + return true; } - result.Name = name; - return result; + return false; } } } diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs index a7581972e4..73a445612b 100644 --- a/Emby.Naming/Video/CleanDateTimeResult.cs +++ b/Emby.Naming/Video/CleanDateTimeResult.cs @@ -1,26 +1,33 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable namespace Emby.Naming.Video { - public class CleanDateTimeResult + public readonly struct CleanDateTimeResult { + public CleanDateTimeResult(string name, int? year) + { + Name = name; + Year = year; + } + + public CleanDateTimeResult(string name) + { + Name = name; + Year = null; + } + /// - /// Gets or sets the name. + /// Gets the name. /// /// The name. - public string Name { get; set; } + public string Name { get; } /// - /// Gets or sets the year. + /// Gets the year. /// /// The year. - public int? Year { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has changed. - /// - /// true if this instance has changed; otherwise, false. - public bool HasChanged { get; set; } + public int? Year { get; } } } diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index fe2a91bdb9..b7b65d8228 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,6 +1,8 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable +using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -11,42 +13,33 @@ namespace Emby.Naming.Video /// public static class CleanStringParser { - public static CleanStringResult Clean(string name, IEnumerable expressions) + public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName) { - var hasChanged = false; - - foreach (var exp in expressions) + var len = expressions.Count; + for (int i = 0; i < len; i++) { - var result = Clean(name, exp); - - if (!string.IsNullOrEmpty(result.Name)) + if (TryClean(name, expressions[i], out newName)) { - name = result.Name; - hasChanged = hasChanged || result.HasChanged; + return true; } } - return new CleanStringResult - { - Name = name, - HasChanged = hasChanged - }; + newName = ReadOnlySpan.Empty; + return false; } - private static CleanStringResult Clean(string name, Regex expression) + private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) { - var result = new CleanStringResult(); - var match = expression.Match(name); - - if (match.Success) + int index = match.Index; + if (match.Success && index != 0) { - result.HasChanged = true; - name = name.Substring(0, match.Index); + newName = name.AsSpan().Slice(0, match.Index); + return true; } - result.Name = name; - return result; + newName = string.Empty; + return false; } } } diff --git a/Emby.Naming/Video/CleanStringResult.cs b/Emby.Naming/Video/CleanStringResult.cs deleted file mode 100644 index 786fe9e028..0000000000 --- a/Emby.Naming/Video/CleanStringResult.cs +++ /dev/null @@ -1,20 +0,0 @@ -#pragma warning disable CS1591 -#pragma warning disable SA1600 - -namespace Emby.Naming.Video -{ - public class CleanStringResult - { - /// - /// Gets or sets the name. - /// - /// The name. - public string Name { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has changed. - /// - /// true if this instance has changed; otherwise, false. - public bool HasChanged { get; set; } - } -} diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 97f59121b1..76e0a5a0ec 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -94,9 +94,10 @@ namespace Emby.Naming.Video { var cleanDateTimeResult = CleanDateTime(name); - if (extraResult.ExtraType == null) + if (extraResult.ExtraType == null + && TryCleanString(cleanDateTimeResult.Name, out ReadOnlySpan newName)) { - name = CleanString(cleanDateTimeResult.Name).Name; + name = newName.ToString(); } year = cleanDateTimeResult.Year; @@ -130,9 +131,9 @@ namespace Emby.Naming.Video return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } - public CleanStringResult CleanString(string name) + public bool TryCleanString(string name, out ReadOnlySpan newName) { - return CleanStringParser.Clean(name, _options.CleanStringRegexes); + return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } public CleanDateTimeResult CleanDateTime(string name) diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index 7c3270ebcc..fde06c5a17 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -1,4 +1,5 @@ -using Emby.Naming.Common; +using System; +using Emby.Naming.Common; using Emby.Naming.Video; using Xunit; @@ -30,8 +31,15 @@ namespace Jellyfin.Naming.Tests.Video // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] public void CleanStringTest(string input, string expectedName) { - var result = new VideoResolver(_namingOptions).CleanString(input); - Assert.Equal(expectedName, result.Name); + if (new VideoResolver(_namingOptions).TryCleanString(input, out ReadOnlySpan newName)) + { + // TODO: compare spans when XUnit supports it + Assert.Equal(expectedName, newName.ToString()); + } + else + { + Assert.Equal(expectedName, input); + } } } } From ec0ef2a2c5a20b7e6aaa5959b52bf399b0b6dde2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:18:30 +0100 Subject: [PATCH 040/108] Remove useless statement --- Emby.Naming/Video/CleanDateTimeParser.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 8638dddd42..84a14a54f5 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -24,12 +24,8 @@ namespace Emby.Naming.Video { var regexes = _options.CleanDateTimeRegexes; var len = regexes.Length; - CleanDateTimeResult result = new CleanDateTimeResult(name); - if (len == 0) - { - return result; - } + CleanDateTimeResult result = new CleanDateTimeResult(name); for (int i = 0; i < len; i++) { if (TryClean(name, regexes[i], ref result)) From abf03f7d3ad14f026fd439f522403353a7ecec86 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:31:35 +0100 Subject: [PATCH 041/108] Clean up some more --- Emby.Naming/Video/CleanDateTimeParser.cs | 19 +++++------------ Emby.Naming/Video/VideoResolver.cs | 2 +- .../Library/LibraryManager.cs | 21 ++++++------------- 3 files changed, 12 insertions(+), 30 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 84a14a54f5..6c74c07d55 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -2,33 +2,24 @@ #pragma warning disable SA1600 #nullable enable +using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; -using Emby.Naming.Common; namespace Emby.Naming.Video { /// /// . /// - public class CleanDateTimeParser + public static class CleanDateTimeParser { - private readonly NamingOptions _options; - - public CleanDateTimeParser(NamingOptions options) + public static CleanDateTimeResult Clean(string name, IReadOnlyList cleanDateTimeRegexes) { - _options = options; - } - - public CleanDateTimeResult Clean(string name) - { - var regexes = _options.CleanDateTimeRegexes; - var len = regexes.Length; - CleanDateTimeResult result = new CleanDateTimeResult(name); + var len = cleanDateTimeRegexes.Count; for (int i = 0; i < len; i++) { - if (TryClean(name, regexes[i], ref result)) + if (TryClean(name, cleanDateTimeRegexes[i], ref result)) { return result; } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 76e0a5a0ec..f93db24866 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -138,7 +138,7 @@ namespace Emby.Naming.Video public CleanDateTimeResult CleanDateTime(string name) { - return new CleanDateTimeParser(_options).Clean(name); + return CleanDateTimeParser.Clean(name, _options.CleanDateTimeRegexes); } } } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index ae3cdece91..6fb6235541 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -36,7 +36,6 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Library; using MediaBrowser.Model.Net; @@ -54,6 +53,9 @@ namespace Emby.Server.Implementations.Library /// public class LibraryManager : ILibraryManager { + private NamingOptions _namingOptions; + private string[] _videoFileExtensions; + /// /// Gets or sets the postscan tasks. /// @@ -2508,21 +2510,11 @@ namespace Emby.Server.Implementations.Library } public NamingOptions GetNamingOptions() - { - return GetNamingOptionsInternal(); - } - - private NamingOptions _namingOptions; - private string[] _videoFileExtensions; - - private NamingOptions GetNamingOptionsInternal() { if (_namingOptions == null) { - var options = new NamingOptions(); - - _namingOptions = options; - _videoFileExtensions = _namingOptions.VideoFileExtensions.ToArray(); + _namingOptions = new NamingOptions(); + _videoFileExtensions = _namingOptions.VideoFileExtensions; } return _namingOptions; @@ -2533,11 +2525,10 @@ namespace Emby.Server.Implementations.Library var resolver = new VideoResolver(GetNamingOptions()); var result = resolver.CleanDateTime(name); - var cleanName = resolver.CleanString(result.Name); return new ItemLookupInfo { - Name = cleanName.Name, + Name = resolver.TryCleanString(result.Name, out var newName) ? newName.ToString() : result.Name, Year = result.Year }; } From 9f5bbb126e55b23243d22bcfd85fbbb17e10ec17 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 22:29:46 +0100 Subject: [PATCH 042/108] Fix tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 41060426fa..9ce503b8e4 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -177,7 +177,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { - @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](\d{4})([ _\,\.\(\)\[\]\-][^\d]|).*(\d{4})*" + @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19\d{2}|20\d{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19\d{2}|20\d{2})*" }; CleanStrings = new[] From 08c4d3797fd2bb54936d4cba1b71de915432ebd1 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Sun, 12 Jan 2020 21:38:28 +0800 Subject: [PATCH 043/108] add support for AMF hardware encoding on Linux. 1) h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg. 2) Using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu. --- .../MediaEncoding/EncodingHelper.cs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 020f0553ed..a099087628 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2642,22 +2642,11 @@ namespace MediaBrowser.Controller.MediaEncoding else return "-hwaccel dxva2"; } - - switch (videoStream.Codec.ToLowerInvariant()) + else { - case "avc": - case "h264": - if (_mediaEncoder.SupportsDecoder("h264_amf") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_amf"; - } - break; - case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("hevc_amf") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_mmal"; - } - break; + //h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg + //using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu + return "-hwaccel vaapi"; } } } From 2a09f05ff35d7ae9ab4bb0d216a93698814b6821 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Sun, 12 Jan 2020 16:30:31 +0100 Subject: [PATCH 044/108] Fix build --- jellyfin.ruleset | 2 -- 1 file changed, 2 deletions(-) diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 9846367d83..27d8a7cd92 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -33,8 +33,6 @@ - - From ded9857f45388ce5499d09b537c56157c48ca759 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Sun, 12 Jan 2020 18:59:10 +0100 Subject: [PATCH 045/108] Clean up server discovery code --- .../EntryPoints/UdpServerEntryPoint.cs | 58 ++-- .../Net/SocketFactory.cs | 29 -- Emby.Server.Implementations/Net/UdpSocket.cs | 9 - Emby.Server.Implementations/Udp/UdpServer.cs | 265 ++++-------------- MediaBrowser.Model/Net/ISocket.cs | 2 - MediaBrowser.Model/Net/ISocketFactory.cs | 9 - 6 files changed, 74 insertions(+), 298 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 9ee219854d..a83817cb96 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.Udp; using MediaBrowser.Controller; @@ -12,7 +13,7 @@ namespace Emby.Server.Implementations.EntryPoints /// /// Class UdpServerEntryPoint. /// - public class UdpServerEntryPoint : IServerEntryPoint + public sealed class UdpServerEntryPoint : IServerEntryPoint { /// /// The port of the UDP server. @@ -31,61 +32,44 @@ namespace Emby.Server.Implementations.EntryPoints /// The UDP server. /// private UdpServer _udpServer; + private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private bool _disposed = false; /// /// Initializes a new instance of the class. /// public UdpServerEntryPoint( - ILogger logger, - IServerApplicationHost appHost, - IJsonSerializer json, - ISocketFactory socketFactory) + ILogger logger, + IServerApplicationHost appHost) { _logger = logger; _appHost = appHost; - _json = json; - _socketFactory = socketFactory; - } - /// - public Task RunAsync() - { - var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory); - - try - { - udpServer.Start(PortNumber); - - _udpServer = udpServer; - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to start UDP Server"); - } - return Task.CompletedTask; } /// - public void Dispose() + public async Task RunAsync() { - Dispose(true); - GC.SuppressFinalize(this); + _udpServer = new UdpServer(_logger, _appHost); + _udpServer.Start(PortNumber, _cancellationTokenSource.Token); } - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) + /// + public void Dispose() { - if (dispose) + if (_disposed) { - if (_udpServer != null) - { - _udpServer.Dispose(); - } + return; } + + _cancellationTokenSource.Cancel(); + _udpServer.Dispose(); + + _cancellationTokenSource = null; + _udpServer = null; + + _disposed = true; } } } diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 0870db003f..4e04cde78c 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -8,32 +8,6 @@ namespace Emby.Server.Implementations.Net { public class SocketFactory : ISocketFactory { - /// - /// Creates a new UDP acceptSocket and binds it to the specified local port. - /// - /// An integer specifying the local port to bind the acceptSocket to. - public ISocket CreateUdpSocket(int localPort) - { - if (localPort < 0) - { - throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); - } - - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - try - { - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - return new UdpSocket(retVal, localPort, IPAddress.Any); - } - catch - { - retVal?.Dispose(); - - throw; - } - } - public ISocket CreateUdpBroadcastSocket(int localPort) { if (localPort < 0) @@ -156,8 +130,5 @@ namespace Emby.Server.Implementations.Net throw; } } - - public Stream CreateNetworkStream(ISocket socket, bool ownsSocket) - => new NetworkStream(((UdpSocket)socket).Socket, ownsSocket); } } diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs index dde4a2a34c..211ca67841 100644 --- a/Emby.Server.Implementations/Net/UdpSocket.cs +++ b/Emby.Server.Implementations/Net/UdpSocket.cs @@ -181,15 +181,6 @@ namespace Emby.Server.Implementations.Net return taskCompletion.Task; } - public Task ReceiveAsync(CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var buffer = new byte[8192]; - - return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken); - } - public Task SendToAsync(byte[] buffer, int offset, int size, IPEndPoint endPoint, CancellationToken cancellationToken) { ThrowIfDisposed(); diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 185a282ac4..19fc1e316d 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -1,112 +1,47 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net; +using System.Net.Sockets; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller; using MediaBrowser.Model.ApiClient; -using MediaBrowser.Model.Events; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Udp { /// - /// Provides a Udp Server + /// Provides a Udp Server. /// - public class UdpServer : IDisposable + public sealed class UdpServer : IDisposable { /// /// The _logger /// private readonly ILogger _logger; - - private bool _isDisposed; - - private readonly List>> _responders = new List>>(); - private readonly IServerApplicationHost _appHost; - private readonly IJsonSerializer _json; /// - /// Initializes a new instance of the class. + /// The _udp client. /// - public UdpServer(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory) - { - _logger = logger; - _appHost = appHost; - _json = json; - _socketFactory = socketFactory; - - AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message); - } + private Socket _udpSocket; + private IPEndPoint _endpoint; + private readonly byte[] _receiveBuffer = new byte[8192]; - private void AddMessageResponder(string message, bool isSubstring, Func responder) - { - _responders.Add(new Tuple>(message, isSubstring, responder)); - } + private bool _disposed = false; /// - /// Raises the event. + /// Initializes a new instance of the class. /// - private async void OnMessageReceived(GenericEventArgs e) - { - var message = e.Argument; - - var encoding = Encoding.UTF8; - var responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding); - - if (responder == null) - { - encoding = Encoding.Unicode; - responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding); - } - - if (responder != null) - { - var cancellationToken = CancellationToken.None; - - try - { - await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in OnMessageReceived"); - } - } - } - - private Tuple>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding) + public UdpServer(ILogger logger, IServerApplicationHost appHost) { - var text = encoding.GetString(buffer, 0, bytesReceived); - var responder = _responders.FirstOrDefault(i => - { - if (i.Item2) - { - return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1; - } - return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase); - }); - - if (responder == null) - { - return null; - } - return new Tuple>>(text, responder); + _logger = logger; + _appHost = appHost; } - private async Task RespondToV2Message(string messageText, IPEndPoint endpoint, Encoding encoding, CancellationToken cancellationToken) + private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken) { - var parts = messageText.Split('|'); - var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false); if (!string.IsNullOrEmpty(localUrl)) @@ -118,8 +53,16 @@ namespace Emby.Server.Implementations.Udp Name = _appHost.FriendlyName }; - await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint, cancellationToken).ConfigureAwait(false); + try + { + await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false); + } + catch (SocketException ex) + { + _logger.LogError(ex, "Error sending response message"); + } + var parts = messageText.Split('|'); if (parts.Length > 1) { _appHost.EnableLoopback(parts[1]); @@ -131,162 +74,60 @@ namespace Emby.Server.Implementations.Udp } } - /// - /// The _udp client - /// - private ISocket _udpClient; - private readonly ISocketFactory _socketFactory; - /// /// Starts the specified port. /// /// The port. - public void Start(int port) - { - _udpClient = _socketFactory.CreateUdpSocket(port); - - Task.Run(() => BeginReceive()); - } - - private readonly byte[] _receiveBuffer = new byte[8192]; - - private void BeginReceive() + /// + public void Start(int port, CancellationToken cancellationToken) { - if (_isDisposed) - { - return; - } + _endpoint = new IPEndPoint(IPAddress.Any, port); - try - { - var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult); + _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + _udpSocket.Bind(_endpoint); - if (result.CompletedSynchronously) - { - OnReceiveResult(result); - } - } - catch (ObjectDisposedException) - { - //TODO Investigate and properly fix. - } - catch (Exception ex) - { - _logger.LogError(ex, "Error receiving udp message"); - } - } - - private void OnReceiveResult(IAsyncResult result) - { - if (_isDisposed) - { - return; - } - - try - { - var socketResult = _udpClient.EndReceive(result); - - OnMessageReceived(socketResult); - } - catch (ObjectDisposedException) - { - //TODO Investigate and properly fix. - } - catch (Exception ex) - { - _logger.LogError(ex, "Error receiving udp message"); - } - - BeginReceive(); + _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); } - /// - /// Called when [message received]. - /// - /// The message. - private void OnMessageReceived(SocketReceiveResult message) + private async Task BeginReceiveAsync(CancellationToken cancellationToken) { - if (_isDisposed) - { - return; - } - - if (message.RemoteEndPoint.Port == 0) + while (!cancellationToken.IsCancellationRequested) { - return; - } - - try - { - OnMessageReceived(new GenericEventArgs + try { - Argument = message - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error handling UDP message"); - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - } + var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint).ConfigureAwait(false); - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - _isDisposed = true; + cancellationToken.ThrowIfCancellationRequested(); - if (_udpClient != null) + var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes); + if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase)) + { + await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false); + } + } + catch (SocketException ex) { - _udpClient.Dispose(); + _logger.LogError(ex, "Failed to receive data drom socket"); + } + catch (OperationCanceledException) + { + // Don't throw } } } - public async Task SendAsync(byte[] bytes, IPEndPoint remoteEndPoint, CancellationToken cancellationToken) + /// + public void Dispose() { - if (_isDisposed) + if (_disposed) { - throw new ObjectDisposedException(GetType().Name); - } - - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes)); - } - - if (remoteEndPoint == null) - { - throw new ArgumentNullException(nameof(remoteEndPoint)); + return; } - try - { - await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false); + _udpSocket?.Dispose(); - _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint); - } - catch (OperationCanceledException) - { - - } - catch (Exception ex) - { - _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint); - } + GC.SuppressFinalize(this); } } - } diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs index f80de5524c..3fdc40bbe2 100644 --- a/MediaBrowser.Model/Net/ISocket.cs +++ b/MediaBrowser.Model/Net/ISocket.cs @@ -14,8 +14,6 @@ namespace MediaBrowser.Model.Net Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); - int Receive(byte[] buffer, int offset, int count); - IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback); SocketReceiveResult EndReceive(IAsyncResult result); diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index 2f857f1af0..dc69b1fb25 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -8,13 +8,6 @@ namespace MediaBrowser.Model.Net /// public interface ISocketFactory { - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The local port to bind to. - /// A implementation. - ISocket CreateUdpSocket(int localPort); - ISocket CreateUdpBroadcastSocket(int localPort); /// @@ -30,7 +23,5 @@ namespace MediaBrowser.Model.Net /// The local port to bind to. /// A implementation. ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort); - - Stream CreateNetworkStream(ISocket socket, bool ownsSocket); } } From ea075c1b4805cfabff58739fc4e3de7813a33298 Mon Sep 17 00:00:00 2001 From: gnattu Date: Sun, 12 Jan 2020 13:22:20 -0500 Subject: [PATCH 046/108] Add reminder to remove the workaround This will be no longer needed when ffmpeg is ready Co-Authored-By: dkanada --- MediaBrowser.Api/Playback/UniversalAudioService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index c9d29f8ef6..625ea9ac1f 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -301,6 +301,7 @@ namespace MediaBrowser.Api.Playback var transcodingProfile = deviceProfile.TranscodingProfiles[0]; // hls segment container can only be mpegts or fmp4 per ffmpeg documentation + // TODO: remove this when we switch back to the segment muxer var supportedHLSContainers = new string[] { "mpegts", "fmp4" }; var newRequest = new GetMasterHlsAudioPlaylist From da5893b0f14c6d1efec77e105a6240b241a1c412 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 21:21:20 +0100 Subject: [PATCH 047/108] Try to fix nullreff --- MediaBrowser.Api/Playback/MediaInfoService.cs | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 4b9bb80103..4fa0e31406 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -266,8 +266,7 @@ namespace MediaBrowser.Api.Playback private T Clone(T obj) { - // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it - // Should we move this directly into MediaSourceManager? + var json = JsonSerializer.SerializeToUtf8Bytes(obj); return JsonSerializer.Deserialize(json); } @@ -278,27 +277,20 @@ namespace MediaBrowser.Api.Playback var item = _libraryManager.GetItemById(id); var result = new PlaybackInfoResponse(); + MediaSourceInfo[] mediaSources; if (string.IsNullOrWhiteSpace(liveStreamId)) { - IEnumerable mediaSources; - try - { - // TODO handle supportedLiveMediaTypes ? - mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - mediaSources = new List(); - Logger.LogError(ex, "Could not find media sources for item id {id}", id); - // TODO PlaybackException ?? - //result.ErrorCode = ex.ErrorCode; - } - result.MediaSources = mediaSources.ToArray(); + // TODO handle supportedLiveMediaTypes ? + var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(mediaSourceId)) + if (string.IsNullOrWhiteSpace(mediaSourceId)) { - result.MediaSources = result.MediaSources + mediaSources = mediaSourcesList.ToArray(); + } + else + { + mediaSources = mediaSourcesList .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)) .ToArray(); } @@ -307,11 +299,13 @@ namespace MediaBrowser.Api.Playback { var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false); - result.MediaSources = new MediaSourceInfo[] { mediaSource }; + mediaSources = new MediaSourceInfo[] { mediaSource }; } - if (result.MediaSources.Count == 0) + if (mediaSources.Length == 0) { + result.MediaSources = Array.Empty(); + if (!result.ErrorCode.HasValue) { result.ErrorCode = PlaybackErrorCode.NoCompatibleStream; @@ -319,7 +313,9 @@ namespace MediaBrowser.Api.Playback } else { - result.MediaSources = Clone(result.MediaSources); + // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it + // Should we move this directly into MediaSourceManager? + result.MediaSources = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(mediaSources)); result.PlaySessionId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); } From 84d1b12530b4c53910b300b040fe5f316523427e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 21:55:04 +0100 Subject: [PATCH 048/108] Attempt #2 --- MediaBrowser.Api/Playback/MediaInfoService.cs | 7 ------- MediaBrowser.Model/Dto/MediaSourceInfo.cs | 1 + 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 4fa0e31406..53823943f3 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -264,13 +264,6 @@ namespace MediaBrowser.Api.Playback return ToOptimizedResult(result); } - private T Clone(T obj) - { - - var json = JsonSerializer.SerializeToUtf8Bytes(obj); - return JsonSerializer.Deserialize(json); - } - private async Task GetPlaybackInfo(Guid id, Guid userId, string[] supportedLiveMediaTypes, string mediaSourceId = null, string liveStreamId = null) { var user = _userManager.GetUserById(userId); diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs index 5cb0565666..16a212a81b 100644 --- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs +++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs @@ -76,6 +76,7 @@ namespace MediaBrowser.Model.Dto { Formats = Array.Empty(); MediaStreams = new List(); + MediaAttachments = Array.Empty(); RequiredHttpHeaders = new Dictionary(); SupportsTranscoding = true; SupportsDirectStream = true; From 93ab829df523c36a44ffa2f9caaf96505a2b2e5c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 23:25:57 +0100 Subject: [PATCH 049/108] Attempt #3 --- MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs index 7fa7afa5b3..0b2f1d231e 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs @@ -225,7 +225,7 @@ namespace MediaBrowser.MediaEncoding.Probing /// /// The start_pts. [JsonPropertyName("start_pts")] - public int StartPts { get; set; } + public long StartPts { get; set; } /// /// Gets or sets the is_avc. From 56f580cdf6eb1a84275a582c4dc7dfb8245cc347 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 23:57:13 +0100 Subject: [PATCH 050/108] Add test to prevent regressions --- .../EncoderValidatorTestsData.cs | 6 +- .../FFprobeParserTests.cs | 22 ++++ .../Jellyfin.MediaEncoding.Tests.csproj | 6 + .../Test Data/ffprobe1.json | 105 ++++++++++++++++++ 4 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json diff --git a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs index 12fde07705..c46c9578b9 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs @@ -26,7 +26,7 @@ libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100"; - public const string FFmpegV414Output = @"ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegV414Output = @"ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8 (Raspbian 8.3.0-6+rpi1) configuration: --prefix=/usr --extra-version='1~deb10u1' --toolchain=hardened --libdir=/usr/lib/arm-linux-gnueabihf --incdir=/usr/include/arm-linux-gnueabihf --arch=arm --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared libavutil 56. 22.100 / 56. 22.100 @@ -39,7 +39,7 @@ libswscale 5. 3.100 / 5. 3.100 libswresample 3. 3.100 / 3. 3.100 libpostproc 55. 3.100 / 55. 3.100"; - public const string FFmpegV404Output = @"ffmpeg version 4.0.4 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegV404Output = @"ffmpeg version 4.0.4 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8 (Debian 8.3.0-6) configuration: --toolchain=hardened --prefix=/usr --target-os=linux --enable-cross-compile --extra-cflags=--static --enable-gpl --enable-static --disable-doc --disable-ffplay --disable-shared --disable-libxcb --disable-sdl2 --disable-xlib --enable-libfontconfig --enable-fontconfig --enable-gmp --enable-gnutls --enable-libass --enable-libbluray --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libx264 --enable-libx265 --enable-libzvbi --enable-omx --enable-omx-rpi --enable-version3 --enable-vaapi --enable-vdpau --arch=amd64 --enable-nvenc --enable-nvdec libavutil 56. 14.100 / 56. 14.100 @@ -51,7 +51,7 @@ libswscale 5. 1.100 / 5. 1.100 libswresample 3. 1.100 / 3. 1.100 libpostproc 55. 1.100 / 55. 1.100"; - public const string FFmpegGitUnknownOutput = @"ffmpeg version N-94303-g7cb4f8c962 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegGitUnknownOutput = @"ffmpeg version N-94303-g7cb4f8c962 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9.1.1 (GCC) 20190716 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 30.100 / 56. 30.100 diff --git a/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs new file mode 100644 index 0000000000..2032f6cecd --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs @@ -0,0 +1,22 @@ +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using MediaBrowser.MediaEncoding.Probing; +using Xunit; + +namespace Jellyfin.MediaEncoding.Tests +{ + public class FFprobeParserTests + { + [Theory] + [InlineData("ffprobe1.json")] + public async Task Test(string fileName) + { + var path = Path.Join("Test Data", fileName); + using (var stream = File.OpenRead(path)) + { + await JsonSerializer.DeserializeAsync(stream).ConfigureAwait(false); + } + } + } +} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 7f6b905332..5d9b32086c 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -5,6 +5,12 @@ false + + + PreserveNewest + + + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json new file mode 100644 index 0000000000..cdad5df502 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json @@ -0,0 +1,105 @@ +{ + "streams": [ + { + "index": 0, + "codec_name": "h264", + "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", + "profile": "Main", + "codec_type": "video", + "codec_time_base": "1/50", + "codec_tag_string": "[27][0][0][0]", + "codec_tag": "0x001b", + "width": 1920, + "height": 1080, + "coded_width": 1920, + "coded_height": 1080, + "has_b_frames": 0, + "sample_aspect_ratio": "0:1", + "display_aspect_ratio": "0:1", + "pix_fmt": "yuvj420p", + "level": 42, + "color_range": "pc", + "color_space": "bt709", + "color_transfer": "bt709", + "color_primaries": "bt709", + "chroma_location": "left", + "field_order": "progressive", + "refs": 1, + "is_avc": "false", + "nal_length_size": "0", + "id": "0x1", + "r_frame_rate": "25/1", + "avg_frame_rate": "25/1", + "time_base": "1/90000", + "start_pts": 8570867078, + "start_time": "95231.856422", + "duration_ts": 31694552, + "duration": "352.161689", + "bits_per_raw_sample": "8", + "disposition": { + "default": 0, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + } + }, + { + "index": 1, + "codec_name": "aac", + "codec_long_name": "AAC (Advanced Audio Coding)", + "profile": "LC", + "codec_type": "audio", + "codec_time_base": "1/44100", + "codec_tag_string": "[15][0][0][0]", + "codec_tag": "0x000f", + "sample_fmt": "fltp", + "sample_rate": "44100", + "channels": 2, + "channel_layout": "stereo", + "bits_per_sample": 0, + "id": "0x2", + "r_frame_rate": "0/0", + "avg_frame_rate": "0/0", + "time_base": "1/90000", + "start_pts": 8570867697, + "start_time": "95231.863300", + "duration_ts": 31695687, + "duration": "352.174300", + "bit_rate": "98191", + "disposition": { + "default": 0, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + } + } + ], + "format": { + "filename": "TS Test record.ts", + "nb_streams": 2, + "nb_programs": 1, + "format_name": "mpegts", + "format_long_name": "MPEG-TS (MPEG-2 Transport Stream)", + "start_time": "95231.856422", + "duration": "352.181178", + "size": "179003772", + "bit_rate": "4066174", + "probe_score": 50 + } +} From a8cd963d468ba4fb4caa003d9eb927117a3afa77 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:25:54 +0900 Subject: [PATCH 051/108] fix tests for absolute paths --- .ci/azure-pipelines.yml | 2 +- .../IO/ManagedFileSystem.cs | 35 +++++++++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 7bcaed70cd..d69cc4943e 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -112,7 +112,7 @@ jobs: - job: main_test displayName: Main Test pool: - vmImage: windows-latest + vmImage: ubuntu-latest steps: - checkout: self clean: true diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index e27081c45a..bf2173d79b 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -3,8 +3,8 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -17,7 +17,7 @@ using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; namespace Emby.Server.Implementations.IO { /// - /// Class ManagedFileSystem + /// Class ManagedFileSystem. /// public class ManagedFileSystem : IFileSystem { @@ -80,20 +80,20 @@ namespace Emby.Server.Implementations.IO public virtual string MakeAbsolutePath(string folderPath, string filePath) { - if (string.IsNullOrWhiteSpace(filePath) - // stream - || filePath.Contains("://")) + // path is actually a stream + if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.InvariantCulture)) { return filePath; } if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/') { - return filePath; // absolute local path + // absolute local path + return filePath; } // unc path - if (filePath.StartsWith("\\\\")) + if (filePath.StartsWith("\\\\", StringComparison.InvariantCulture)) { return filePath; } @@ -101,13 +101,16 @@ namespace Emby.Server.Implementations.IO var firstChar = filePath[0]; if (firstChar == '/') { - // For this we don't really know. + // for this we don't really know return filePath; } - if (firstChar == '\\') //relative path + + // relative path + if (firstChar == '\\') { filePath = filePath.Substring(1); } + try { return Path.GetFullPath(Path.Combine(folderPath, filePath)); @@ -131,11 +134,7 @@ namespace Emby.Server.Implementations.IO /// /// The shortcut path. /// The target. - /// - /// shortcutPath - /// or - /// target - /// + /// The shortcutPath or target is null. public virtual void CreateShortcut(string shortcutPath, string target) { if (string.IsNullOrEmpty(shortcutPath)) @@ -281,11 +280,11 @@ namespace Emby.Server.Implementations.IO } /// - /// Takes a filename and removes invalid characters + /// Takes a filename and removes invalid characters. /// /// The filename. /// System.String. - /// filename + /// The filename is null. public virtual string GetValidFilename(string filename) { var builder = new StringBuilder(filename); @@ -473,7 +472,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetReadOnly(string path, bool isReadOnly) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } @@ -497,7 +496,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } From 65e9a705d303ebfadbc58035f9763966141ee437 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:34:50 +0900 Subject: [PATCH 052/108] check operating system for absolute path test --- .ci/azure-pipelines.yml | 2 +- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 ++-- .../IO/ManagedFileSystemTests.cs | 13 ++++++++++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index d69cc4943e..7bcaed70cd 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -112,7 +112,7 @@ jobs: - job: main_test displayName: Main Test pool: - vmImage: ubuntu-latest + vmImage: windows-latest steps: - checkout: self clean: true diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index bf2173d79b..1fd8ddc4d4 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -448,7 +448,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetHidden(string path, bool isHidden) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } @@ -779,7 +779,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetExecutable(string path) { - if (OperatingSystem.Id == MediaBrowser.Model.System.OperatingSystemId.Darwin) + if (OperatingSystem.Id == OperatingSystemId.Darwin) { RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path)); } diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index f2a8e447fa..b2aa01e655 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -1,6 +1,8 @@ +using System; using AutoFixture; using AutoFixture.AutoMoq; using Emby.Server.Implementations.IO; +using MediaBrowser.Model.System; using Xunit; namespace Jellyfin.Server.Implementations.Tests.IO @@ -26,7 +28,16 @@ namespace Jellyfin.Server.Implementations.Tests.IO string expectedAbsolutePath) { var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath); - Assert.Equal(expectedAbsolutePath, generatedPath); + + if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) + { + var windowsPath = "d:" + generatedPath.Replace('/', '\\'); + Assert.Equal(expectedAbsolutePath, windowsPath); + } + else + { + Assert.Equal(expectedAbsolutePath, generatedPath); + } } } } From d00fd7ca82d33e90c87a5a6c02a1eb8505babfcf Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:43:06 +0900 Subject: [PATCH 053/108] switch two incorrectly used variables --- .../IO/ManagedFileSystemTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index b2aa01e655..182c709982 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,8 +31,8 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var windowsPath = "d:" + generatedPath.Replace('/', '\\'); - Assert.Equal(expectedAbsolutePath, windowsPath); + var expectedWindowsPath = "d:" + expectedAbsolutePath.Replace('/', '\\'); + Assert.Equal(expectedWindowsPath, generatedPath); } else { From 665ca5cf1fcd6c757f214998d121e3f6a50fb8f3 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 09:00:30 +0100 Subject: [PATCH 054/108] Update UdpServer.cs --- Emby.Server.Implementations/Udp/UdpServer.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 19fc1e316d..c91d137a72 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -22,9 +22,6 @@ namespace Emby.Server.Implementations.Udp private readonly ILogger _logger; private readonly IServerApplicationHost _appHost; - /// - /// The _udp client. - /// private Socket _udpSocket; private IPEndPoint _endpoint; private readonly byte[] _receiveBuffer = new byte[8192]; From cf13e89ad6d086cc20acd877a76df23900b222a9 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 09:01:14 +0100 Subject: [PATCH 055/108] Update MediaBrowser.Api/Playback/MediaInfoService.cs Co-Authored-By: dkanada --- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 53823943f3..10f10a15ec 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.Api.Playback if (string.IsNullOrWhiteSpace(liveStreamId)) { - // TODO handle supportedLiveMediaTypes ? + // TODO handle supportedLiveMediaTypes? var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(mediaSourceId)) From 9eac19c75ad9c69c0c30ae90c0772856e7b0ce9e Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:09:22 +0900 Subject: [PATCH 056/108] change invariant culture to ordinal --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 1fd8ddc4d4..68417876cf 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -81,7 +81,7 @@ namespace Emby.Server.Implementations.IO public virtual string MakeAbsolutePath(string folderPath, string filePath) { // path is actually a stream - if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.InvariantCulture)) + if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.Ordinal)) { return filePath; } @@ -93,7 +93,7 @@ namespace Emby.Server.Implementations.IO } // unc path - if (filePath.StartsWith("\\\\", StringComparison.InvariantCulture)) + if (filePath.StartsWith("\\\\", StringComparison.Ordinal)) { return filePath; } From d461f46befb06dae742ab523a3b28dadbff853f3 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:31:14 +0900 Subject: [PATCH 057/108] ignore drive name in windows environments --- .../IO/ManagedFileSystemTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 182c709982..de227cd859 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,7 +31,7 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var expectedWindowsPath = "d:" + expectedAbsolutePath.Replace('/', '\\'); + var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\').Split(':')[1]; Assert.Equal(expectedWindowsPath, generatedPath); } else From 536237c35dc74205e25593667add97695a27f0f2 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:37:07 +0900 Subject: [PATCH 058/108] move the split usage to the proper location --- .../IO/ManagedFileSystemTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index de227cd859..e324002f0c 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,8 +31,8 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\').Split(':')[1]; - Assert.Equal(expectedWindowsPath, generatedPath); + var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\'); + Assert.Equal(expectedWindowsPath, generatedPath.Split(':')[1]); } else { From 9c2c31b0c63b12ff303790f1294eeccb6adea252 Mon Sep 17 00:00:00 2001 From: punkch Date: Fri, 10 Jan 2020 23:42:06 +0000 Subject: [PATCH 059/108] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index 46c10d912e..9441da5915 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -16,7 +16,7 @@ "Folders": "Папки", "Genres": "Жанрове", "HeaderAlbumArtists": "Изпълнители на албуми", - "HeaderCameraUploads": "", + "HeaderCameraUploads": "Качени от камера", "HeaderContinueWatching": "Продължаване на гледането", "HeaderFavoriteAlbums": "Любими албуми", "HeaderFavoriteArtists": "Любими изпълнители", @@ -25,7 +25,7 @@ "HeaderFavoriteSongs": "Любими песни", "HeaderLiveTV": "Телевизия на живо", "HeaderNextUp": "Следва", - "HeaderRecordingGroups": "", + "HeaderRecordingGroups": "Запис групи", "HomeVideos": "Домашни клипове", "Inherit": "Наследяване", "ItemAddedWithName": "{0} е добавено към библиотеката", @@ -34,7 +34,7 @@ "LabelRunningTimeValue": "", "Latest": "Последни", "MessageApplicationUpdated": "Сървърът е обновен", - "MessageApplicationUpdatedTo": "", + "MessageApplicationUpdatedTo": "Сървърът е обновен до {0}", "MessageNamedServerConfigurationUpdatedWithValue": "", "MessageServerConfigurationUpdated": "", "MixedContent": "Смесено съдържание", From 31347de792cec994ac9796628e161eaac4bbaf4a Mon Sep 17 00:00:00 2001 From: Philmo67 Date: Fri, 10 Jan 2020 15:17:30 +0000 Subject: [PATCH 060/108] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 6b25e3df0f..ff70733359 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -11,11 +11,11 @@ "Collections": "Collections", "DeviceOfflineWithName": "{0} s'est déconnecté", "DeviceOnlineWithName": "{0} est connecté", - "FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}", + "FailedLoginAttemptWithUserName": "Échec de connexion de {0}", "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes de l'album", + "HeaderAlbumArtists": "Artistes d'album", "HeaderCameraUploads": "Photos transférées", "HeaderContinueWatching": "Continuer à regarder", "HeaderFavoriteAlbums": "Albums favoris", From faf898ea0d8fc5d0dcd6d98a0d4cfc95d4126a6d Mon Sep 17 00:00:00 2001 From: hbo Date: Fri, 10 Jan 2020 15:18:30 +0000 Subject: [PATCH 061/108] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index ff70733359..90754e4155 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -34,7 +34,7 @@ "LabelRunningTimeValue": "Durée : {0}", "Latest": "Derniers", "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour", - "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers {0}", + "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour en version {0}", "MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour", "MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour", "MixedContent": "Contenu mixte", From 7b91df199401e299463264b3b6bbae729bf51499 Mon Sep 17 00:00:00 2001 From: Alexander Brissman Date: Fri, 10 Jan 2020 21:46:39 +0000 Subject: [PATCH 062/108] =?UTF-8?q?Translated=20using=20Weblate=20(Norwegi?= =?UTF-8?q?an=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Translat?= =?UTF-8?q?e-URL:=20https://translate.jellyfin.org/projects/jellyfin/jelly?= =?UTF-8?q?fin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Emby.Server.Implementations/Localization/Core/nb.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index 7d4b2bdac1..f9fa1b68cd 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -62,7 +62,7 @@ "NotificationOptionVideoPlayback": "Videoavspilling startet", "NotificationOptionVideoPlaybackStopped": "Videoavspilling stoppet", "Photos": "Bilder", - "Playlists": "Spliielister", + "Playlists": "Spillelister", "Plugin": "Plugin", "PluginInstalledWithName": "{0} ble installert", "PluginUninstalledWithName": "{0} ble avinstallert", From ab0130e9e288c92d8e11abc8067c69c6bb13e468 Mon Sep 17 00:00:00 2001 From: Z Yang Date: Sat, 11 Jan 2020 13:18:35 +0000 Subject: [PATCH 063/108] Translated using Weblate (Chinese (Simplified)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hans/ --- Emby.Server.Implementations/Localization/Core/zh-CN.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index a4d53c57e9..a567e6e2d3 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -3,9 +3,9 @@ "AppDeviceValues": "应用: {0}, 设备: {1}", "Application": "应用程序", "Artists": "艺术家", - "AuthenticationSucceededWithUserName": "{0} 认证成功", + "AuthenticationSucceededWithUserName": "{0} 验证成功", "Books": "书籍", - "CameraImageUploadedFrom": "已从 {0} 上传了一张新的相片", + "CameraImageUploadedFrom": "新的相机图像已从 {0} 上传", "Channels": "频道", "ChapterNameValue": "章节 {0}", "Collections": "合集", @@ -18,7 +18,7 @@ "HeaderAlbumArtists": "专辑作家", "HeaderCameraUploads": "相机上传", "HeaderContinueWatching": "继续观看", - "HeaderFavoriteAlbums": "最爱的专辑", + "HeaderFavoriteAlbums": "收藏的专辑", "HeaderFavoriteArtists": "最爱的艺术家", "HeaderFavoriteEpisodes": "最爱的剧集", "HeaderFavoriteShows": "最爱的节目", From 138bff43270279f46358c39cc03666fb3ee331b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Slobodan=20Simi=C4=87?= Date: Fri, 10 Jan 2020 20:27:47 +0000 Subject: [PATCH 064/108] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- .../Localization/Core/sr.json | 97 ++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 0967ef424b..da0088991b 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -1 +1,96 @@ -{} +{ + "UserPolicyUpdatedWithName": "Корисничке смернице ажуриране за {0}", + "NotificationOptionUserLockedOut": "Корисник закључан", + "VersionNumber": "Верзија {0}", + "ValueSpecialEpisodeName": "Специјал - {0}", + "ValueHasBeenAddedToLibrary": "{0} је додато у вашу медијску библиотеку", + "UserStoppedPlayingItemWithValues": "{0} заврши пуштање {1} на {2}", + "UserStartedPlayingItemWithValues": "{0} пушта {1} на {2}", + "UserPasswordChangedWithName": "Лозинка је промењена за корисника {0}", + "UserOnlineFromDevice": "{0} је на вези од {1}", + "UserOfflineFromDevice": "{0} се одвезао са {1}", + "UserLockedOutWithName": "Корисник {0} је закључан", + "UserDownloadingItemWithValues": "{0} преузима {1}", + "UserDeletedWithName": "Корисник {0} је обрисан", + "UserCreatedWithName": "Корисник {0} је направљен", + "User": "Корисник", + "TvShows": "ТВ серије", + "System": "Систем", + "Sync": "Усклади", + "SubtitlesDownloadedForItem": "Титлови преузети за {0}", + "SubtitleDownloadFailureFromForItem": "Неуспело преузимање титлова за {1} са {0}", + "StartupEmbyServerIsLoading": "Џелифин сервер се подиже. Покушајте поново убрзо.", + "Songs": "Песме", + "Shows": "Серије", + "ServerNameNeedsToBeRestarted": "{0} треба поново покренути", + "ScheduledTaskStartedWithName": "{0} покренуто", + "ScheduledTaskFailedWithName": "{0} неуспело", + "ProviderValue": "Пружалац: {0}", + "PluginUpdatedWithName": "{0} ажуриран", + "PluginUninstalledWithName": "{0} деинсталиран", + "PluginInstalledWithName": "{0} инсталиран", + "Plugin": "Прикључак", + "Playlists": "Листе", + "Photos": "Фотографије", + "NotificationOptionVideoPlaybackStopped": "Заустављено пуштање видеа", + "NotificationOptionVideoPlayback": "Покренуто пуштање видеа", + "NotificationOptionTaskFailed": "Неуспешан заказани посао", + "NotificationOptionServerRestartRequired": "Потребан је рестарт сервера", + "NotificationOptionPluginUpdateInstalled": "Ажурирање прикључка инсталирано", + "NotificationOptionPluginUninstalled": "Прикључак уклоњен", + "NotificationOptionPluginInstalled": "Прикључак инсталиран", + "NotificationOptionPluginError": "Грешка прикључка", + "NotificationOptionNewLibraryContent": "Додат нови садржај", + "NotificationOptionInstallationFailed": "Неуспела инсталација", + "NotificationOptionCameraImageUploaded": "Слика са камере послата", + "NotificationOptionAudioPlaybackStopped": "Заустављено пуштање звука", + "NotificationOptionAudioPlayback": "Покренуто пуштање звука", + "NotificationOptionApplicationUpdateInstalled": "Ажурирање инсталирано", + "NotificationOptionApplicationUpdateAvailable": "Доступно је ажурирање за апликацију", + "NewVersionIsAvailable": "Нова верзија Џелифин сервера је доступна за преузимање.", + "NameSeasonUnknown": "Непозната сезона", + "NameSeasonNumber": "Сезона {0}", + "NameInstallFailed": "Инсталација {0} није успела", + "MusicVideos": "Музички спотови", + "Music": "Музика", + "Movies": "Филмови", + "MixedContent": "Мешовит садржај", + "MessageServerConfigurationUpdated": "Серверска поставка је ажурирана", + "MessageNamedServerConfigurationUpdatedWithValue": "Одељак серверске поставке {0} је ажуриран", + "MessageApplicationUpdatedTo": "Џелифин сервер је ажуриран на {0}", + "MessageApplicationUpdated": "Џелифин сервер је ажуриран", + "Latest": "Последње", + "LabelRunningTimeValue": "Време рада: {0}", + "LabelIpAddressValue": "ИП адреса: {0}", + "ItemRemovedWithName": "{0} уклоњено из библиотеке", + "ItemAddedWithName": "{0} додато у библиотеку", + "Inherit": "Наследи", + "HomeVideos": "Кућни видео", + "HeaderRecordingGroups": "Групе снимања", + "HeaderNextUp": "Следеће горе", + "HeaderLiveTV": "ТВ уживо", + "HeaderFavoriteSongs": "Омиљене песме", + "HeaderFavoriteShows": "Омиљене серије", + "HeaderFavoriteEpisodes": "Омиљене епизоде", + "HeaderFavoriteArtists": "Омиљени извођачи", + "HeaderFavoriteAlbums": "Омиљени албуми", + "HeaderContinueWatching": "Настави гледање", + "HeaderCameraUploads": "Слања са камере", + "HeaderAlbumArtists": "Извођачи албума", + "Genres": "Жанрови", + "Folders": "Фасцикле", + "Favorites": "Омиљено", + "FailedLoginAttemptWithUserName": "Неуспела пријава са {0}", + "DeviceOnlineWithName": "{0} се повезао", + "DeviceOfflineWithName": "{0} се одвезао", + "Collections": "Колекције", + "ChapterNameValue": "Поглавље {0}", + "Channels": "Канали", + "CameraImageUploadedFrom": "Нова фотографија је послата са {0}", + "Books": "Књиге", + "AuthenticationSucceededWithUserName": "{0} успешно проверено", + "Artists": "Извођач", + "Application": "Апликација", + "AppDeviceValues": "Апл: {0}, уређај: {1}", + "Albums": "Албуми" +} From 65fe243afbcc4b596cf8726708c1965cd34b5f68 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 19:44:17 +0100 Subject: [PATCH 065/108] Add thread ID and source to logging --- Jellyfin.Server/Jellyfin.Server.csproj | 1 + Jellyfin.Server/Program.cs | 6 ++++-- Jellyfin.Server/Resources/Configuration/logging.json | 7 ++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 166e22909d..62bf5b0fbd 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -42,6 +42,7 @@ + diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 712990a1ee..8f44327971 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -475,17 +475,19 @@ namespace Jellyfin.Server Serilog.Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() + .Enrich.WithThreadId() .CreateLogger(); } catch (Exception ex) { Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}") .WriteTo.Async(x => x.File( Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")) + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}")) .Enrich.FromLogContext() + .Enrich.WithThreadId() .CreateLogger(); Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration"); diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json index e85ef05afd..6bc2ed2ee4 100644 --- a/Jellyfin.Server/Resources/Configuration/logging.json +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -5,7 +5,7 @@ { "Name": "Console", "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}" } }, { @@ -20,12 +20,13 @@ "retainedFileCountLimit": 3, "rollOnFileSizeLimit": true, "fileSizeLimitBytes": 100000000, - "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}" } } ] } } - ] + ], + "Enrich": [ "FromLogContext", "WithThreadId" ] } } From 402691b5e1e1b753ba88fda64ffc877b96c78ecf Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 17:16:43 -0500 Subject: [PATCH 066/108] Explicitly ask for ffmpeg logs gimme yo ffmpeg logs, yo --- .github/ISSUE_TEMPLATE/media_playback.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 93af33fbfd..5b3cb834e2 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,10 @@ assignees: '' **Logs** - + + +**FFmpeg Logs** + **Stats for Nerds Screenshots** From cd5e5cda61fe1da1501bc0e5956684ac851eefd1 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 21:25:21 -0500 Subject: [PATCH 067/108] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 5b3cb834e2..b2bd717b04 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,7 @@ assignees: '' **Logs** - + **FFmpeg Logs** @@ -32,4 +32,3 @@ assignees: '' - Client: [e.g. Web/Browser, webOS, Android, Android TV, Electron] - Browser (if Web client): [e.g. Firefox, Chrome, Safari] - Client and Browser Version: [e.g. 10.3.4 and 68.0] - From c1350f30d20029932c1e6734c7fb9e85c6a0b75a Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 21:25:41 -0500 Subject: [PATCH 068/108] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index b2bd717b04..97e3785910 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -14,7 +14,7 @@ assignees: '' **FFmpeg Logs** - + **Stats for Nerds Screenshots** From da91b4fa4c10e6d2579291895bc32cd3a41f7bbd Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Mon, 13 Jan 2020 16:22:52 +0100 Subject: [PATCH 069/108] Split CI testing files Switch to cobertura for code coverage Switch to dotnet test for tests Add matrix run for different platforms Add extra variables for easier maintenance --- .ci/azure-pipelines-compat.yml | 96 ++++++++++ .ci/azure-pipelines-main.yml | 101 ++++++++++ .ci/azure-pipelines-test.yml | 68 +++++++ .ci/azure-pipelines-windows.yml | 82 ++++++++ .ci/azure-pipelines.yml | 326 +++----------------------------- .ci/publish-nightly.yml | 46 ----- .ci/publish-release.yml | 48 ----- tests/coverletArgs.runsettings | 17 ++ 8 files changed, 389 insertions(+), 395 deletions(-) create mode 100644 .ci/azure-pipelines-compat.yml create mode 100644 .ci/azure-pipelines-main.yml create mode 100644 .ci/azure-pipelines-test.yml create mode 100644 .ci/azure-pipelines-windows.yml delete mode 100644 .ci/publish-nightly.yml delete mode 100644 .ci/publish-release.yml create mode 100644 tests/coverletArgs.runsettings diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml new file mode 100644 index 0000000000..ac23e0b6db --- /dev/null +++ b/.ci/azure-pipelines-compat.yml @@ -0,0 +1,96 @@ +parameters: + - name: Packages + type: object + default: {} + - name: LinuxImage + type: string + default: "ubuntu-latest" + - name: DotNetSdkVersion + type: string + default: 3.1.100 + +jobs: + - job: CompatibilityCheck + displayName: Compatibility Check + pool: + vmImage: "${{ parameters.LinuxImage}}" + # only execute for pull requests + condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) + strategy: + matrix: + ${{ each Package in parameters.Packages }}: + ${{ Package.key }}: + NugetPackageName: ${{ Package.value.NugetPackageName }} + AssemblyFileName: ${{ Package.value.AssemblyFileName }} + maxParallel: 2 + dependsOn: MainBuild + steps: + - checkout: none + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DownloadPipelineArtifact@2 + displayName: "Download New Assembly Build Artifact" + inputs: + source: "current" # Options: current, specific + artifact: "$(NugetPackageName)" # Optional + path: "$(System.ArtifactsDirectory)/new-artifacts" + runVersion: "latest" # Required when source == Specific. Options: latest, latestFromBranch, specific + + - task: CopyFiles@2 + displayName: "Copy New Assembly Build Artifact" + inputs: + sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional + contents: "**/*.dll" + targetFolder: $(System.ArtifactsDirectory)/new-release + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: DownloadPipelineArtifact@2 + displayName: "Download Reference Assembly Build Artifact" + inputs: + source: "specific" # Options: current, specific + artifact: "$(NugetPackageName)" # Optional + path: "$(System.ArtifactsDirectory)/current-artifacts" + project: "$(System.TeamProjectId)" # Required when source == Specific + pipeline: "$(System.DefinitionId)" # Required when source == Specific + runVersion: "latestFromBranch" # Required when source == Specific. Options: latest, latestFromBranch, specific + runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" # Required when source == Specific && runVersion == LatestFromBranch + + - task: CopyFiles@2 + displayName: "Copy Reference Assembly Build Artifact" + inputs: + sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional + contents: "**/*.dll" + targetFolder: $(System.ArtifactsDirectory)/current-release + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: DownloadGitHubRelease@0 + displayName: "Download ABI Compatibility Check Tool" + inputs: + connection: Jellyfin Release Download + userRepository: EraYaN/dotnet-compatibility + defaultVersionType: "latest" # Options: latest, specificVersion, specificTag + itemPattern: "**-ci.zip" # Optional + downloadPath: "$(System.ArtifactsDirectory)" + + - task: ExtractFiles@1 + displayName: "Extract ABI Compatibility Check Tool" + inputs: + archiveFilePatterns: "$(System.ArtifactsDirectory)/*-ci.zip" + destinationFolder: $(System.ArtifactsDirectory)/tools + cleanDestinationFolder: true + + # The `--warnings-only` switch will swallow the return code and not emit any errors. + - task: CmdLine@2 + displayName: "Execute ABI Compatibility Check Tool" + inputs: + script: "dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only" + workingDirectory: $(System.ArtifactsDirectory) # Optional \ No newline at end of file diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml new file mode 100644 index 0000000000..fd263e20f9 --- /dev/null +++ b/.ci/azure-pipelines-main.yml @@ -0,0 +1,101 @@ +parameters: + LinuxImage: "ubuntu-latest" + RestoreBuildProjects: "Jellyfin.Server/Jellyfin.Server.csproj" + DotNetSdkVersion: 3.1.100 + +jobs: + - job: MainBuild + displayName: Main Build + strategy: + matrix: + Release: + BuildConfiguration: Release + Debug: + BuildConfiguration: Debug + maxParallel: 2 + pool: + vmImage: "${{ parameters.LinuxImage }}" + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: true + + - task: CmdLine@2 + displayName: "Clone Web Client (Master, Release, or Tag)" + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: CmdLine@2 + displayName: "Clone Web Client (PR)" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) + inputs: + script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: NodeTool@0 + displayName: "Install Node" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + versionSpec: "10.x" + + - task: CmdLine@2 + displayName: "Build Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: yarn install + workingDirectory: $(Agent.TempDirectory)/jellyfin-web + + - task: CopyFiles@2 + displayName: "Copy Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + contents: "**" + targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: false # Optional + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DotNetCoreCLI@2 + displayName: "Publish Server" + inputs: + command: publish + publishWebProjects: false + projects: "${{ parameters.RestoreBuildProjects }}" + arguments: "--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)" + zipAfterPublish: false + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Naming" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll" + artifactName: "Jellyfin.Naming" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Controller" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll" + artifactName: "Jellyfin.Controller" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Model" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll" + artifactName: "Jellyfin.Model" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Common" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" + artifactName: "Jellyfin.Common" \ No newline at end of file diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml new file mode 100644 index 0000000000..eec02ff3be --- /dev/null +++ b/.ci/azure-pipelines-test.yml @@ -0,0 +1,68 @@ +parameters: + - name: ImageNames + type: object + default: + Linux: "ubuntu-latest" + Windows: "windows-latest" + macOS: "macos-latest" + - name: TestProjects + type: string + default: "tests/**/*Tests.csproj" + - name: DotNetSdkVersion + type: string + default: 3.1.100 + +jobs: + - job: MainTest + displayName: Main Test + strategy: + matrix: + ${{ each imageName in parameters.ImageNames }}: + ${{ imageName.key }}: + ImageName: ${{ imageName.value }} + maxParallel: 3 + pool: + vmImage: "$(ImageName)" + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: false + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DotNetCoreCLI@2 + displayName: Run .NET Core CLI tests + inputs: + command: "test" + projects: ${{ parameters.TestProjects }} + arguments: "--configuration Release --collect:\"XPlat Code Coverage\" --settings tests/coverletArgs.runsettings --verbosity minimal \"-p:GenerateDocumentationFile=False\"" + publishTestResults: true + testRunTitle: $(Agent.JobName) + workingDirectory: "$(Build.SourcesDirectory)" + + + - 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: ReportGenerator (merge) + inputs: + reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' + targetdir: '$(Agent.TempDirectory)/merged/' + reporttypes: 'Cobertura' + + ## V2 is already in the repository but it does not work "wrong number of segments" YAML error. + - 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 + inputs: + codeCoverageTool: 'cobertura' + #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2 + summaryFileLocation: '$(Agent.TempDirectory)/merged/**.xml' + pathToSources: $(Build.SourcesDirectory) # Optional + #reportDirectory: # Optional + #additionalCodeCoverageFiles: # Optional + failIfCoverageEmpty: true # Optional diff --git a/.ci/azure-pipelines-windows.yml b/.ci/azure-pipelines-windows.yml new file mode 100644 index 0000000000..c6ff3736a4 --- /dev/null +++ b/.ci/azure-pipelines-windows.yml @@ -0,0 +1,82 @@ +parameters: + WindowsImage: "windows-latest" + TestProjects: "tests/**/*Tests.csproj" + DotNetSdkVersion: 3.1.100 + +jobs: + - job: PublishWindows + displayName: Publish Windows + pool: + vmImage: ${{ parameters.WindowsImage }} + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: true + + - task: CmdLine@2 + displayName: "Clone Web Client (Master, Release, or Tag)" + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master'), contains(variables['Build.SourceBranch'], 'tag')), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: CmdLine@2 + displayName: "Clone Web Client (PR)" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest')) + inputs: + script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: NodeTool@0 + displayName: "Install Node" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + versionSpec: "10.x" + + - task: CmdLine@2 + displayName: "Build Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: yarn install + workingDirectory: $(Agent.TempDirectory)/jellyfin-web + + - task: CopyFiles@2 + displayName: "Copy Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + contents: "**" + targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: false # Optional + + - task: CmdLine@2 + displayName: "Clone UX Repository" + inputs: + script: git clone --depth=1 https://github.com/jellyfin/jellyfin-ux $(Agent.TempDirectory)\jellyfin-ux + + - task: PowerShell@2 + displayName: "Build NSIS Installer" + inputs: + targetType: "filePath" # Optional. Options: filePath, inline + filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath + arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) + errorActionPreference: "stop" # Optional. Options: stop, continue, silentlyContinue + workingDirectory: $(Build.SourcesDirectory) # Optional + + - task: CopyFiles@2 + displayName: "Copy NSIS Installer" + inputs: + sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional + contents: "jellyfin*.exe" + targetFolder: $(System.ArtifactsDirectory)/setup + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Setup" + condition: succeeded() + inputs: + targetPath: "$(build.artifactstagingdirectory)/setup" + artifactName: "Jellyfin Server Setup" \ No newline at end of file diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 7bcaed70cd..221db162ac 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -2,9 +2,11 @@ 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 pr: autoCancel: true @@ -13,234 +15,26 @@ trigger: batch: true jobs: - - job: main_build - displayName: Main Build - pool: - vmImage: ubuntu-latest - strategy: - matrix: - Release: - BuildConfiguration: Release - Debug: - BuildConfiguration: Debug - maxParallel: 2 - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: true - - - task: CmdLine@2 - displayName: "Clone Web Client (Master, Release, or Tag)" - condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' - - - task: CmdLine@2 - displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) - inputs: - script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' - - - task: NodeTool@0 - displayName: 'Install Node' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - versionSpec: '10.x' - - - task: CmdLine@2 - displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: yarn install - workingDirectory: $(Agent.TempDirectory)/jellyfin-web - - - task: CopyFiles@2 - displayName: 'Copy Web Client' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional - contents: '**' - targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional - - - task: UseDotNet@2 - displayName: 'Update DotNet' - inputs: - packageType: sdk - version: 3.1.100 - - - task: DotNetCoreCLI@2 - displayName: 'Publish Server' - inputs: - command: publish - publishWebProjects: false - projects: '$(RestoreBuildProjects)' - arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)' - zipAfterPublish: false - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Naming' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll' - artifactName: 'Jellyfin.Naming' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Controller' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll' - artifactName: 'Jellyfin.Controller' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Model' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll' - artifactName: 'Jellyfin.Model' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Common' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll' - artifactName: 'Jellyfin.Common' - - - job: main_test - displayName: Main Test - pool: - vmImage: windows-latest - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: false - - - task: DotNetCoreCLI@2 - displayName: Build - inputs: - command: build - publishWebProjects: false - projects: '$(TestProjects)' - arguments: '--configuration $(BuildConfiguration)' - zipAfterPublish: false - - - task: VisualStudioTestPlatformInstaller@1 - inputs: - packageFeedSelector: 'nugetOrg' # Options: nugetOrg, customFeed, netShare - versionSelector: 'latestPreRelease' # Required when packageFeedSelector == NugetOrg || PackageFeedSelector == CustomFeed# Options: latestPreRelease, latestStable, specificVersion - - task: VSTest@2 - inputs: - testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun - testAssemblyVer2: | # Required when testSelector == TestAssemblies - **\bin\$(BuildConfiguration)\**\*tests.dll - **\bin\$(BuildConfiguration)\**\*test.dll - !**\obj\** - !**\xunit.runner.visualstudio.testadapter.dll - !**\xunit.runner.visualstudio.dotnetcore.testadapter.dll - searchFolder: '$(System.DefaultWorkingDirectory)' - runInParallel: True # Optional - runTestsInIsolation: True # Optional - codeCoverageEnabled: True # Optional - configuration: 'Debug' # Optional - publishRunAttachments: true # Optional - testRunTitle: $(Agent.JobName) - otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal"' - - - job: main_build_win - displayName: Publish Windows - pool: - vmImage: windows-latest - strategy: - matrix: - Release: - BuildConfiguration: Release - maxParallel: 2 - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: true - - - task: CmdLine@2 - displayName: "Clone Web Client (Master, Release, or Tag)" - condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master'), contains(variables['Build.SourceBranch'], 'tag')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' - - - task: CmdLine@2 - displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) - inputs: - script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' - - - task: NodeTool@0 - displayName: 'Install Node' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - versionSpec: '10.x' - - - task: CmdLine@2 - displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: yarn install - workingDirectory: $(Agent.TempDirectory)/jellyfin-web - - - task: CopyFiles@2 - displayName: 'Copy Web Client' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional - contents: '**' - targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional - - - task: CmdLine@2 - displayName: 'Clone UX Repository' - inputs: - script: git clone --depth=1 https://github.com/jellyfin/jellyfin-ux $(Agent.TempDirectory)\jellyfin-ux - - - task: PowerShell@2 - displayName: 'Build NSIS Installer' - inputs: - targetType: 'filePath' # Optional. Options: filePath, inline - filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath - arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) - errorActionPreference: 'stop' # Optional. Options: stop, continue, silentlyContinue - workingDirectory: $(Build.SourcesDirectory) # Optional - - - task: CopyFiles@2 - displayName: 'Copy NSIS Installer' - inputs: - sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional - contents: 'jellyfin*.exe' - targetFolder: $(System.ArtifactsDirectory)/setup - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Setup' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/setup' - artifactName: 'Jellyfin Server Setup' - - - job: dotnet_compat - displayName: Compatibility Check - pool: - vmImage: ubuntu-latest - dependsOn: main_build - # only execute for pull requests - condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) - strategy: - matrix: + - template: azure-pipelines-main.yml + parameters: + LinuxImage: 'ubuntu-latest' + RestoreBuildProjects: $(RestoreBuildProjects) + + - template: azure-pipelines-test.yml + parameters: + ImageNames: + Linux: 'ubuntu-latest' + Windows: 'windows-latest' + macOS: 'macos-latest' + + - template: azure-pipelines-windows.yml + parameters: + WindowsImage: 'windows-latest' + TestProjects: $(TestProjects) + + - template: azure-pipelines-compat.yml + parameters: + Packages: Naming: NugetPackageName: Jellyfin.Naming AssemblyFileName: Emby.Naming.dll @@ -253,74 +47,4 @@ jobs: Common: NugetPackageName: Jellyfin.Common AssemblyFileName: MediaBrowser.Common.dll - maxParallel: 2 - steps: - - checkout: none - - - task: UseDotNet@2 - displayName: 'Update DotNet' - inputs: - packageType: sdk - version: 3.1.100 - - - task: DownloadPipelineArtifact@2 - displayName: 'Download New Assembly Build Artifact' - inputs: - source: 'current' # Options: current, specific - artifact: '$(NugetPackageName)' # Optional - path: '$(System.ArtifactsDirectory)/new-artifacts' - runVersion: 'latest' # Required when source == Specific. Options: latest, latestFromBranch, specific - - - task: CopyFiles@2 - displayName: 'Copy New Assembly Build Artifact' - inputs: - sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional - contents: '**/*.dll' - targetFolder: $(System.ArtifactsDirectory)/new-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: DownloadPipelineArtifact@2 - displayName: 'Download Reference Assembly Build Artifact' - inputs: - source: 'specific' # Options: current, specific - artifact: '$(NugetPackageName)' # Optional - path: '$(System.ArtifactsDirectory)/current-artifacts' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipeline: '$(System.DefinitionId)' # Required when source == Specific - runVersion: 'latestFromBranch' # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: 'refs/heads/$(System.PullRequest.TargetBranch)' # Required when source == Specific && runVersion == LatestFromBranch - - - task: CopyFiles@2 - displayName: 'Copy Reference Assembly Build Artifact' - inputs: - sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional - contents: '**/*.dll' - targetFolder: $(System.ArtifactsDirectory)/current-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: DownloadGitHubRelease@0 - displayName: 'Download ABI Compatibility Check Tool' - inputs: - connection: Jellyfin Release Download - userRepository: EraYaN/dotnet-compatibility - defaultVersionType: 'latest' # Options: latest, specificVersion, specificTag - itemPattern: '**-ci.zip' # Optional - downloadPath: '$(System.ArtifactsDirectory)' - - - task: ExtractFiles@1 - displayName: 'Extract ABI Compatibility Check Tool' - inputs: - archiveFilePatterns: '$(System.ArtifactsDirectory)/*-ci.zip' - destinationFolder: $(System.ArtifactsDirectory)/tools - cleanDestinationFolder: true - - # The `--warnings-only` switch will swallow the return code and not emit any errors. - - task: CmdLine@2 - displayName: 'Execute ABI Compatibility Check Tool' - inputs: - script: 'dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only' - workingDirectory: $(System.ArtifactsDirectory) # Optional + LinuxImage: 'ubuntu-latest' \ No newline at end of file diff --git a/.ci/publish-nightly.yml b/.ci/publish-nightly.yml deleted file mode 100644 index a693e10f6c..0000000000 --- a/.ci/publish-nightly.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Nightly-$(date:yyyyMMdd).$(rev:r) - -variables: - - name: Version - value: '1.0.0' - -trigger: none -pr: none - -jobs: - - job: publish_artifacts_nightly - displayName: Publish Artifacts Nightly - pool: - vmImage: ubuntu-latest - steps: - - checkout: none - - task: DownloadPipelineArtifact@2 - displayName: Download the Windows Setup Artifact - inputs: - source: 'specific' # Options: current, specific - artifact: 'Jellyfin Server Setup' # Optional - path: '$(System.ArtifactsDirectory)/win-installer' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipelineId: 1 # Required when source == Specific - runVersion: 'latestFromBranch' # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: 'refs/heads/master' # Required when source == Specific && runVersion == LatestFromBranch - - - task: SSH@0 - displayName: 'Create Drop directory' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_nightly_azure_upload' - - - task: CopyFilesOverSSH@0 - displayName: 'Copy the Windows Setup to the Repo' - inputs: - sshEndpoint: 'Jellyfin Build Server' - sourceFolder: '$(System.ArtifactsDirectory)/win-installer' - contents: 'jellyfin_*.exe' - targetFolder: '/srv/incoming/jellyfin_nightly_azure_upload/win-installer' - - - task: SSH@0 - displayName: 'Clean up SCP symlink' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'rm -f /srv/incoming/jellyfin_nightly_azure_upload' diff --git a/.ci/publish-release.yml b/.ci/publish-release.yml deleted file mode 100644 index 57e77ae5aa..0000000000 --- a/.ci/publish-release.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: Release-$(Version)-$(date:yyyyMMdd).$(rev:r) - -variables: - - name: Version - value: '1.0.0' - - name: UsedRunId - value: 0 - -trigger: none -pr: none - -jobs: - - job: publish_artifacts_release - displayName: Publish Artifacts Release - pool: - vmImage: ubuntu-latest - steps: - - checkout: none - - task: DownloadPipelineArtifact@2 - displayName: Download the Windows Setup Artifact - inputs: - source: 'specific' # Options: current, specific - artifact: 'Jellyfin Server Setup' # Optional - path: '$(System.ArtifactsDirectory)/win-installer' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipelineId: 1 # Required when source == Specific - runVersion: 'specific' # Required when source == Specific. Options: latest, latestFromBranch, specific - runId: $(UsedRunId) - - - task: SSH@0 - displayName: 'Create Drop directory' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_release_azure_upload' - - - task: CopyFilesOverSSH@0 - displayName: 'Copy the Windows Setup to the Repo' - inputs: - sshEndpoint: 'Jellyfin Build Server' - sourceFolder: '$(System.ArtifactsDirectory)/win-installer' - contents: 'jellyfin_*.exe' - targetFolder: '/srv/incoming/jellyfin_release_azure_upload/win-installer' - - - task: SSH@0 - displayName: 'Clean up SCP symlink' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'rm -f /srv/incoming/jellyfin_release_azure_upload' diff --git a/tests/coverletArgs.runsettings b/tests/coverletArgs.runsettings new file mode 100644 index 0000000000..3113957e0a --- /dev/null +++ b/tests/coverletArgs.runsettings @@ -0,0 +1,17 @@ + + + + + + + cobertura + [coverlet.*.tests?]*,[*]Coverlet.Core*,[*]Moq* + Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute + false + true + false + + + + + \ No newline at end of file From 22f408201a1ba827c7dd92f1d10b6f75656f0b13 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:20:01 +0100 Subject: [PATCH 070/108] Less output and lesser compression. --- deployment/windows/jellyfin.nsi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 5666d30f06..d3b75482cc 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,7 +1,7 @@ ; Shows a lot of debug information while compiling ; This can be removed once stable. -!verbose 4 -SetCompressor lzma +!verbose 2 +SetCompressor bzip2 ShowInstDetails show ShowUninstDetails show ;-------------------------------- From d3bd22d7a27949d1053c8be75d160adadf3c767b Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:36:22 +0100 Subject: [PATCH 071/108] Enable Unicode ANSI targets are deprecated --- deployment/windows/jellyfin.nsi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index d3b75482cc..dbce29e84c 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -4,6 +4,8 @@ SetCompressor bzip2 ShowInstDetails show ShowUninstDetails show +Unicode True + ;-------------------------------- !define SF_USELECTED 0 ; used to check selected options status, rest are inherited from Sections.nsh From 9aa870cf246916abe985aba1da4a63daf4137b92 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:36:54 +0100 Subject: [PATCH 072/108] Enable /SOLID switch for compression --- deployment/windows/jellyfin.nsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index dbce29e84c..5629fcf12e 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,7 +1,7 @@ ; Shows a lot of debug information while compiling ; This can be removed once stable. !verbose 2 -SetCompressor bzip2 +SetCompressor bzip2 /SOLID ShowInstDetails show ShowUninstDetails show Unicode True From 1ad6f016172cb094b0ead5ff3517568d027708e7 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:37:37 +0100 Subject: [PATCH 073/108] Switch to slightly more verbose logging. --- deployment/windows/jellyfin.nsi | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 5629fcf12e..3e8d687e79 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,6 +1,4 @@ -; Shows a lot of debug information while compiling -; This can be removed once stable. -!verbose 2 +!verbose 3 SetCompressor bzip2 /SOLID ShowInstDetails show ShowUninstDetails show From 67cae3730897318233179bd32945125d676e74a8 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:27:38 +0100 Subject: [PATCH 074/108] Formatting and comment removal. --- .ci/azure-pipelines-compat.yml | 44 ++++++++++++++++----------------- .ci/azure-pipelines-main.yml | 10 ++++---- .ci/azure-pipelines-test.yml | 21 +++++++--------- .ci/azure-pipelines-windows.yml | 26 +++++++++---------- .ci/azure-pipelines.yml | 16 ++++++------ 5 files changed, 57 insertions(+), 60 deletions(-) diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml index ac23e0b6db..6af956e1a7 100644 --- a/.ci/azure-pipelines-compat.yml +++ b/.ci/azure-pipelines-compat.yml @@ -21,8 +21,8 @@ jobs: ${{ each Package in parameters.Packages }}: ${{ Package.key }}: NugetPackageName: ${{ Package.value.NugetPackageName }} - AssemblyFileName: ${{ Package.value.AssemblyFileName }} - maxParallel: 2 + AssemblyFileName: ${{ Package.value.AssemblyFileName }} + maxParallel: 2 dependsOn: MainBuild steps: - checkout: none @@ -36,49 +36,49 @@ jobs: - task: DownloadPipelineArtifact@2 displayName: "Download New Assembly Build Artifact" inputs: - source: "current" # Options: current, specific - artifact: "$(NugetPackageName)" # Optional + source: "current" + artifact: "$(NugetPackageName)" path: "$(System.ArtifactsDirectory)/new-artifacts" - runVersion: "latest" # Required when source == Specific. Options: latest, latestFromBranch, specific + runVersion: "latest" - task: CopyFiles@2 displayName: "Copy New Assembly Build Artifact" inputs: - sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional + sourceFolder: $(System.ArtifactsDirectory)/new-artifacts contents: "**/*.dll" targetFolder: $(System.ArtifactsDirectory)/new-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: DownloadPipelineArtifact@2 displayName: "Download Reference Assembly Build Artifact" inputs: - source: "specific" # Options: current, specific - artifact: "$(NugetPackageName)" # Optional + source: "specific" + artifact: "$(NugetPackageName)" path: "$(System.ArtifactsDirectory)/current-artifacts" - project: "$(System.TeamProjectId)" # Required when source == Specific - pipeline: "$(System.DefinitionId)" # Required when source == Specific - runVersion: "latestFromBranch" # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" # Required when source == Specific && runVersion == LatestFromBranch + project: "$(System.TeamProjectId)" + pipeline: "$(System.DefinitionId)" + runVersion: "latestFromBranch" + runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" - task: CopyFiles@2 displayName: "Copy Reference Assembly Build Artifact" inputs: - sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional + sourceFolder: $(System.ArtifactsDirectory)/current-artifacts contents: "**/*.dll" targetFolder: $(System.ArtifactsDirectory)/current-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: DownloadGitHubRelease@0 displayName: "Download ABI Compatibility Check Tool" inputs: connection: Jellyfin Release Download userRepository: EraYaN/dotnet-compatibility - defaultVersionType: "latest" # Options: latest, specificVersion, specificTag - itemPattern: "**-ci.zip" # Optional + defaultVersionType: "latest" + itemPattern: "**-ci.zip" downloadPath: "$(System.ArtifactsDirectory)" - task: ExtractFiles@1 @@ -93,4 +93,4 @@ jobs: displayName: "Execute ABI Compatibility Check Tool" inputs: script: "dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only" - workingDirectory: $(System.ArtifactsDirectory) # Optional \ No newline at end of file + workingDirectory: $(System.ArtifactsDirectory) diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index fd263e20f9..9880bbfaa2 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -50,12 +50,12 @@ jobs: displayName: "Copy Web Client" condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: false - task: UseDotNet@2 displayName: "Update DotNet" @@ -98,4 +98,4 @@ jobs: condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" - artifactName: "Jellyfin.Common" \ No newline at end of file + artifactName: "Jellyfin.Common" diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index eec02ff3be..4455632e15 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -1,7 +1,7 @@ parameters: - name: ImageNames type: object - default: + default: Linux: "ubuntu-latest" Windows: "windows-latest" macOS: "macos-latest" @@ -40,29 +40,26 @@ jobs: inputs: command: "test" projects: ${{ parameters.TestProjects }} - arguments: "--configuration Release --collect:\"XPlat Code Coverage\" --settings tests/coverletArgs.runsettings --verbosity minimal \"-p:GenerateDocumentationFile=False\"" + arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal "-p:GenerateDocumentationFile=False"' publishTestResults: true testRunTitle: $(Agent.JobName) workingDirectory: "$(Build.SourcesDirectory)" - - 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: ReportGenerator (merge) inputs: - reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' - targetdir: '$(Agent.TempDirectory)/merged/' - reporttypes: 'Cobertura' + reports: "$(Agent.TempDirectory)/**/coverage.cobertura.xml" + targetdir: "$(Agent.TempDirectory)/merged/" + reporttypes: "Cobertura" ## V2 is already in the repository but it does not work "wrong number of segments" YAML error. - 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 inputs: - codeCoverageTool: 'cobertura' + codeCoverageTool: "cobertura" #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2 - summaryFileLocation: '$(Agent.TempDirectory)/merged/**.xml' - pathToSources: $(Build.SourcesDirectory) # Optional - #reportDirectory: # Optional - #additionalCodeCoverageFiles: # Optional - failIfCoverageEmpty: true # Optional + summaryFileLocation: "$(Agent.TempDirectory)/merged/**.xml" + pathToSources: $(Build.SourcesDirectory) + failIfCoverageEmpty: true diff --git a/.ci/azure-pipelines-windows.yml b/.ci/azure-pipelines-windows.yml index c6ff3736a4..32d1d1382d 100644 --- a/.ci/azure-pipelines-windows.yml +++ b/.ci/azure-pipelines-windows.yml @@ -43,12 +43,12 @@ jobs: displayName: "Copy Web Client" condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: false - task: CmdLine@2 displayName: "Clone UX Repository" @@ -58,25 +58,25 @@ jobs: - task: PowerShell@2 displayName: "Build NSIS Installer" inputs: - targetType: "filePath" # Optional. Options: filePath, inline - filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath + targetType: "filePath" + filePath: ./deployment/windows/build-jellyfin.ps1 arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) - errorActionPreference: "stop" # Optional. Options: stop, continue, silentlyContinue - workingDirectory: $(Build.SourcesDirectory) # Optional + errorActionPreference: "stop" + workingDirectory: $(Build.SourcesDirectory) - task: CopyFiles@2 displayName: "Copy NSIS Installer" inputs: - sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional + sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ contents: "jellyfin*.exe" targetFolder: $(System.ArtifactsDirectory)/setup - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Setup" condition: succeeded() inputs: targetPath: "$(build.artifactstagingdirectory)/setup" - artifactName: "Jellyfin Server Setup" \ No newline at end of file + artifactName: "Jellyfin Server Setup" diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 221db162ac..f79a85b210 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -17,24 +17,24 @@ 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' + ImageNames: + Linux: "ubuntu-latest" + Windows: "windows-latest" + macOS: "macos-latest" - template: azure-pipelines-windows.yml parameters: - WindowsImage: 'windows-latest' + WindowsImage: "windows-latest" TestProjects: $(TestProjects) - template: azure-pipelines-compat.yml parameters: - Packages: + Packages: Naming: NugetPackageName: Jellyfin.Naming AssemblyFileName: Emby.Naming.dll @@ -47,4 +47,4 @@ jobs: Common: NugetPackageName: Jellyfin.Common AssemblyFileName: MediaBrowser.Common.dll - LinuxImage: 'ubuntu-latest' \ No newline at end of file + LinuxImage: "ubuntu-latest" From 8868ff2ffa7d50d19779e5e8c1f661ece9fd0321 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Wed, 15 Jan 2020 18:40:58 +0800 Subject: [PATCH 075/108] remove useless comment --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index a099087628..3b8cb93fcc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2644,8 +2644,6 @@ namespace MediaBrowser.Controller.MediaEncoding } else { - //h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg - //using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu return "-hwaccel vaapi"; } } From 2c10891b66bf5963d2bfca34b704607a3bc0de85 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Wed, 15 Jan 2020 18:45:28 +0800 Subject: [PATCH 076/108] turn on indentation. --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 993cd3f747..f5decdc0db 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -56,8 +56,8 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc_vaapi", "h264_v4l2m2m", "ac3", - "h264_amf", - "hevc_amf" + "h264_amf", + "hevc_amf" }; // Try and use the individual library versions to determine a FFmpeg version From ec8baaf48d28526e888d2301c5eaf207455c3dfd Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 12:17:42 +0100 Subject: [PATCH 077/108] Switch around SetCompressor arguments. Hide progress bars for powershell. --- deployment/windows/build-jellyfin.ps1 | 2 ++ deployment/windows/jellyfin.nsi | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index dde6eb8fcf..bb2f509192 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -15,6 +15,8 @@ param( [ValidateSet('x64','x86', 'arm', 'arm64')][string]$Architecture = 'x64' ) +$ProgressPreference = 'SilentlyContinue' # Speedup all downloads by hiding progress bars. + #PowershellCore and *nix check to make determine which temp dir to use. if(($PSVersionTable.PSEdition -eq 'Core') -and (-not $IsWindows)){ $TempDir = mktemp -d diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 3e8d687e79..86724b8f49 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,5 +1,5 @@ !verbose 3 -SetCompressor bzip2 /SOLID +SetCompressor /SOLID bzip2 ShowInstDetails show ShowUninstDetails show Unicode True From 2cad58e5cd4c16dfe9e3ad2267d4f5734dc9d7a1 Mon Sep 17 00:00:00 2001 From: artiume Date: Wed, 15 Jan 2020 10:02:01 -0500 Subject: [PATCH 078/108] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 97e3785910..b51500f870 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,7 @@ assignees: '' **Logs** - + **FFmpeg Logs** From d4745957b3dc0b1cc5f5baac299883a89df4cfb6 Mon Sep 17 00:00:00 2001 From: nextlooper42 Date: Tue, 14 Jan 2020 10:29:23 +0000 Subject: [PATCH 079/108] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- .../Localization/Core/sk.json | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 9bac305a27..1988bda526 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -15,7 +15,7 @@ "Favorites": "Obľúbené", "Folders": "Priečinky", "Genres": "Žánre", - "HeaderAlbumArtists": "Albumy umelcov", + "HeaderAlbumArtists": "Umelci albumu", "HeaderCameraUploads": "Nahrané fotografie", "HeaderContinueWatching": "Pokračovať v pozeraní", "HeaderFavoriteAlbums": "Obľúbené albumy", @@ -45,25 +45,25 @@ "NameSeasonNumber": "Séria {0}", "NameSeasonUnknown": "Neznáma séria", "NewVersionIsAvailable": "Nová verzia Jellyfin Serveru je dostupná na stiahnutie.", - "NotificationOptionApplicationUpdateAvailable": "Aktualizácia aplikácie je dostupná", - "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie nainštalovaná", - "NotificationOptionAudioPlayback": "Prehrávanie audia bolo spustené", - "NotificationOptionAudioPlaybackStopped": "Prehrávanie audia bolo zastavené", + "NotificationOptionApplicationUpdateAvailable": "Je dostupná aktualizácia aplikácie", + "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie bola nainštalovaná", + "NotificationOptionAudioPlayback": "Prehrávanie zvuku bolo spustené", + "NotificationOptionAudioPlaybackStopped": "Prehrávanie zvuku bolo zastavené", "NotificationOptionCameraImageUploaded": "Obrázok z fotoaparátu bol nahraný", "NotificationOptionInstallationFailed": "Chyba inštalácie", - "NotificationOptionNewLibraryContent": "Nový obsah bol pridaný", - "NotificationOptionPluginError": "Chyba rozšírenia", - "NotificationOptionPluginInstalled": "Rozšírenie nainštalované", - "NotificationOptionPluginUninstalled": "Rozšírenie odinštalované", - "NotificationOptionPluginUpdateInstalled": "Aktualizácia rozšírenia nainštalovaná", + "NotificationOptionNewLibraryContent": "Bol pridaný nový obsah", + "NotificationOptionPluginError": "Chyba zásuvného modulu", + "NotificationOptionPluginInstalled": "Bol nainštalovaný zásuvný modul", + "NotificationOptionPluginUninstalled": "Zásuvný modul bol odinštalovaný", + "NotificationOptionPluginUpdateInstalled": "Bola nainštalovaná aktualizácia zásuvného modulu", "NotificationOptionServerRestartRequired": "Vyžaduje sa reštart servera", "NotificationOptionTaskFailed": "Naplánovaná úloha zlyhala", "NotificationOptionUserLockedOut": "Používateľ je uzamknutý", "NotificationOptionVideoPlayback": "Spustené prehrávanie videa", "NotificationOptionVideoPlaybackStopped": "Zastavené prehrávanie videa", "Photos": "Fotky", - "Playlists": "Zoznamy skladieb", - "Plugin": "Rozšírenie", + "Playlists": "Playlisty", + "Plugin": "Zásuvný modul", "PluginInstalledWithName": "{0} bol nainštalovaný", "PluginUninstalledWithName": "{0} bol odinštalovaný", "PluginUpdatedWithName": "{0} bol aktualizovaný", @@ -72,8 +72,8 @@ "ScheduledTaskStartedWithName": "{0} zahájených", "ServerNameNeedsToBeRestarted": "{0} vyžaduje reštart", "Shows": "Seriály", - "Songs": "Skladby", - "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Skúste to prosím o chvíľu znova.", + "Songs": "Piesne", + "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Prosím, skúste to o chvíľu znova.", "SubtitleDownloadFailureForItem": "Sťahovanie titulkov pre {0} zlyhalo", "SubtitleDownloadFailureFromForItem": "Sťahovanie titulkov z {0} pre {1} zlyhalo", "SubtitlesDownloadedForItem": "Titulky pre {0} stiahnuté", @@ -87,11 +87,11 @@ "UserLockedOutWithName": "Používateľ {0} bol vymknutý", "UserOfflineFromDevice": "{0} sa odpojil od {1}", "UserOnlineFromDevice": "{0} je online z {1}", - "UserPasswordChangedWithName": "Heslo používateľa {0} zmenené", + "UserPasswordChangedWithName": "Heslo používateľa {0} bolo zmenené", "UserPolicyUpdatedWithName": "Používateľské zásady pre {0} boli aktualizované", - "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1}", - "UserStoppedPlayingItemWithValues": "{0} zastavil prehrávanie {1}", - "ValueHasBeenAddedToLibrary": "{0} bolo pridané do vašej knižnice médií", + "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1} na {2}", + "UserStoppedPlayingItemWithValues": "{0} ukončil prehrávanie {1} na {2}", + "ValueHasBeenAddedToLibrary": "{0} bol pridané do vašej knižnice médií", "ValueSpecialEpisodeName": "Špeciál - {0}", "VersionNumber": "Verzia {0}" } From 42213d94e5126a9966c5a555d4d9cce87451c481 Mon Sep 17 00:00:00 2001 From: 4d1m Date: Wed, 15 Jan 2020 06:58:17 +0000 Subject: [PATCH 080/108] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index b871626f0d..1a4756e3de 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -65,7 +65,7 @@ "LabelIpAddressValue": "Adresa IP: {0}", "ItemRemovedWithName": "{0} a fost eliminat din bibliotecă", "ItemAddedWithName": "{0} a fost adăugat în bibliotecă", - "Inherit": "moștenit", + "Inherit": "Moștenit", "HomeVideos": "Videoclipuri personale", "HeaderRecordingGroups": "Grupuri de înregistrare", "HeaderLiveTV": "TV în Direct", From 15c52867eae01487a3f32a94adad9042f17b9101 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 16:32:04 +0800 Subject: [PATCH 081/108] New upstream ffmpeg version 4.2.1 on windows --- deployment/win-x64/docker-build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/win-x64/docker-build.sh b/deployment/win-x64/docker-build.sh index 3f1ad78b50..77372a66f7 100755 --- a/deployment/win-x64/docker-build.sh +++ b/deployment/win-x64/docker-build.sh @@ -8,7 +8,7 @@ set -o xtrace # Version variables NSSM_VERSION="nssm-2.24-101-g897c7ad" NSSM_URL="http://files.evilt.win/nssm/${NSSM_VERSION}.zip" -FFMPEG_VERSION="ffmpeg-4.0.2-win64-static" +FFMPEG_VERSION="ffmpeg-4.2.1-win64-static" FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win64/static/${FFMPEG_VERSION}.zip" # Move to source directory From ac0b30285e22eff5e9ab36c08fe8cd24a6c3ef4a Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 16:32:07 +0800 Subject: [PATCH 082/108] New upstream ffmpeg version 4.2.1 on windows --- deployment/win-x86/docker-build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/win-x86/docker-build.sh b/deployment/win-x86/docker-build.sh index 7d79ba4958..dd411756a8 100755 --- a/deployment/win-x86/docker-build.sh +++ b/deployment/win-x86/docker-build.sh @@ -8,7 +8,7 @@ set -o xtrace # Version variables NSSM_VERSION="nssm-2.24-101-g897c7ad" NSSM_URL="http://files.evilt.win/nssm/${NSSM_VERSION}.zip" -FFMPEG_VERSION="ffmpeg-4.0.2-win32-static" +FFMPEG_VERSION="ffmpeg-4.2.1-win32-static" FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win32/static/${FFMPEG_VERSION}.zip" # Move to source directory From e92e105c420660f59ad3671852a4a57bb04b7c67 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 17:57:19 +0800 Subject: [PATCH 083/108] New upstream ffmpeg version 4.2.1 on windows --- deployment/windows/build-jellyfin.ps1 | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index dde6eb8fcf..0be832f373 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -44,7 +44,8 @@ function Build-JellyFin { function Install-FFMPEG { param( [string]$ResolvedInstallLocation, - [string]$Architecture + [string]$Architecture, + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared", ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ @@ -55,7 +56,7 @@ function Install-FFMPEG { Invoke-WebRequest -Uri https://repo.jellyfin.org/releases/server/windows/ffmpeg/jellyfin-ffmpeg.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose }else{ Write-Verbose "Downloading 32 bit FFMPEG" - Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win32/shared/ffmpeg-4.0.2-win32-shared.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose + Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win32/shared/$FFMPEGVersionX86.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose } Expand-Archive "$tempdir/ffmpeg.zip" -DestinationPath "$tempdir/ffmpeg/" -Force | Write-Verbose @@ -66,7 +67,7 @@ function Install-FFMPEG { } }else{ Write-Verbose "Copying Binaries to Jellyfin location" - Get-ChildItem "$tempdir/ffmpeg/ffmpeg-4.0.2-win32-shared/bin" | ForEach-Object { + Get-ChildItem "$tempdir/ffmpeg/$FFMPEGVersionX86/bin" | ForEach-Object { Copy-Item $_.FullName -Destination $installLocation | Write-Verbose } } From 0a7ea36c68e8f7b013dd9148d1356c031bd53e1e Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 18:10:14 +0800 Subject: [PATCH 084/108] Update build-jellyfin.ps1 --- deployment/windows/build-jellyfin.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index 0be832f373..9fd86e84d8 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -45,7 +45,7 @@ function Install-FFMPEG { param( [string]$ResolvedInstallLocation, [string]$Architecture, - [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared", + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ From 2ce16d4bb5d98677ac972739983c39b67518038f Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 18:47:54 +0800 Subject: [PATCH 085/108] fix indentation --- deployment/windows/build-jellyfin.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index 9fd86e84d8..7afc385eac 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -44,8 +44,8 @@ function Build-JellyFin { function Install-FFMPEG { param( [string]$ResolvedInstallLocation, - [string]$Architecture, - [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" + [string]$Architecture, + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ From 96c9af590494aa8137d5a061aaf1e68feee60b67 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 13:20:01 +0100 Subject: [PATCH 086/108] Add brackets around thread id --- Jellyfin.Server/Program.cs | 4 ++-- Jellyfin.Server/Resources/Configuration/logging.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 8f44327971..fa9b626744 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -481,11 +481,11 @@ namespace Jellyfin.Server catch (Exception ex) { Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}") + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}") .WriteTo.Async(x => x.File( Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}")) + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}")) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json index 6bc2ed2ee4..e9f71afd49 100644 --- a/Jellyfin.Server/Resources/Configuration/logging.json +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -5,7 +5,7 @@ { "Name": "Console", "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}" } }, { @@ -20,7 +20,7 @@ "retainedFileCountLimit": 3, "rollOnFileSizeLimit": true, "fileSizeLimitBytes": 100000000, - "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}" + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}" } } ] From e882b03e817715bd14223cb2b9495e983ff5ac2f Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 13:30:38 +0100 Subject: [PATCH 087/108] Add back support for DVDs copied as folders --- .../Encoder/MediaEncoder.cs | 77 ++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index e0f7b992ce..deab0715cf 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -849,14 +849,89 @@ namespace MediaBrowser.MediaEncoding.Encoder } } + /// public Task ConvertImage(string inputPath, string outputPath) { throw new NotImplementedException(); } + /// public IEnumerable GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber) { - throw new NotImplementedException(); + // min size 300 mb + const long MinPlayableSize = 314572800; + + var root = isoMount != null ? isoMount.MountedPath : path; + + // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size + // Once we reach a file that is at least the minimum, return all subsequent ones + var allVobs = _fileSystem.GetFiles(root, true) + .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase)) + .OrderBy(i => i.FullName) + .ToList(); + + // If we didn't find any satisfying the min length, just take them all + if (allVobs.Count == 0) + { + _logger.LogWarning("No vobs found in dvd structure."); + return Enumerable.Empty(); + } + + if (titleNumber.HasValue) + { + var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(CultureInfo.InvariantCulture)); + var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); + + if (vobs.Count > 0) + { + var minSizeVobs = vobs + .SkipWhile(f => f.Length < MinPlayableSize) + .ToList(); + + return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName); + } + + _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path); + } + + var files = allVobs + .SkipWhile(f => f.Length < MinPlayableSize) + .ToList(); + + // If we didn't find any satisfying the min length, just take them all + if (files.Count == 0) + { + _logger.LogWarning("Vob size filter resulted in zero matches. Taking all vobs."); + files = allVobs; + } + + // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file + if (files.Count > 0) + { + var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_'); + + if (parts.Length == 3) + { + var title = parts[1]; + + files = files.TakeWhile(f => + { + var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_'); + + return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase); + + }).ToList(); + + // If this resulted in not getting any vobs, just take them all + if (files.Count == 0) + { + _logger.LogWarning("Vob filename filter resulted in zero matches. Taking all vobs."); + files = allVobs; + } + } + } + + return files.Select(i => i.FullName); } public bool CanExtractSubtitles(string codec) From f3a1729964f8ff582aaa9f31eb415114340035ce Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 15:02:50 +0100 Subject: [PATCH 088/108] Address comments --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index deab0715cf..4123f0203a 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -879,7 +879,10 @@ namespace MediaBrowser.MediaEncoding.Encoder if (titleNumber.HasValue) { - var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(CultureInfo.InvariantCulture)); + var prefix = string.Format( + CultureInfo.InvariantCulture, + titleNumber.Value >= 10 ? "VTS_{0}_" : "VTS_0{0}_", + titleNumber.Value); var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); if (vobs.Count > 0) @@ -891,7 +894,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName); } - _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path); + _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", path); } var files = allVobs From dcd6ceb9a2a971ec10fe22c94880d643910a21ab Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Thu, 16 Jan 2020 09:31:20 -0500 Subject: [PATCH 089/108] Update SQLitePCL to new version --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 03cbe00b7a..77333a03d0 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -35,7 +35,7 @@ - + From 73a47e934d1699c5969167c0b614216f108defd3 Mon Sep 17 00:00:00 2001 From: artiume Date: Fri, 17 Jan 2020 00:35:41 -0500 Subject: [PATCH 090/108] Fix Docker Arm Nightly (#2286) * Fix Docker Arm Nightly Updated image base. There was an error for libssl missing. I attempted to add libssl1.0.0 but it wasn't found so I fell back to libssl-dev. Much more work needs to be done. ffmpeg is still debian based. I attempted to add jellyfin-ffmpeg but I was having too many issues so I'm saving it for another day, but it at least builds out successfully. * Fix docker arm64 nightly --- Dockerfile.arm | 3 ++- Dockerfile.arm64 | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 4d8fbb77d1..0e62366288 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -24,10 +24,11 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-arm as qemu -FROM debian:stretch-slim-arm32v7 +FROM debian:stretch-slim COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ + libssl-dev \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /cache /config /media \ && chmod 777 /cache /config /media diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index d41268f13e..796d12f980 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -24,10 +24,11 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu -FROM debian:stretch-slim-arm64v8 +FROM debian:stretch-slim COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ + libssl-dev \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /cache /config /media \ && chmod 777 /cache /config /media From 8e71046a3c7b2e39bbdbfda8518730df21120ef8 Mon Sep 17 00:00:00 2001 From: 4d1m Date: Thu, 16 Jan 2020 08:34:40 +0000 Subject: [PATCH 091/108] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index 1a4756e3de..71bffffc6b 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -66,7 +66,7 @@ "ItemRemovedWithName": "{0} a fost eliminat din bibliotecă", "ItemAddedWithName": "{0} a fost adăugat în bibliotecă", "Inherit": "Moștenit", - "HomeVideos": "Videoclipuri personale", + "HomeVideos": "Filme personale", "HeaderRecordingGroups": "Grupuri de înregistrare", "HeaderLiveTV": "TV în Direct", "HeaderFavoriteSongs": "Melodii Favorite", From 549a2d8b6d51d9ea8c3a319e3ca37da8ea4c088c Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 17 Jan 2020 22:48:28 +0300 Subject: [PATCH 092/108] Enable path mapping in `PlaybackInfo` endpoint --- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 10f10a15ec..15880a9a16 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -275,7 +275,7 @@ namespace MediaBrowser.Api.Playback { // TODO handle supportedLiveMediaTypes? - var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); + var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, true, CancellationToken.None).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(mediaSourceId)) { From 2610f377c0a15788badffd0720175109117af1ed Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 18 Jan 2020 00:09:25 +0100 Subject: [PATCH 093/108] Kestrel doesn't like sync IO operations --- Emby.Dlna/Service/BaseControlHandler.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 067d5fa43f..79f03fed9f 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -63,7 +63,8 @@ namespace Emby.Dlna.Service ValidationType = ValidationType.None, CheckCharacters = false, IgnoreProcessingInstructions = true, - IgnoreComments = true + IgnoreComments = true, + Async = true }; using (var reader = XmlReader.Create(streamReader, readerSettings)) @@ -79,7 +80,8 @@ namespace Emby.Dlna.Service var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, - CloseOutput = false + CloseOutput = false, + Async = true }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); From e700fc8a076769d8f2bc29dac232a2bf8faaa0cf Mon Sep 17 00:00:00 2001 From: dkanada Date: Sun, 19 Jan 2020 00:18:55 +0900 Subject: [PATCH 094/108] fix and remove a few more tests --- Emby.Naming/Subtitles/SubtitleParser.cs | 3 +-- Emby.Naming/TV/EpisodePathParser.cs | 2 +- .../Music/MultiDiscAlbumTests.cs | 21 ++++++++++----- .../Subtitles/SubtitleParserTests.cs | 1 - .../TV/EpisodeNumberTests.cs | 27 +++---------------- ...llyfin.Server.Implementations.Tests.csproj | 2 -- 6 files changed, 21 insertions(+), 35 deletions(-) diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index 99680c6221..b055b1a6c2 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -31,7 +31,6 @@ namespace Emby.Naming.Subtitles } var flags = GetFlags(path); - var info = new SubtitleInfo { Path = path, @@ -45,7 +44,7 @@ namespace Emby.Naming.Subtitles // Should have a name, language and file extension if (parts.Count >= 3) { - info.Language = parts[parts.Count - 2]; + info.Language = parts[^2]; } return info; diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index 4fac543f92..6b557d2e19 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -131,7 +131,7 @@ namespace Emby.Naming.TV var endingNumberGroup = match.Groups["endingepnumber"]; if (endingNumberGroup.Success) { - // Will only set EndingEpsiodeNumber if the captured number is not followed by additional numbers + // Will only set EndingEpisodeNumber if the captured number is not followed by additional numbers // or a 'p' or 'i' as what you would get with a pixel resolution specification. // It avoids erroneous parsing of something like "series-s09e14-1080p.mkv" as a multi-episode from E14 to E108 int nextIndex = endingNumberGroup.Index + endingNumberGroup.Length; diff --git a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs index eb69d915ca..a79e2cf614 100644 --- a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs +++ b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs @@ -10,18 +10,27 @@ namespace Jellyfin.Naming.Tests.Music public void TestMultiDiscAlbums() { Assert.False(IsMultiDiscAlbumFolder(@"blah blah")); - Assert.False(IsMultiDiscAlbumFolder(@"d:/music\weezer/03 Pinkerton")); - Assert.False(IsMultiDiscAlbumFolder(@"d:/music/michael jackson/Bad (2012 Remaster)")); + Assert.False(IsMultiDiscAlbumFolder(@"D:/music/weezer/03 Pinkerton")); + Assert.False(IsMultiDiscAlbumFolder(@"D:/music/michael jackson/Bad (2012 Remaster)")); Assert.True(IsMultiDiscAlbumFolder(@"cd1")); - Assert.True(IsMultiDiscAlbumFolder(@"disc1")); - Assert.True(IsMultiDiscAlbumFolder(@"disk1")); + Assert.True(IsMultiDiscAlbumFolder(@"disc18")); + Assert.True(IsMultiDiscAlbumFolder(@"disk10")); + Assert.True(IsMultiDiscAlbumFolder(@"vol7")); + Assert.True(IsMultiDiscAlbumFolder(@"volume1")); - // Add a space Assert.True(IsMultiDiscAlbumFolder(@"cd 1")); Assert.True(IsMultiDiscAlbumFolder(@"disc 1")); Assert.True(IsMultiDiscAlbumFolder(@"disk 1")); + Assert.False(IsMultiDiscAlbumFolder(@"disk")); + Assert.False(IsMultiDiscAlbumFolder(@"disk ·")); + Assert.False(IsMultiDiscAlbumFolder(@"disk a")); + + Assert.False(IsMultiDiscAlbumFolder(@"disk volume")); + Assert.False(IsMultiDiscAlbumFolder(@"disc disc")); + Assert.False(IsMultiDiscAlbumFolder(@"disk disc 6")); + Assert.True(IsMultiDiscAlbumFolder(@"cd - 1")); Assert.True(IsMultiDiscAlbumFolder(@"disc- 1")); Assert.True(IsMultiDiscAlbumFolder(@"disk - 1")); @@ -38,7 +47,7 @@ namespace Jellyfin.Naming.Tests.Music [Fact] public void TestMultiDiscAlbums1() { - Assert.False(IsMultiDiscAlbumFolder(@"[1985] Oppurtunities (Let's make lots of money) (1985)")); + Assert.False(IsMultiDiscAlbumFolder(@"[1985] Opportunities (Let's make lots of money) (1985)")); } [Fact] diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs index e8f14cdc45..41da889c28 100644 --- a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -22,7 +22,6 @@ namespace Jellyfin.Naming.Tests.Subtitles Test("The Skin I Live In (2011).eng.forced.srt", "eng", false, true); Test("The Skin I Live In (2011).eng.foreign.srt", "eng", false, true); Test("The Skin I Live In (2011).eng.default.foreign.srt", "eng", true, true); - Test("The Skin I Live In (2011).default.foreign.eng.srt", "eng", true, true); } diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 1ae6372817..837b23455c 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -60,21 +60,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(36, GetEpisodeNumberFromFile(@"Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv")); } - [Fact] - public void TestEpisodeNumber50() - { - // This convention is not currently supported, just adding in case we want to look at it in the future - Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season s2016e1.mp4")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber51() - { - // This convention is not currently supported, just adding in case we want to look at it in the future - Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season 2016x1.mp4")); - } - [Fact] public void TestEpisodeNumber52() { @@ -84,29 +69,25 @@ namespace Jellyfin.Naming.Tests.TV [Fact] public void TestEpisodeNumber53() { - // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16.avi")); } [Fact] public void TestEpisodeNumber54() { - // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); } - // [Fact] + [Fact] public void TestEpisodeNumber55() { - // This is not supported. Expected to fail, although it would be a good one to add support for. - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); + Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); } - // [Fact] + [Fact] public void TestEpisodeNumber56() { - // This is not supported. Expected to fail, although it would be a good one to add support for. - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); + Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); } [Fact] diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index bb2afea168..f62d3dcbc5 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -2,9 +2,7 @@ netcoreapp3.1 - false - Jellyfin.Server.Implementations.Tests From a562a4d5053edd2943f22dfb45f7ad5bb0ae8cfa Mon Sep 17 00:00:00 2001 From: dkanada Date: Sun, 19 Jan 2020 00:19:19 +0900 Subject: [PATCH 095/108] minor linting for ci files --- .ci/azure-pipelines-compat.yml | 2 +- .ci/azure-pipelines-main.yml | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml index 6af956e1a7..762bbdcb2e 100644 --- a/.ci/azure-pipelines-compat.yml +++ b/.ci/azure-pipelines-compat.yml @@ -13,7 +13,7 @@ jobs: - job: CompatibilityCheck displayName: Compatibility Check pool: - vmImage: "${{ parameters.LinuxImage}}" + vmImage: "${{ parameters.LinuxImage }}" # only execute for pull requests condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) strategy: diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index 9880bbfaa2..09901b2a6a 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -23,32 +23,32 @@ jobs: - task: CmdLine@2 displayName: "Clone Web Client (Master, Release, or Tag)" - condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" - task: CmdLine@2 displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) inputs: script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" - task: NodeTool@0 displayName: "Install Node" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: versionSpec: "10.x" - task: CmdLine@2 displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: script: yarn install workingDirectory: $(Agent.TempDirectory)/jellyfin-web - task: CopyFiles@2 displayName: "Copy Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" @@ -74,28 +74,28 @@ jobs: - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Naming" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll" artifactName: "Jellyfin.Naming" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Controller" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll" artifactName: "Jellyfin.Controller" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Model" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll" artifactName: "Jellyfin.Model" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Common" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" artifactName: "Jellyfin.Common" From f2eea89ff084111a4a90bfefdb6def68165e6025 Mon Sep 17 00:00:00 2001 From: Carey Metcalfe Date: Sun, 19 Jan 2020 00:51:02 -0500 Subject: [PATCH 096/108] Fix pagination for DLNA root folder list Previously, when responding to a DLNA "Browse" request, the `StartingIndex` was not respected and all of the root items were returned each time. This caused infinite loops with in DLNA clients that ignored the `TotalMatches` data in the response and just continued asking for the next page until they got an empty response. This fix makes the root folder list respect the `StartingIndex` and `RequestedCount` parameters like all other responses. Fixes issue #2303 --- CONTRIBUTORS.md | 1 + Emby.Dlna/ContentDirectory/ControlHandler.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 458944778e..800b3d51ff 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -32,6 +32,7 @@ - [nevado](https://github.com/nevado) - [mark-monteiro](https://github.com/mark-monteiro) - [ullmie02](https://github.com/ullmie02) + - [pR0Ps](https://github.com/pR0Ps) # Emby Contributors diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4f74bb222e..2068e1d2aa 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -771,11 +771,11 @@ namespace Emby.Dlna.ContentDirectory }) .ToArray(); - return new QueryResult + return ApplyPaging(new QueryResult { Items = folders, TotalRecordCount = folders.Length - }; + }, startIndex, limit); } private QueryResult GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit) From 075dad87208fa7fdf2bdaaa54a7be842a038d422 Mon Sep 17 00:00:00 2001 From: Andrew Rabert <6550543+nvllsvm@users.noreply.github.com> Date: Sun, 19 Jan 2020 07:51:38 -0500 Subject: [PATCH 097/108] Fix ARM images (#2302) Allow for native building of Docker images. Use buildx if cross-compilation is needed. --- Dockerfile.arm | 4 ---- Dockerfile.arm64 | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 0e62366288..97e02a17d9 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -1,5 +1,3 @@ -# Requires binfm_misc registration -# https://github.com/multiarch/qemu-user-static#binfmt_misc-register ARG DOTNET_VERSION=3.1 @@ -23,9 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM multiarch/qemu-user-static:x86_64-arm as qemu FROM debian:stretch-slim -COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 796d12f980..445a39add7 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -1,5 +1,3 @@ -# Requires binfm_misc registration -# https://github.com/multiarch/qemu-user-static#binfmt_misc-register ARG DOTNET_VERSION=3.1 @@ -23,9 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu FROM debian:stretch-slim -COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ From da2c998e28e8428cd96951eb58ced81ba59db32f Mon Sep 17 00:00:00 2001 From: Andrew Rabert <6550543+nvllsvm@users.noreply.github.com> Date: Sun, 19 Jan 2020 12:34:33 -0500 Subject: [PATCH 098/108] Update ARM images to debian buster (#2313) Also has the effect of updating ffmpeg to 4.1 --- Dockerfile.arm | 2 +- Dockerfile.arm64 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 97e02a17d9..551aa177a2 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -21,7 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM debian:stretch-slim +FROM debian:buster-slim RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 445a39add7..4c2ca12a66 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -21,7 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM debian:stretch-slim +FROM debian:buster-slim RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ From 11c758b6bea2e15ac14b6b6975a5d2e83f55ae55 Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 21 Jan 2020 00:20:24 +0900 Subject: [PATCH 099/108] remove unsupported test cases --- tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 837b23455c..93c59c9cab 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -78,18 +78,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); } - [Fact] - public void TestEpisodeNumber55() - { - Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); - } - - [Fact] - public void TestEpisodeNumber56() - { - Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); - } - [Fact] public void TestEpisodeNumber57() { From ef487441d1545a21ff4e11d40c37a9ecf200f2e5 Mon Sep 17 00:00:00 2001 From: Waldemar Tomme Date: Tue, 21 Jan 2020 06:48:25 +0100 Subject: [PATCH 100/108] Remove configuration of global_header flag --- .../MediaEncoding/EncodingHelper.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 424dd0dbe8..7022459461 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2750,8 +2750,6 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -mpegts_m2ts_mode 1"; } - var supportsGlobalHeaderFlag = state.OutputContainer != "mkv"; - if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null @@ -2772,11 +2770,6 @@ namespace MediaBrowser.Controller.MediaEncoding if (!state.RunTimeTicks.HasValue) { - if(supportsGlobalHeaderFlag) - { - args += " -flags -global_header"; - } - args += " -fflags +genpts"; } } @@ -2822,11 +2815,6 @@ namespace MediaBrowser.Controller.MediaEncoding { args += " " + qualityParam.Trim(); } - - if (supportsGlobalHeaderFlag && !state.RunTimeTicks.HasValue) - { - args += " -flags -global_header"; - } } if (!string.IsNullOrEmpty(state.OutputVideoSync)) From ac3b958c6791a48217cda5625a68ffeb18fbcae6 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Tue, 21 Jan 2020 17:59:41 +0100 Subject: [PATCH 101/108] Use async methods --- Emby.Dlna/Api/DlnaServerService.cs | 16 ++-- .../ConnectionManager/ConnectionManager.cs | 7 +- .../ContentDirectory/ContentDirectory.cs | 7 +- Emby.Dlna/ContentDirectory/ControlHandler.cs | 4 +- Emby.Dlna/IUpnpService.cs | 4 +- .../MediaReceiverRegistrar.cs | 7 +- Emby.Dlna/Service/BaseControlHandler.cs | 94 ++++++++----------- Emby.Dlna/Service/ControlErrorHandler.cs | 4 +- 8 files changed, 68 insertions(+), 75 deletions(-) diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs index a451bbcf91..a7ff6e9cfd 100644 --- a/Emby.Dlna/Api/DlnaServerService.cs +++ b/Emby.Dlna/Api/DlnaServerService.cs @@ -170,32 +170,32 @@ namespace Emby.Dlna.Api return _resultFactory.GetResult(Request, xml, XMLContentType); } - public object Post(ProcessMediaReceiverRegistrarControlRequest request) + public async Task Post(ProcessMediaReceiverRegistrarControlRequest request) { - var response = PostAsync(request.RequestStream, MediaReceiverRegistrar); + var response = await PostAsync(request.RequestStream, MediaReceiverRegistrar).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - public object Post(ProcessContentDirectoryControlRequest request) + public async Task Post(ProcessContentDirectoryControlRequest request) { - var response = PostAsync(request.RequestStream, ContentDirectory); + var response = await PostAsync(request.RequestStream, ContentDirectory).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - public object Post(ProcessConnectionManagerControlRequest request) + public async Task Post(ProcessConnectionManagerControlRequest request) { - var response = PostAsync(request.RequestStream, ConnectionManager); + var response = await PostAsync(request.RequestStream, ConnectionManager).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - private ControlResponse PostAsync(Stream requestStream, IUpnpService service) + private Task PostAsync(Stream requestStream, IUpnpService service) { var id = GetPathValue(2).ToString(); - return service.ProcessControlRequest(new ControlRequest + return service.ProcessControlRequestAsync(new ControlRequest { Headers = Request.Headers, InputXml = requestStream, diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index 83011fbabd..934b353c28 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -20,17 +21,19 @@ namespace Emby.Dlna.ConnectionManager _logger = logger; } + /// public string GetServiceXml() { return new ConnectionManagerXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile(); - return new ControlHandler(_config, _logger, profile).ProcessControlRequest(request); + return new ControlHandler(_config, _logger, profile).ProcessControlRequestAsync(request); } } } diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index 78d69b3380..a3062b18fd 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -66,12 +67,14 @@ namespace Emby.Dlna.ContentDirectory } } + /// public string GetServiceXml() { return new ContentDirectoryXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile(); @@ -96,7 +99,7 @@ namespace Emby.Dlna.ContentDirectory _userViewManager, _mediaEncoder, _tvSeriesManager) - .ProcessControlRequest(request); + .ProcessControlRequestAsync(request); } private User GetUser(DeviceProfile profile) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4f74bb222e..7ed46984ad 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -76,7 +76,7 @@ namespace Emby.Dlna.ContentDirectory _profile = profile; _config = config; - _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, mediaEncoder); + _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, mediaEncoder); } protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) @@ -1336,7 +1336,7 @@ namespace Emby.Dlna.ContentDirectory }; } - _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); + Logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); return new ServerItem(_libraryManager.GetUserRootFolder()); } diff --git a/Emby.Dlna/IUpnpService.cs b/Emby.Dlna/IUpnpService.cs index ae90e95c79..0f3d327ed2 100644 --- a/Emby.Dlna/IUpnpService.cs +++ b/Emby.Dlna/IUpnpService.cs @@ -1,3 +1,5 @@ +using System.Threading.Tasks; + namespace Emby.Dlna { public interface IUpnpService @@ -13,6 +15,6 @@ namespace Emby.Dlna /// /// The request. /// ControlResponse. - ControlResponse ProcessControlRequest(ControlRequest request); + Task ProcessControlRequestAsync(ControlRequest request); } } diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index b565cb631e..5eab6aee0c 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -15,17 +16,19 @@ namespace Emby.Dlna.MediaReceiverRegistrar _config = config; } + /// public string GetServiceXml() { return new MediaReceiverRegistrarXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { return new ControlHandler( _config, Logger) - .ProcessControlRequest(request); + .ProcessControlRequestAsync(request); } } } diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 79f03fed9f..d56f54149f 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using System.Threading.Tasks; using System.Xml; using Emby.Dlna.Didl; using MediaBrowser.Controller.Configuration; @@ -15,44 +16,34 @@ namespace Emby.Dlna.Service { private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; - protected readonly IServerConfigurationManager Config; - protected readonly ILogger _logger; + protected IServerConfigurationManager Config { get; } + protected ILogger Logger { get; } protected BaseControlHandler(IServerConfigurationManager config, ILogger logger) { Config = config; - _logger = logger; + Logger = logger; } - public ControlResponse ProcessControlRequest(ControlRequest request) + public async Task ProcessControlRequestAsync(ControlRequest request) { try { - var enableDebugLogging = Config.GetDlnaConfiguration().EnableDebugLog; - - if (enableDebugLogging) - { - LogRequest(request); - } - - var response = ProcessControlRequestInternal(request); - - if (enableDebugLogging) - { - LogResponse(response); - } + LogRequest(request); + var response = await ProcessControlRequestInternalAsync(request).ConfigureAwait(false); + LogResponse(response); return response; } catch (Exception ex) { - _logger.LogError(ex, "Error processing control request"); + Logger.LogError(ex, "Error processing control request"); - return new ControlErrorHandler().GetResponse(ex); + return ControlErrorHandler.GetResponse(ex); } } - private ControlResponse ProcessControlRequestInternal(ControlRequest request) + private async Task ProcessControlRequestInternalAsync(ControlRequest request) { ControlRequestInfo requestInfo = null; @@ -69,19 +60,18 @@ namespace Emby.Dlna.Service using (var reader = XmlReader.Create(streamReader, readerSettings)) { - requestInfo = ParseRequest(reader); + requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false); } } - _logger.LogDebug("Received control request {0}", requestInfo.LocalName); + Logger.LogDebug("Received control request {0}", requestInfo.LocalName); var result = GetResult(requestInfo.LocalName, requestInfo.Headers); var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, - CloseOutput = false, - Async = true + CloseOutput = false }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); @@ -116,17 +106,15 @@ namespace Emby.Dlna.Service IsSuccessful = true }; - //logger.LogDebug(xml); - controlResponse.Headers.Add("EXT", string.Empty); return controlResponse; } - private ControlRequestInfo ParseRequest(XmlReader reader) + private async Task ParseRequestAsync(XmlReader reader) { - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -141,37 +129,38 @@ namespace Emby.Dlna.Service { using (var subReader = reader.ReadSubtree()) { - return ParseBodyTag(subReader); + return await ParseBodyTagAsync(subReader).ConfigureAwait(false); } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } + break; } default: { - reader.Skip(); + await reader.SkipAsync().ConfigureAwait(false); break; } } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } return new ControlRequestInfo(); } - private ControlRequestInfo ParseBodyTag(XmlReader reader) + private async Task ParseBodyTagAsync(XmlReader reader) { var result = new ControlRequestInfo(); - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -185,28 +174,28 @@ namespace Emby.Dlna.Service { using (var subReader = reader.ReadSubtree()) { - ParseFirstBodyChild(subReader, result.Headers); + await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false); return result; } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } return result; } - private void ParseFirstBodyChild(XmlReader reader, IDictionary headers) + private async Task ParseFirstBodyChildAsync(XmlReader reader, IDictionary headers) { - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -214,20 +203,20 @@ namespace Emby.Dlna.Service if (reader.NodeType == XmlNodeType.Element) { // TODO: Should we be doing this here, or should it be handled earlier when decoding the request? - headers[reader.LocalName.RemoveDiacritics()] = reader.ReadElementContentAsString(); + headers[reader.LocalName.RemoveDiacritics()] = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } } private class ControlRequestInfo { - public string LocalName; - public string NamespaceURI; - public IDictionary Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + public string LocalName { get; set; } + public string NamespaceURI { get; set; } + public Dictionary Headers { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); } protected abstract IEnumerable> GetResult(string methodName, IDictionary methodParams); @@ -239,10 +228,7 @@ namespace Emby.Dlna.Service return; } - var originalHeaders = request.Headers; - var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - - _logger.LogDebug("Control request. Headers: {0}", headers); + Logger.LogDebug("Control request. Headers: {@Header}", request.Headers); } private void LogResponse(ControlResponse response) @@ -252,11 +238,7 @@ namespace Emby.Dlna.Service return; } - var originalHeaders = response.Headers; - var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - //builder.Append(response.Xml); - - _logger.LogDebug("Control response. Headers: {0}", headers); + Logger.LogDebug("Control response. Headers: {@Headers}\n{Xml}", response.Headers, response.Xml); } } } diff --git a/Emby.Dlna/Service/ControlErrorHandler.cs b/Emby.Dlna/Service/ControlErrorHandler.cs index d5eb4a8879..bbf975f384 100644 --- a/Emby.Dlna/Service/ControlErrorHandler.cs +++ b/Emby.Dlna/Service/ControlErrorHandler.cs @@ -6,11 +6,11 @@ using Emby.Dlna.Didl; namespace Emby.Dlna.Service { - public class ControlErrorHandler + public static class ControlErrorHandler { private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; - public ControlResponse GetResponse(Exception ex) + public static ControlResponse GetResponse(Exception ex) { var settings = new XmlWriterSettings { From 5340eb9363f006e61b4574a30091bfdd43a0772b Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 22 Jan 2020 17:46:26 +0100 Subject: [PATCH 102/108] Update Emby.Dlna/Service/BaseControlHandler.cs Co-Authored-By: dkanada --- Emby.Dlna/Service/BaseControlHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index d56f54149f..49129f6ffd 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -228,7 +228,7 @@ namespace Emby.Dlna.Service return; } - Logger.LogDebug("Control request. Headers: {@Header}", request.Headers); + Logger.LogDebug("Control request. Headers: {@Headers}", request.Headers); } private void LogResponse(ControlResponse response) From 6eac7f0fa7e753731e3d65c0b6c0323eb730ccd8 Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 21 Jan 2020 16:40:09 +0000 Subject: [PATCH 103/108] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 8f91effb92..c1c40c18e1 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -9,7 +9,7 @@ "Channels": "Canali", "ChapterNameValue": "Capitolo {0}", "Collections": "Collezioni", - "DeviceOfflineWithName": "{0} ha disconnesso", + "DeviceOfflineWithName": "{0} si è disconnesso", "DeviceOnlineWithName": "{0} è connesso", "FailedLoginAttemptWithUserName": "Tentativo di accesso fallito da {0}", "Favorites": "Preferiti", From c8409d2ea1b4843bb89377b130733e61e6dc2e41 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 8 Jan 2020 17:52:50 +0100 Subject: [PATCH 104/108] Remove FileSystem.GetStream --- DvdLib/Ifo/Dvd.cs | 4 +- Emby.Dlna/DlnaManager.cs | 2 +- Emby.Drawing/ImageProcessor.cs | 3 +- .../ApplicationHost.cs | 2 +- .../Devices/DeviceManager.cs | 2 +- .../HttpClientManager/HttpClientManager.cs | 4 +- .../HttpServer/FileWriter.cs | 14 +- .../IO/ManagedFileSystem.cs | 81 ---------- .../LiveTv/EmbyTV/DirectRecorder.cs | 8 +- .../LiveTv/EmbyTV/EmbyTV.cs | 8 +- .../LiveTv/EmbyTV/EncodedRecorder.cs | 6 +- .../LiveTv/TunerHosts/LiveStream.cs | 4 +- .../LiveTv/TunerHosts/SharedHttpStream.cs | 4 +- .../Serialization/JsonSerializer.cs | 32 ++-- MediaBrowser.Api/Images/ImageService.cs | 2 +- MediaBrowser.Api/Images/RemoteImageService.cs | 6 +- MediaBrowser.Api/ItemLookupService.cs | 2 +- .../Playback/BaseStreamingService.cs | 2 +- .../Playback/Hls/BaseHlsService.cs | 8 +- .../Playback/Hls/DynamicHlsService.cs | 8 +- .../Playback/Hls/HlsSegmentService.cs | 4 +- .../BaseProgressiveStreamingService.cs | 2 +- .../Progressive/ProgressiveStreamWriter.cs | 12 +- MediaBrowser.Api/System/SystemService.cs | 4 +- .../MediaEncoding/EncodingHelper.cs | 28 ++-- .../Net/IHttpResultFactory.cs | 2 +- .../Net/StaticResultOptions.cs | 4 +- .../Savers/BaseXmlSaver.cs | 2 +- .../BdInfo/BdInfoDirectoryInfo.cs | 38 ++--- .../BdInfo/BdInfoFileInfo.cs | 14 +- .../Subtitles/SubtitleEncoder.cs | 2 +- MediaBrowser.Model/IO/IFileSystem.cs | 138 ------------------ .../IO/{StreamDefaults.cs => IODefaults.cs} | 8 +- MediaBrowser.Providers/Manager/ImageSaver.cs | 4 +- .../Manager/ItemImageProvider.cs | 6 +- .../Manager/MetadataService.cs | 2 +- .../Manager/ProviderManager.cs | 2 +- .../Music/AudioDbAlbumProvider.cs | 6 +- .../Music/AudioDbArtistProvider.cs | 5 +- MediaBrowser.Providers/Omdb/OmdbProvider.cs | 4 +- .../Studios/StudiosImageProvider.cs | 6 +- .../Subtitles/SubtitleManager.cs | 4 +- .../Tmdb/People/TmdbPersonProvider.cs | 2 +- .../Api/DashboardService.cs | 2 +- 44 files changed, 128 insertions(+), 375 deletions(-) rename MediaBrowser.Model/IO/{StreamDefaults.cs => IODefaults.cs} (58%) diff --git a/DvdLib/Ifo/Dvd.cs b/DvdLib/Ifo/Dvd.cs index 90125fa3e3..157b2e197f 100644 --- a/DvdLib/Ifo/Dvd.cs +++ b/DvdLib/Ifo/Dvd.cs @@ -42,7 +42,7 @@ namespace DvdLib.Ifo } else { - using (var vmgFs = _fileSystem.GetFileStream(vmgPath.FullName, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) + using (var vmgFs = new FileStream(vmgPath.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var vmgRead = new BigEndianBinaryReader(vmgFs)) { @@ -95,7 +95,7 @@ namespace DvdLib.Ifo { VTSPaths[vtsNum] = vtsPath; - using (var vtsFs = _fileSystem.GetFileStream(vtsPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) + using (var vtsFs = new FileStream(vtsPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var vtsRead = new BigEndianBinaryReader(vtsFs)) { diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index d5d788021d..7e744e0aac 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -385,7 +385,7 @@ namespace Emby.Dlna { Directory.CreateDirectory(systemProfilesPath); - using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { await stream.CopyToAsync(fileStream); } diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index ce8089e59c..4e0f9493a6 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -14,7 +14,6 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; @@ -129,7 +128,7 @@ namespace Emby.Drawing { var file = await ProcessImage(options).ConfigureAwait(false); - using (var fileStream = _fileSystem.GetFileStream(file.Item1, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true)) + using (var fileStream = new FileStream(file.Item1, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { await fileStream.CopyToAsync(toStream).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0bb1d832fb..226a8f3026 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -599,7 +599,7 @@ namespace Emby.Server.Implementations HttpsPort = ServerConfiguration.DefaultHttpsPort; } - JsonSerializer = new JsonSerializer(FileSystemManager); + JsonSerializer = new JsonSerializer(); if (Plugins != null) { diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index ef73170506..2bd0b840a5 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -243,7 +243,7 @@ namespace Emby.Server.Implementations.Devices try { - using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { await stream.CopyToAsync(fs).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 50233ea485..8a2bc83fb0 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -197,7 +197,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (File.Exists(responseCachePath) && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow) { - var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true); + var stream = new FileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true); return new HttpResponseInfo { @@ -220,7 +220,7 @@ namespace Emby.Server.Implementations.HttpClientManager FileMode.Create, FileAccess.Write, FileShare.None, - StreamDefaults.DefaultFileStreamBufferSize, + IODefaults.FileStreamBufferSize, true)) { await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs index 1795651fd7..d36f230d64 100644 --- a/Emby.Server.Implementations/HttpServer/FileWriter.cs +++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs @@ -72,7 +72,7 @@ namespace Emby.Server.Implementations.HttpServer SetRangeValues(); } - FileShare = FileShareMode.Read; + FileShare = FileShare.Read; Cookies = new List(); } @@ -94,7 +94,7 @@ namespace Emby.Server.Implementations.HttpServer public List Cookies { get; private set; } - public FileShareMode FileShare { get; set; } + public FileShare FileShare { get; set; } /// /// Gets the options. @@ -222,17 +222,17 @@ namespace Emby.Server.Implementations.HttpServer } } - public async Task TransmitFile(Stream stream, string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken) + public async Task TransmitFile(Stream stream, string path, long offset, long count, FileShare fileShare, CancellationToken cancellationToken) { - var fileOpenOptions = FileOpenOptions.SequentialScan; + var fileOptions = FileOptions.SequentialScan; // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - fileOpenOptions |= FileOpenOptions.Asynchronous; + fileOptions |= FileOptions.Asynchronous; } - using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions)) + using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, fileShare, IODefaults.FileStreamBufferSize, fileOptions)) { if (offset > 0) { @@ -245,7 +245,7 @@ namespace Emby.Server.Implementations.HttpServer } else { - await fs.CopyToAsync(stream, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false); + await fs.CopyToAsync(stream, IODefaults.CopyToBufferSize, cancellationToken).ConfigureAwait(false); } } } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 68417876cf..da5a4d50ed 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -365,87 +365,6 @@ namespace Emby.Server.Implementations.IO return GetLastWriteTimeUtc(GetFileSystemInfo(path)); } - /// - /// Gets the file stream. - /// - /// The path. - /// The mode. - /// The access. - /// The share. - /// if set to true [is asynchronous]. - /// FileStream. - public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false) - { - if (isAsync) - { - return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous); - } - - return GetFileStream(path, mode, access, share, FileOpenOptions.None); - } - - public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) - => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions)); - - private static FileOptions GetFileOptions(FileOpenOptions mode) - { - var val = (int)mode; - return (FileOptions)val; - } - - private static FileMode GetFileMode(FileOpenMode mode) - { - switch (mode) - { - //case FileOpenMode.Append: - // return FileMode.Append; - case FileOpenMode.Create: - return FileMode.Create; - case FileOpenMode.CreateNew: - return FileMode.CreateNew; - case FileOpenMode.Open: - return FileMode.Open; - case FileOpenMode.OpenOrCreate: - return FileMode.OpenOrCreate; - //case FileOpenMode.Truncate: - // return FileMode.Truncate; - default: - throw new Exception("Unrecognized FileOpenMode"); - } - } - - private static FileAccess GetFileAccess(FileAccessMode mode) - { - switch (mode) - { - //case FileAccessMode.ReadWrite: - // return FileAccess.ReadWrite; - case FileAccessMode.Write: - return FileAccess.Write; - case FileAccessMode.Read: - return FileAccess.Read; - default: - throw new Exception("Unrecognized FileAccessMode"); - } - } - - private static FileShare GetFileShare(FileShareMode mode) - { - switch (mode) - { - case FileShareMode.ReadWrite: - return FileShare.ReadWrite; - case FileShareMode.Write: - return FileShare.Write; - case FileShareMode.Read: - return FileShare.Read; - case FileShareMode.None: - return FileShare.None; - default: - throw new Exception("Unrecognized FileShareMode"); - } - } - public virtual void SetHidden(string path, bool isHidden) { if (OperatingSystem.Id != OperatingSystemId.Windows) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 84e8c31f95..161cf60516 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -15,14 +15,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { private readonly ILogger _logger; private readonly IHttpClient _httpClient; - private readonly IFileSystem _fileSystem; private readonly IStreamHelper _streamHelper; - public DirectRecorder(ILogger logger, IHttpClient httpClient, IFileSystem fileSystem, IStreamHelper streamHelper) + public DirectRecorder(ILogger logger, IHttpClient httpClient, IStreamHelper streamHelper) { _logger = logger; _httpClient = httpClient; - _fileSystem = fileSystem; _streamHelper = streamHelper; } @@ -45,7 +43,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { onStarted(); @@ -81,7 +79,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { onStarted(); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index f4d6cd4d3a..2fe699aabc 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1664,10 +1664,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http)) { - return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _processFactory, _config); + return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _processFactory, _config); } - return new DirectRecorder(_logger, _httpClient, _fileSystem, _streamHelper); + return new DirectRecorder(_logger, _httpClient, _streamHelper); } private void OnSuccessfulRecording(TimerInfo timer, string path) @@ -1888,7 +1888,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return; } - using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { var settings = new XmlWriterSettings { @@ -1952,7 +1952,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return; } - using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { var settings = new XmlWriterSettings { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index cc9c8e5d29..ee5086a65f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -14,7 +14,6 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; @@ -24,7 +23,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public class EncodedRecorder : IRecorder { private readonly ILogger _logger; - private readonly IFileSystem _fileSystem; private readonly IMediaEncoder _mediaEncoder; private readonly IServerApplicationPaths _appPaths; private bool _hasExited; @@ -38,7 +36,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public EncodedRecorder( ILogger logger, - IFileSystem fileSystem, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, IJsonSerializer json, @@ -46,7 +43,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV IServerConfigurationManager config) { _logger = logger; - _fileSystem = fileSystem; _mediaEncoder = mediaEncoder; _appPaths = appPaths; _json = json; @@ -107,7 +103,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - _logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true); + _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 1d55e7992e..862b9fdfed 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts FileMode.Open, FileAccess.Read, FileShare.ReadWrite, - StreamDefaults.DefaultFileStreamBufferSize, + IODefaults.FileStreamBufferSize, allowAsyncFileRead ? FileOptions.SequentialScan | FileOptions.Asynchronous : FileOptions.SequentialScan); public Task DeleteTempFiles() @@ -199,7 +199,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts await StreamHelper.CopyToAsync( inputStream, stream, - StreamDefaults.DefaultCopyToBufferSize, + IODefaults.CopyToBufferSize, emptyReadLimit, cancellationToken).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 0d94f4b329..99244eb625 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -127,12 +127,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using (response) using (var stream = response.Content) - using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) + using (var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { await StreamHelper.CopyToAsync( stream, fileStream, - StreamDefaults.DefaultCopyToBufferSize, + IODefaults.CopyToBufferSize, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs index 36196ee36c..bcc814daf2 100644 --- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs +++ b/Emby.Server.Implementations/Serialization/JsonSerializer.cs @@ -2,7 +2,6 @@ using System; using System.Globalization; using System.IO; using System.Threading.Tasks; -using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.Serialization @@ -12,13 +11,15 @@ namespace Emby.Server.Implementations.Serialization /// public class JsonSerializer : IJsonSerializer { - private readonly IFileSystem _fileSystem; - - public JsonSerializer( - IFileSystem fileSystem) + public JsonSerializer() { - _fileSystem = fileSystem; - Configure(); + ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601; + ServiceStack.Text.JsConfig.ExcludeTypeInfo = true; + ServiceStack.Text.JsConfig.IncludeNullValues = false; + ServiceStack.Text.JsConfig.AlwaysUseUtc = true; + ServiceStack.Text.JsConfig.AssumeUtc = true; + + ServiceStack.Text.JsConfig.SerializeFn = SerializeGuid; } /// @@ -81,7 +82,7 @@ namespace Emby.Server.Implementations.Serialization throw new ArgumentNullException(nameof(file)); } - using (var stream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) { SerializeToStream(obj, stream); } @@ -162,7 +163,6 @@ namespace Emby.Server.Implementations.Serialization throw new ArgumentNullException(nameof(stream)); } - return ServiceStack.Text.JsonSerializer.DeserializeFromStreamAsync(stream); } @@ -225,20 +225,6 @@ namespace Emby.Server.Implementations.Serialization } } - /// - /// Configures this instance. - /// - private void Configure() - { - ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601; - ServiceStack.Text.JsConfig.ExcludeTypeInfo = true; - ServiceStack.Text.JsConfig.IncludeNullValues = false; - ServiceStack.Text.JsConfig.AlwaysUseUtc = true; - ServiceStack.Text.JsConfig.AssumeUtc = true; - - ServiceStack.Text.JsConfig.SerializeFn = SerializeGuid; - } - private static string SerializeGuid(Guid guid) { if (guid.Equals(Guid.Empty)) diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index e94c1321f4..c55618aa1d 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -656,7 +656,7 @@ namespace MediaBrowser.Api.Images IsHeadRequest = isHeadRequest, Path = imageResult.Item1, - FileShare = FileShareMode.Read + FileShare = FileShare.Read }).ConfigureAwait(false); } diff --git a/MediaBrowser.Api/Images/RemoteImageService.cs b/MediaBrowser.Api/Images/RemoteImageService.cs index 5a37d37302..f03f5efd8d 100644 --- a/MediaBrowser.Api/Images/RemoteImageService.cs +++ b/MediaBrowser.Api/Images/RemoteImageService.cs @@ -274,11 +274,9 @@ namespace MediaBrowser.Api.Images Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) + using (var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { - using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) - { - await stream.CopyToAsync(filestream).ConfigureAwait(false); - } + await stream.CopyToAsync(filestream).ConfigureAwait(false); } Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index ea5a99892d..a76369a157 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -305,7 +305,7 @@ namespace MediaBrowser.Api Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) - using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { await stream.CopyToAsync(filestream).ConfigureAwait(false); } diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 1f7dc0d71f..ab74bab1c3 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -261,7 +261,7 @@ namespace MediaBrowser.Api.Playback var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt"); // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - Stream logStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true); + Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false); diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 5d0dc98ddc..0cbfe4bdfa 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -168,7 +168,7 @@ namespace MediaBrowser.Api.Playback.Hls private string GetLivePlaylistText(string path, int segmentLength) { - using (var stream = FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite)) + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var reader = new StreamReader(stream)) { @@ -211,7 +211,7 @@ namespace MediaBrowser.Api.Playback.Hls { try { - // Need to use FileShareMode.ReadWrite because we're reading the file at the same time it's being written + // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written using (var fileStream = GetPlaylistFileStream(playlist)) { using (var reader = new StreamReader(fileStream)) @@ -252,11 +252,11 @@ namespace MediaBrowser.Api.Playback.Hls try { - return FileSystem.GetFileStream(tmpPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, FileOpenOptions.SequentialScan); + return new FileStream(tmpPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.SequentialScan); } catch (IOException) { - return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, FileOpenOptions.SequentialScan); + return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.SequentialScan); } } diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 0178f53af6..e85ed20505 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -537,7 +537,7 @@ namespace MediaBrowser.Api.Playback.Hls return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions { Path = segmentPath, - FileShare = FileShareMode.ReadWrite, + FileShare = FileShare.ReadWrite, OnComplete = () => { Logger.LogDebug("finished serving {0}", segmentPath); @@ -954,12 +954,12 @@ namespace MediaBrowser.Api.Playback.Hls // Unable to force key frames to h264_qsv transcode if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) { - Logger.LogInformation("Bug Workaround: Disabling force_key_frames for h264_qsv"); - } + Logger.LogInformation("Bug Workaround: Disabling force_key_frames for h264_qsv"); + } else { args += " " + keyFrameArg; - } + } //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0"; diff --git a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs index bb12ab1f0d..87ccde2e04 100644 --- a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs +++ b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs @@ -140,7 +140,7 @@ namespace MediaBrowser.Api.Playback.Hls var file = request.SegmentId + Path.GetExtension(Request.PathInfo); file = Path.Combine(ServerConfigurationManager.GetTranscodePath(), file); - return ResultFactory.GetStaticFileResult(Request, file, FileShareMode.ReadWrite); + return ResultFactory.GetStaticFileResult(Request, file, FileShare.ReadWrite); } private Task GetFileResult(string path, string playlistPath) @@ -150,7 +150,7 @@ namespace MediaBrowser.Api.Playback.Hls return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions { Path = path, - FileShare = FileShareMode.ReadWrite, + FileShare = FileShare.ReadWrite, OnComplete = () => { if (transcodingJob != null) diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index ed30dbba61..ed68219c9f 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -248,7 +248,7 @@ namespace MediaBrowser.Api.Playback.Progressive // ContentType = contentType, // IsHeadRequest = isHeadRequest, // Path = outputPath, - // FileShare = FileShareMode.ReadWrite, + // FileShare = FileShare.ReadWrite, // OnComplete = () => // { // if (transcodingJob != null) diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs index 6609120655..a53b848f9e 100644 --- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs +++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs @@ -21,8 +21,6 @@ namespace MediaBrowser.Api.Playback.Progressive private readonly CancellationToken _cancellationToken; private readonly Dictionary _outputHeaders; - const int StreamCopyToBufferSize = 81920; - private long _bytesWritten = 0; public long StartPosition { get; set; } public bool AllowEndOfFile = true; @@ -52,14 +50,14 @@ namespace MediaBrowser.Api.Playback.Progressive private Stream GetInputStream(bool allowAsyncFileRead) { - var fileOpenOptions = FileOpenOptions.SequentialScan; + var fileOptions = FileOptions.SequentialScan; if (allowAsyncFileRead) { - fileOpenOptions |= FileOpenOptions.Asynchronous; + fileOptions |= FileOptions.Asynchronous; } - return _fileSystem.GetFileStream(_path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions); + return new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions); } public async Task WriteToAsync(Stream outputStream, CancellationToken cancellationToken) @@ -127,7 +125,7 @@ namespace MediaBrowser.Api.Playback.Progressive private async Task CopyToInternalAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken) { - var array = new byte[StreamCopyToBufferSize]; + var array = new byte[IODefaults.CopyToBufferSize]; int bytesRead; int totalBytesRead = 0; @@ -154,7 +152,7 @@ namespace MediaBrowser.Api.Playback.Progressive private async Task CopyToInternalAsync(Stream source, Stream destination, CancellationToken cancellationToken) { - var array = new byte[StreamCopyToBufferSize]; + var array = new byte[IODefaults.CopyToBufferSize]; int bytesRead; int totalBytesRead = 0; diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index 3a56ba701e..3a3eeb8b8f 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -170,10 +170,10 @@ namespace MediaBrowser.Api.System // For older files, assume fully static if (file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1)) { - return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShareMode.Read); + return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShare.Read); } - return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShareMode.ReadWrite); + return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShare.ReadWrite); } /// diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index acc89e352b..342c764146 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -475,7 +475,7 @@ namespace MediaBrowser.Controller.MediaEncoding .Append(' '); } - if (state.IsVideoRequest + if (state.IsVideoRequest && string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)) { var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions); @@ -486,11 +486,11 @@ namespace MediaBrowser.Controller.MediaEncoding if (!string.IsNullOrEmpty(videoDecoder) && videoDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase)) { arg.Append("-hwaccel qsv "); - } - else + } + else { arg.Append("-init_hw_device qsv=hw -filter_hw_device hw "); - } + } } arg.Append(videoDecoder + " "); @@ -653,7 +653,7 @@ namespace MediaBrowser.Controller.MediaEncoding // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath)); // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf")) // { - // using (var fileStream = _fileSystem.GetFileStream(fallbackFontPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read)) // { // stream.CopyTo(fileStream); // } @@ -1624,22 +1624,22 @@ namespace MediaBrowser.Controller.MediaEncoding // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference) var retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay{3}\""; - if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) { /* QSV in FFMpeg can now setup hardware overlay for transcodes. For software decoding and hardware encoding option, frames must be hwuploaded into hardware - with fixed frame size. + with fixed frame size. */ if (!string.IsNullOrEmpty(videoDecoder) && videoDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase)) { retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv=x=(W-w)/2:y=(H-h)/2{3}\""; - } - else + } + else { retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwupload=extra_hw_frames=64[v];[v][sub]overlay_qsv=x=(W-w)/2:y=(H-h)/2{3}\""; } - } + } return string.Format( CultureInfo.InvariantCulture, @@ -1731,8 +1731,8 @@ namespace MediaBrowser.Controller.MediaEncoding vaapi_or_qsv, outputWidth, outputHeight)); - } - else + } + else { filters.Add(string.Format(CultureInfo.InvariantCulture, "scale_{0}=format=nv12", vaapi_or_qsv)); } @@ -1979,8 +1979,8 @@ namespace MediaBrowser.Controller.MediaEncoding var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options); - // If we are software decoding, and hardware encoding - if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + // If we are software decoding, and hardware encoding + if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) && (string.IsNullOrEmpty(videoDecoder) || !videoDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase))) { filters.Add("format=nv12|qsv"); diff --git a/MediaBrowser.Controller/Net/IHttpResultFactory.cs b/MediaBrowser.Controller/Net/IHttpResultFactory.cs index ff9ecf8af0..fb00ee0081 100644 --- a/MediaBrowser.Controller/Net/IHttpResultFactory.cs +++ b/MediaBrowser.Controller/Net/IHttpResultFactory.cs @@ -66,7 +66,7 @@ namespace MediaBrowser.Controller.Net /// The path. /// The file share. /// System.Object. - Task GetStaticFileResult(IRequest requestContext, string path, FileShareMode fileShare = FileShareMode.Read); + Task GetStaticFileResult(IRequest requestContext, string path, FileShare fileShare = FileShare.Read); /// /// Gets the static file result. diff --git a/MediaBrowser.Controller/Net/StaticResultOptions.cs b/MediaBrowser.Controller/Net/StaticResultOptions.cs index 7a179913ac..7267326607 100644 --- a/MediaBrowser.Controller/Net/StaticResultOptions.cs +++ b/MediaBrowser.Controller/Net/StaticResultOptions.cs @@ -24,12 +24,12 @@ namespace MediaBrowser.Controller.Net public string Path { get; set; } public long? ContentLength { get; set; } - public FileShareMode FileShare { get; set; } + public FileShare FileShare { get; set; } public StaticResultOptions() { ResponseHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - FileShare = FileShareMode.Read; + FileShare = FileShare.Read; } } diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index bd727bcdf9..46c5317974 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.LocalMetadata.Savers // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); - using (var filestream = FileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.CopyTo(filestream); } diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs index 91c8b27925..e040286ab9 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs @@ -1,16 +1,27 @@ using System; -using System.Collections.Generic; using System.Linq; using BDInfo.IO; using MediaBrowser.Model.IO; namespace MediaBrowser.MediaEncoding.BdInfo { - class BdInfoDirectoryInfo : BDInfo.IO.IDirectoryInfo + class BdInfoDirectoryInfo : IDirectoryInfo { - IFileSystem _fileSystem = null; + private readonly IFileSystem _fileSystem = null; - FileSystemMetadata _impl = null; + private readonly FileSystemMetadata _impl = null; + + public BdInfoDirectoryInfo(IFileSystem fileSystem, string path) + { + _fileSystem = fileSystem; + _impl = _fileSystem.GetDirectoryInfo(path); + } + + private BdInfoDirectoryInfo(IFileSystem fileSystem, FileSystemMetadata impl) + { + _fileSystem = fileSystem; + _impl = impl; + } public string Name => _impl.Name; @@ -25,22 +36,11 @@ namespace MediaBrowser.MediaEncoding.BdInfo { return new BdInfoDirectoryInfo(_fileSystem, parentFolder); } + return null; } } - public BdInfoDirectoryInfo(IFileSystem fileSystem, string path) - { - _fileSystem = fileSystem; - _impl = _fileSystem.GetDirectoryInfo(path); - } - - private BdInfoDirectoryInfo(IFileSystem fileSystem, FileSystemMetadata impl) - { - _fileSystem = fileSystem; - _impl = impl; - } - public IDirectoryInfo[] GetDirectories() { return Array.ConvertAll(_fileSystem.GetDirectories(_impl.FullName).ToArray(), @@ -50,20 +50,20 @@ namespace MediaBrowser.MediaEncoding.BdInfo public IFileInfo[] GetFiles() { return Array.ConvertAll(_fileSystem.GetFiles(_impl.FullName).ToArray(), - x => new BdInfoFileInfo(_fileSystem, x)); + x => new BdInfoFileInfo(x)); } public IFileInfo[] GetFiles(string searchPattern) { return Array.ConvertAll(_fileSystem.GetFiles(_impl.FullName, new[] { searchPattern }, false, false).ToArray(), - x => new BdInfoFileInfo(_fileSystem, x)); + x => new BdInfoFileInfo(x)); } public IFileInfo[] GetFiles(string searchPattern, System.IO.SearchOption searchOption) { return Array.ConvertAll(_fileSystem.GetFiles(_impl.FullName, new[] { searchPattern }, false, searchOption.HasFlag(System.IO.SearchOption.AllDirectories)).ToArray(), - x => new BdInfoFileInfo(_fileSystem, x)); + x => new BdInfoFileInfo(x)); } public static IDirectoryInfo FromFileSystemPath(Model.IO.IFileSystem fs, string path) diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs index de9d7cb784..a6ff4f7678 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs @@ -1,11 +1,10 @@ +using System.IO; using MediaBrowser.Model.IO; namespace MediaBrowser.MediaEncoding.BdInfo { class BdInfoFileInfo : BDInfo.IO.IFileInfo { - IFileSystem _fileSystem = null; - FileSystemMetadata _impl = null; public string Name => _impl.Name; @@ -18,18 +17,17 @@ namespace MediaBrowser.MediaEncoding.BdInfo public bool IsDir => _impl.IsDirectory; - public BdInfoFileInfo(IFileSystem fileSystem, FileSystemMetadata impl) + public BdInfoFileInfo(FileSystemMetadata impl) { - _fileSystem = fileSystem; _impl = impl; } public System.IO.Stream OpenRead() { - return _fileSystem.GetFileStream(FullName, - FileOpenMode.Open, - FileAccessMode.Read, - FileShareMode.Read); + return new FileStream(FullName, + FileMode.Open, + FileAccess.Read, + FileShare.Read); } public System.IO.StreamReader OpenText() diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 99bb368b26..a4a7595d29 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -691,7 +691,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!string.Equals(text, newText)) { - using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) using (var writer = new StreamWriter(fileStream, encoding)) { writer.Write(newText); diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index ca99b28ca4..48e5eea6f6 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -98,20 +98,6 @@ namespace MediaBrowser.Model.IO /// DateTime. DateTime GetLastWriteTimeUtc(string path); - /// - /// Gets the file stream. - /// - /// The path. - /// The mode. - /// The access. - /// The share. - /// if set to true [is asynchronous]. - /// FileStream. - Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false); - - Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, - FileOpenOptions fileOpenOptions); - /// /// Swaps the files. /// @@ -218,128 +204,4 @@ namespace MediaBrowser.Model.IO List GetDrives(); void SetExecutable(string path); } - - //TODO Investigate if can be replaced by the one from System.IO ? - public enum FileOpenMode - { - // - // Summary: - // Specifies that the operating system should create a new file. This requires System.Security.Permissions.FileIOPermissionAccess.Write - // permission. If the file already exists, an System.IO.IOException exception is - // thrown. - CreateNew = 1, - // - // Summary: - // Specifies that the operating system should create a new file. If the file already - // exists, it will be overwritten. This requires System.Security.Permissions.FileIOPermissionAccess.Write - // permission. FileMode.Create is equivalent to requesting that if the file does - // not exist, use System.IO.FileMode.CreateNew; otherwise, use System.IO.FileMode.Truncate. - // If the file already exists but is a hidden file, an System.UnauthorizedAccessException - // exception is thrown. - Create = 2, - // - // Summary: - // Specifies that the operating system should open an existing file. The ability - // to open the file is dependent on the value specified by the System.IO.FileAccess - // enumeration. A System.IO.FileNotFoundException exception is thrown if the file - // does not exist. - Open = 3, - // - // Summary: - // Specifies that the operating system should open a file if it exists; otherwise, - // a new file should be created. If the file is opened with FileAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Read - // permission is required. If the file access is FileAccess.Write, System.Security.Permissions.FileIOPermissionAccess.Write - // permission is required. If the file is opened with FileAccess.ReadWrite, both - // System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write - // permissions are required. - OpenOrCreate = 4 - } - - public enum FileAccessMode - { - // - // Summary: - // Read access to the file. Data can be read from the file. Combine with Write for - // read/write access. - Read = 1, - // - // Summary: - // Write access to the file. Data can be written to the file. Combine with Read - // for read/write access. - Write = 2 - } - - public enum FileShareMode - { - // - // Summary: - // Declines sharing of the current file. Any request to open the file (by this process - // or another process) will fail until the file is closed. - None = 0, - // - // Summary: - // Allows subsequent opening of the file for reading. If this flag is not specified, - // any request to open the file for reading (by this process or another process) - // will fail until the file is closed. However, even if this flag is specified, - // additional permissions might still be needed to access the file. - Read = 1, - // - // Summary: - // Allows subsequent opening of the file for writing. If this flag is not specified, - // any request to open the file for writing (by this process or another process) - // will fail until the file is closed. However, even if this flag is specified, - // additional permissions might still be needed to access the file. - Write = 2, - // - // Summary: - // Allows subsequent opening of the file for reading or writing. If this flag is - // not specified, any request to open the file for reading or writing (by this process - // or another process) will fail until the file is closed. However, even if this - // flag is specified, additional permissions might still be needed to access the - // file. - ReadWrite = 3 - } - - // - // Summary: - // Represents advanced options for creating a System.IO.FileStream object. - [Flags] - public enum FileOpenOptions - { - // - // Summary: - // Indicates that the system should write through any intermediate cache and go - // directly to disk. - WriteThrough = int.MinValue, - // - // Summary: - // Indicates that no additional options should be used when creating a System.IO.FileStream - // object. - None = 0, - // - // Summary: - // Indicates that a file is encrypted and can be decrypted only by using the same - // user account used for encryption. - Encrypted = 16384, - // - // Summary: - // Indicates that a file is automatically deleted when it is no longer in use. - DeleteOnClose = 67108864, - // - // Summary: - // Indicates that the file is to be accessed sequentially from beginning to end. - // The system can use this as a hint to optimize file caching. If an application - // moves the file pointer for random access, optimum caching may not occur; however, - // correct operation is still guaranteed. - SequentialScan = 134217728, - // - // Summary: - // Indicates that the file is accessed randomly. The system can use this as a hint - // to optimize file caching. - RandomAccess = 268435456, - // - // Summary: - // Indicates that a file can be used for asynchronous reading and writing. - Asynchronous = 1073741824 - } } diff --git a/MediaBrowser.Model/IO/StreamDefaults.cs b/MediaBrowser.Model/IO/IODefaults.cs similarity index 58% rename from MediaBrowser.Model/IO/StreamDefaults.cs rename to MediaBrowser.Model/IO/IODefaults.cs index 4b55ce1f30..f392dbcce2 100644 --- a/MediaBrowser.Model/IO/StreamDefaults.cs +++ b/MediaBrowser.Model/IO/IODefaults.cs @@ -1,18 +1,18 @@ namespace MediaBrowser.Model.IO { /// - /// Class StreamDefaults. + /// Class IODefaults. /// - public static class StreamDefaults + public static class IODefaults { /// /// The default copy to buffer size. /// - public const int DefaultCopyToBufferSize = 81920; + public const int CopyToBufferSize = 81920; /// /// The default file stream buffer size. /// - public const int DefaultFileStreamBufferSize = 4096; + public const int FileStreamBufferSize = 4096; } } diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index ab906809f3..3ab621ba41 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -244,9 +244,9 @@ namespace MediaBrowser.Providers.Manager _fileSystem.SetAttributes(path, false, false); - using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.Asynchronous)) + using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous)) { - await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false); + await source.CopyToAsync(fs, IODefaults.CopyToBufferSize, cancellationToken).ConfigureAwait(false); } if (_config.Configuration.SaveMetadataHidden) diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index e9179815e7..d83c0cc86f 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -25,14 +25,12 @@ namespace MediaBrowser.Providers.Manager { private readonly ILogger _logger; private readonly IProviderManager _providerManager; - private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; - public ItemImageProvider(ILogger logger, IProviderManager providerManager, IServerConfigurationManager config, IFileSystem fileSystem) + public ItemImageProvider(ILogger logger, IProviderManager providerManager, IFileSystem fileSystem) { _logger = logger; _providerManager = providerManager; - _config = config; _fileSystem = fileSystem; } @@ -141,7 +139,7 @@ namespace MediaBrowser.Providers.Manager { var mimeType = MimeTypes.GetMimeType(response.Path); - var stream = _fileSystem.GetFileStream(response.Path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true); + var stream = new FileStream(response.Path, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true); await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index c3401f12b9..e6cb923e33 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -73,7 +73,7 @@ namespace MediaBrowser.Providers.Manager } } - var itemImageProvider = new ItemImageProvider(Logger, ProviderManager, ServerConfigurationManager, FileSystem); + var itemImageProvider = new ItemImageProvider(Logger, ProviderManager, FileSystem); var localImagesFailed = false; var allImageProviders = ((ProviderManager)ProviderManager).GetImageProviders(item, refreshOptions).ToList(); diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 631d063a54..e7b349f67b 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -182,7 +182,7 @@ namespace MediaBrowser.Providers.Manager throw new ArgumentNullException(nameof(source)); } - var fileStream = _fileSystem.GetFileStream(source, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true); + var fileStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, true); return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, saveLocallyWithMedia, cancellationToken); } diff --git a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs b/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs index e61d8792c5..939c74c01c 100644 --- a/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/AudioDbAlbumProvider.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; @@ -164,11 +165,10 @@ namespace MediaBrowser.Providers.Music { Url = url, CancellationToken = cancellationToken - }, - "GET").ConfigureAwait(false)) + HttpMethod.Get).ConfigureAwait(false)) using (var response = httpResponse.Content) - using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs b/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs index 7e5893d49a..e073a295b0 100644 --- a/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs +++ b/MediaBrowser.Providers/Music/AudioDbArtistProvider.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; @@ -152,12 +153,12 @@ namespace MediaBrowser.Providers.Music CancellationToken = cancellationToken, BufferContent = true }, - "GET").ConfigureAwait(false)) + HttpMethod.Get).ConfigureAwait(false)) using (var response = httpResponse.Content) { Directory.CreateDirectory(Path.GetDirectoryName(path)); - using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { await response.CopyToAsync(xmlFileStream).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Omdb/OmdbProvider.cs index f8b8765802..fbf6ae135b 100644 --- a/MediaBrowser.Providers/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbProvider.cs @@ -209,7 +209,7 @@ namespace MediaBrowser.Providers.Omdb string resultString; - using (var stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new StreamReader(stream, new UTF8Encoding(false))) { @@ -228,7 +228,7 @@ namespace MediaBrowser.Providers.Omdb string resultString; - using (var stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new StreamReader(stream, new UTF8Encoding(false))) { diff --git a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs index ef412db5ac..cbef27a091 100644 --- a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs +++ b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs @@ -78,7 +78,7 @@ namespace MediaBrowser.Providers.Studios private RemoteImageInfo GetImage(BaseItem item, string filename, ImageType type, string remoteFilename) { - var list = GetAvailableImages(filename, _fileSystem); + var list = GetAvailableImages(filename); var match = FindMatch(item, list); @@ -179,9 +179,9 @@ namespace MediaBrowser.Providers.Studios .Replace("/", string.Empty); } - public IEnumerable GetAvailableImages(string file, IFileSystem fileSystem) + public IEnumerable GetAvailableImages(string file) { - using (var fileStream = fileSystem.GetFileStream(file, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) + using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new StreamReader(fileStream)) { diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 37d1230e23..583c7e8ea4 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -19,7 +19,7 @@ using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; using Microsoft.Extensions.Logging; -using static MediaBrowser.Model.IO.StreamDefaults; +using static MediaBrowser.Model.IO.IODefaults; namespace MediaBrowser.Providers.Subtitles { @@ -210,7 +210,7 @@ namespace MediaBrowser.Providers.Subtitles { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); - using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, true)) + using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, FileStreamBufferSize, true)) { await stream.CopyToAsync(fs).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Tmdb/People/TmdbPersonProvider.cs index 130403e4d1..50af9913aa 100644 --- a/MediaBrowser.Providers/Tmdb/People/TmdbPersonProvider.cs +++ b/MediaBrowser.Providers/Tmdb/People/TmdbPersonProvider.cs @@ -234,7 +234,7 @@ namespace MediaBrowser.Providers.Tmdb.People { Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath)); - using (var fs = _fileSystem.GetFileStream(dataFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + using (var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { await json.CopyToAsync(fs).ConfigureAwait(false); } diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index fadf32b28f..96ebdf4a88 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -425,7 +425,7 @@ namespace MediaBrowser.WebDashboard.Api private async Task DumpFile(PackageCreator packageCreator, string resourceVirtualPath, string destinationFilePath, string mode, string appVersion) { using (var stream = await packageCreator.GetResource(resourceVirtualPath, mode, null, appVersion).ConfigureAwait(false)) - using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var fs = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { await stream.CopyToAsync(fs); } From c751ba9f70ca19297406542869a08cec9fc1e558 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 22 Jan 2020 22:27:03 +0100 Subject: [PATCH 105/108] Fix build --- .../HttpServer/HttpResultFactory.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index cefcaa835f..98a4f140e3 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -440,7 +440,7 @@ namespace Emby.Server.Implementations.HttpServer public Task GetStaticFileResult(IRequest requestContext, string path, - FileShareMode fileShare = FileShareMode.Read) + FileShare fileShare = FileShare.Read) { if (string.IsNullOrEmpty(path)) { @@ -464,7 +464,7 @@ namespace Emby.Server.Implementations.HttpServer throw new ArgumentException("Path can't be empty.", nameof(options)); } - if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite) + if (fileShare != FileShare.Read && fileShare != FileShare.ReadWrite) { throw new ArgumentException("FileShare must be either Read or ReadWrite"); } @@ -492,9 +492,9 @@ namespace Emby.Server.Implementations.HttpServer /// The path. /// The file share. /// Stream. - private Stream GetFileStream(string path, FileShareMode fileShare) + private Stream GetFileStream(string path, FileShare fileShare) { - return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare); + return new FileStream(path, FileMode.Open, FileAccess.Read, fileShare); } public Task GetStaticResult(IRequest requestContext, From 4f3bfd9146a4960dec6c45a61fca955b6f31535e Mon Sep 17 00:00:00 2001 From: ThreeFive-O Date: Fri, 24 Jan 2020 23:33:32 +0100 Subject: [PATCH 106/108] Add Transcoding framerate info --- MediaBrowser.Api/Playback/StreamState.cs | 2 +- MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs | 2 +- MediaBrowser.Controller/MediaEncoding/JobLogger.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs index 7396b5c99b..d5d2f58c03 100644 --- a/MediaBrowser.Api/Playback/StreamState.cs +++ b/MediaBrowser.Api/Playback/StreamState.cs @@ -103,7 +103,7 @@ namespace MediaBrowser.Api.Playback _mediaSourceManager = mediaSourceManager; } - public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float framerate, double? percentComplete, long bytesTranscoded, int? bitRate) + public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate) { ApiEntryPoint.Instance.ReportTranscodingProgress(TranscodingJob, this, transcodingPosition, framerate, percentComplete, bytesTranscoded, bitRate); } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 34af3b1568..35f188bb79 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -665,7 +665,7 @@ namespace MediaBrowser.Controller.MediaEncoding } public IProgress Progress { get; set; } - public virtual void ReportTranscodingProgress(TimeSpan? transcodingPosition, float framerate, double? percentComplete, long bytesTranscoded, int? bitRate) + public virtual void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate) { Progress.Report(percentComplete.Value); } diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index ac989f6ba1..171aedb0e0 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -146,7 +146,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (framerate.HasValue || percent.HasValue) { - state.ReportTranscodingProgress(transcodingPosition, 0, percent, 0, bitRate); + state.ReportTranscodingProgress(transcodingPosition, framerate, percent, bytesTranscoded, bitRate); } } } From eb04126473d01eb140a20675573945a918e47a8a Mon Sep 17 00:00:00 2001 From: a-alshabib Date: Thu, 23 Jan 2020 14:25:13 +0000 Subject: [PATCH 107/108] Translated using Weblate (Arabic) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ar/ --- Emby.Server.Implementations/Localization/Core/ar.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ar.json b/Emby.Server.Implementations/Localization/Core/ar.json index 4da3cdd3b7..8932bd0d74 100644 --- a/Emby.Server.Implementations/Localization/Core/ar.json +++ b/Emby.Server.Implementations/Localization/Core/ar.json @@ -9,7 +9,7 @@ "Channels": "القنوات", "ChapterNameValue": "الباب {0}", "Collections": "مجموعات", - "DeviceOfflineWithName": "تم قطع الاتصال بـ{0}", + "DeviceOfflineWithName": " قُطِع الاتصال بـ{0}", "DeviceOnlineWithName": "{0} متصل", "FailedLoginAttemptWithUserName": "عملية تسجيل الدخول فشلت من {0}", "Favorites": "التفضيلات", From ad5081f2763e8d9a323c7df1f6b3d89dc8ed0466 Mon Sep 17 00:00:00 2001 From: SaddFox Date: Fri, 24 Jan 2020 14:46:31 +0000 Subject: [PATCH 108/108] Translated using Weblate (Slovenian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sl/ --- Emby.Server.Implementations/Localization/Core/sl-SI.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sl-SI.json b/Emby.Server.Implementations/Localization/Core/sl-SI.json index c141a40f6e..b43cfbb747 100644 --- a/Emby.Server.Implementations/Localization/Core/sl-SI.json +++ b/Emby.Server.Implementations/Localization/Core/sl-SI.json @@ -12,7 +12,7 @@ "DeviceOfflineWithName": "{0} je prekinil povezavo", "DeviceOnlineWithName": "{0} je povezan", "FailedLoginAttemptWithUserName": "Neuspešen poskus prijave z {0}", - "Favorites": "Priljubljeni", + "Favorites": "Priljubljeno", "Folders": "Mape", "Genres": "Zvrsti", "HeaderAlbumArtists": "Izvajalci albuma",