diff options
42 files changed, 463 insertions, 191 deletions
diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index a79153e86..de9c75da2 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -266,7 +266,7 @@ namespace Emby.Naming.Common MediaFlagDelimiters = new[] { - "." + '.' }; MediaForcedFlags = new[] @@ -715,7 +715,7 @@ namespace Emby.Naming.Common /// <summary> /// Gets or sets list of external media flag delimiters. /// </summary> - public string[] MediaFlagDelimiters { get; set; } + public char[] MediaFlagDelimiters { get; set; } /// <summary> /// Gets or sets list of external media forced flags. diff --git a/Emby.Naming/ExternalFiles/ExternalPathParser.cs b/Emby.Naming/ExternalFiles/ExternalPathParser.cs index 9d07dc2f9..3bde3a1cf 100644 --- a/Emby.Naming/ExternalFiles/ExternalPathParser.cs +++ b/Emby.Naming/ExternalFiles/ExternalPathParser.cs @@ -61,11 +61,11 @@ namespace Emby.Naming.ExternalFiles { var languageString = extraString; var titleString = string.Empty; - int separatorLength = separator.Length; + const int SeparatorLength = 1; while (languageString.Length > 0) { - int lastSeparator = languageString.LastIndexOf(separator, StringComparison.OrdinalIgnoreCase); + int lastSeparator = languageString.LastIndexOf(separator); if (lastSeparator == -1) { @@ -73,7 +73,7 @@ namespace Emby.Naming.ExternalFiles } string currentSlice = languageString[lastSeparator..]; - string currentSliceWithoutSeparator = currentSlice[separatorLength..]; + string currentSliceWithoutSeparator = currentSlice[SeparatorLength..]; if (_namingOptions.MediaDefaultFlags.Any(s => currentSliceWithoutSeparator.Contains(s, StringComparison.OrdinalIgnoreCase))) { @@ -107,7 +107,7 @@ namespace Emby.Naming.ExternalFiles languageString = languageString[..lastSeparator]; } - pathInfo.Title = separatorLength <= titleString.Length ? titleString[separatorLength..] : null; + pathInfo.Title = titleString.Length >= SeparatorLength ? titleString[SeparatorLength..] : null; } return pathInfo; diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 4f8a52f41..399ece7fd 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -704,6 +704,18 @@ namespace Emby.Server.Implementations.IO return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive)); } + /// <inheritdoc /> + public virtual bool DirectoryExists(string path) + { + return Directory.Exists(path); + } + + /// <inheritdoc /> + public virtual bool FileExists(string path) + { + return File.Exists(path); + } + private EnumerationOptions GetEnumerationOptions(bool recursive) { return new EnumerationOptions diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index 7ee8d1040..01a9969b4 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -120,5 +120,7 @@ "Forced": "Vynucené", "Default": "Výchozí", "TaskOptimizeDatabaseDescription": "Zmenší databázi a odstraní prázdné místo. Spuštění této úlohy po skenování knihovny či jiných změnách databáze může zlepšit výkon.", - "TaskOptimizeDatabase": "Optimalizovat databázi" + "TaskOptimizeDatabase": "Optimalizovat databázi", + "TaskKeyframeExtractorDescription": "Vytahuje klíčové snímky ze souborů videa za účelem vytváření přesnějších seznamů přehrávání HLS. Tento úkol může trvat velmi dlouho.", + "TaskKeyframeExtractor": "Vytahovač klíčových snímků" } diff --git a/Emby.Server.Implementations/Localization/Core/cy.json b/Emby.Server.Implementations/Localization/Core/cy.json index 7fc27e18a..981614005 100644 --- a/Emby.Server.Implementations/Localization/Core/cy.json +++ b/Emby.Server.Implementations/Localization/Core/cy.json @@ -54,5 +54,57 @@ "Undefined": "Heb ddiffiniad", "TvShows": "Rhaglenni teledu", "HeaderLiveTV": "Teledu Byw", - "User": "Defnyddiwr" + "User": "Defnyddiwr", + "TaskCleanLogsDescription": "Dileu ffeiliau log sy'n fwy na {0} diwrnod oed.", + "TaskCleanLogs": "Glanhau ffolder log", + "TaskRefreshLibraryDescription": "Sganio'ch llyfrgell gyfryngau am ffeiliau newydd ac yn adnewyddu metaddata.", + "TaskRefreshLibrary": "Sganwich Llyfrgell Cyfryngau", + "TaskCleanActivityLogDescription": "Yn dileu cofnodion log gweithgaredd sy'n hŷn na'r oedran a nodwyd.", + "TaskCleanActivityLog": "Glanhau Log Gweithgaredd", + "SubtitleDownloadFailureFromForItem": "Methodd is-deitlau lawrlwytho o {0} ar gyfer {1}", + "NotificationOptionPluginError": "Methodd ategyn", + "NotificationOptionAudioPlaybackStopped": "Stopiwyd chwarae sain", + "NotificationOptionAudioPlayback": "Dechreuwyd chwarae sain", + "MessageServerConfigurationUpdated": "Mae ffurfweddiad gweinydd wedi'i ddiweddaru", + "MessageNamedServerConfigurationUpdatedWithValue": "Mae adran ffurfweddu gweinydd {0} wedi'i diweddaru", + "FailedLoginAttemptWithUserName": "Cais mewngofnodi wedi methu gan {0}", + "ValueHasBeenAddedToLibrary": "{0} wedi'i hychwanegu at eich llyfrgell gyfryngau", + "UserStoppedPlayingItemWithValues": "{0} wedi gorffen chwarae {1} ar {2}", + "UserStartedPlayingItemWithValues": "{0} yn chwarae {1} ar {2}", + "UserPolicyUpdatedWithName": "Polisi defnyddiwr wedi'i newid ar gyfer {0}", + "UserPasswordChangedWithName": "Cyfrinair wedi'i newid ar gyfer defnyddiwr {0}", + "UserOnlineFromDevice": "Mae {0} ar-lein o {1}", + "UserOfflineFromDevice": "Mae {0} wedi datgysylltu o {1}", + "UserLockedOutWithName": "Mae defnyddiwr {0} wedi'i gloi allan", + "UserDownloadingItemWithValues": "Mae {0} yn lawrlwytho {1}", + "UserDeletedWithName": "Defnyddiwr {0} wedi'i ddileu", + "UserCreatedWithName": "Defnyddiwr {0} wedi'i greu", + "StartupEmbyServerIsLoading": "Gweinydd Jellyfin yn llwytho. Triwch eto mewn ychydig.", + "ServerNameNeedsToBeRestarted": "Mae angen ailddechrau {0}", + "PluginUpdatedWithName": "{0} wedi'i ddiweddaru", + "PluginUninstalledWithName": "{0} wedi'i ddadosod", + "PluginInstalledWithName": "{0} wedi'i osod", + "NotificationOptionVideoPlaybackStopped": "Stopiwyd chwarae fideo", + "NotificationOptionVideoPlayback": "Dechreuwyd chwarae fideo", + "NotificationOptionUserLockedOut": "Defnyddiwr wedi'i gloi allan", + "NotificationOptionTaskFailed": "Methwyd cyflawni y dasg a drefnwyd", + "NotificationOptionServerRestartRequired": "Mae angen ailgychwyn y gweinydd", + "NotificationOptionPluginUpdateInstalled": "Diweddariad ategyn wedi'i osod", + "NotificationOptionPluginUninstalled": "Ategyn wedi'i ddadosod", + "NotificationOptionPluginInstalled": "Ategyn wedi'i osod", + "NotificationOptionNewLibraryContent": "Cynnwys newydd ar gael", + "NotificationOptionCameraImageUploaded": "Llun camera wedi'i huwchlwytho", + "NotificationOptionApplicationUpdateInstalled": "Diweddariad ap wedi'i osod", + "NotificationOptionApplicationUpdateAvailable": "Diweddariad ap ar gael", + "NewVersionIsAvailable": "Mae fersiwn diweddarach o'r gweinydd Jellyfin ar gael.", + "NameInstallFailed": "Gosodiad {0} wedi methu", + "MessageApplicationUpdatedTo": "Gweinydd Jellyfin wedi'i ddiweddaru i {0}", + "MessageApplicationUpdated": "Gweinydd Jellyfin wedi'i ddiweddaru", + "LabelIpAddressValue": "Cyfeiriad IP: {0}", + "ItemRemovedWithName": "{0} wedi'i dynnu o'r llyfrgell", + "ItemAddedWithName": "{0} wedi'i adio i'r llyfrgell", + "HeaderRecordingGroups": "Grwpiau Recordio", + "HeaderFavoriteSongs": "Ffefryn Ganeuon", + "HeaderFavoriteShows": "Ffefryn Shoeau", + "HeaderFavoriteEpisodes": "Ffefryn Rhaglenni" } diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json index 8abf7fa66..7d0fca47f 100644 --- a/Emby.Server.Implementations/Localization/Core/eo.json +++ b/Emby.Server.Implementations/Localization/Core/eo.json @@ -119,5 +119,7 @@ "HeaderRecordingGroups": "Rikordadaj Grupoj", "FailedLoginAttemptWithUserName": "Malsukcesa ensaluta provo de {0}", "CameraImageUploadedFrom": "Nova kamera bildo estis alŝutita de {0}", - "AuthenticationSucceededWithUserName": "{0} sukcese aŭtentikigis" + "AuthenticationSucceededWithUserName": "{0} sukcese aŭtentikigis", + "TaskKeyframeExtractorDescription": "Eltiras ĉefkadrojn el videodosieroj por krei pli precizajn HLS-ludlistojn. Ĉi tiu tasko povas funkcii dum longa tempo.", + "TaskKeyframeExtractor": "Eltiri Ĉefkadrojn" } diff --git a/Emby.Server.Implementations/Localization/Core/es-MX.json b/Emby.Server.Implementations/Localization/Core/es-MX.json index 432814dac..80ae16c5c 100644 --- a/Emby.Server.Implementations/Localization/Core/es-MX.json +++ b/Emby.Server.Implementations/Localization/Core/es-MX.json @@ -120,5 +120,7 @@ "Forced": "Forzado", "Default": "Predeterminado", "TaskOptimizeDatabase": "Optimizar base de datos", - "TaskOptimizeDatabaseDescription": "Compacta la base de datos y trunca el espacio libre. Puede mejorar el rendimiento si se realiza esta tarea después de escanear la biblioteca o después de realizar otros cambios que impliquen modificar la base de datos." + "TaskOptimizeDatabaseDescription": "Compacta la base de datos y trunca el espacio libre. Puede mejorar el rendimiento si se realiza esta tarea después de escanear la biblioteca o después de realizar otros cambios que impliquen modificar la base de datos.", + "TaskKeyframeExtractorDescription": "Extrae los cuadros clave de los archivos de vídeo para crear listas HLS más precisas. Esta tarea puede tardar un buen rato.", + "TaskKeyframeExtractor": "Extractor de Cuadros Clave" } diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json index f8c69712e..4918f468b 100644 --- a/Emby.Server.Implementations/Localization/Core/es.json +++ b/Emby.Server.Implementations/Localization/Core/es.json @@ -120,5 +120,7 @@ "Forced": "Forzado", "Default": "Predeterminado", "TaskOptimizeDatabase": "Optimizar la base de datos", - "TaskOptimizeDatabaseDescription": "Compacta y libera el espacio libre en la base de datos. Ejecutar esta tarea tras escanear la biblioteca o hacer cambios que impliquen modificaciones en la base de datos puede mejorar el rendimiento." + "TaskOptimizeDatabaseDescription": "Compacta y libera el espacio libre en la base de datos. Ejecutar esta tarea tras escanear la biblioteca o hacer cambios que impliquen modificaciones en la base de datos puede mejorar el rendimiento.", + "TaskKeyframeExtractorDescription": "Extrae los fotogramas clave de los archivos de vídeo para crear listas HLS más precisas. Esta tarea puede tardar mucho tiempo.", + "TaskKeyframeExtractor": "Extractor de Fotogramas Clave" } diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index 4a1f4f1d5..435de7363 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -119,5 +119,7 @@ "TaskCleanActivityLog": "Tyhjennä toimintahistoria", "Undefined": "Määrittelemätön", "TaskOptimizeDatabaseDescription": "Tiivistää ja puhdistaa tietokannan. Tämän toiminnon suorittaminen kirjastojen skannauksen tai muiden tietokantaan liittyvien muutoksien jälkeen voi parantaa suorituskykyä.", - "TaskOptimizeDatabase": "Optimoi tietokanta" + "TaskOptimizeDatabase": "Optimoi tietokanta", + "TaskKeyframeExtractorDescription": "Purkaa videotiedostojen avainkuvat tarkempien HLS-toistolistojen luomiseksi. Tehtävä saattaa kestää huomattavan pitkään.", + "TaskKeyframeExtractor": "Avainkuvien purkain" } diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index 85de5925e..781cfcfa2 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -61,5 +61,10 @@ "LabelRunningTimeValue": "चलने का समय: {0}", "ItemAddedWithName": "{0} को लाइब्रेरी में जोड़ा गया", "Inherit": "इनहेरिट", - "NotificationOptionVideoPlaybackStopped": "चलचित्र रुका हुआ" + "NotificationOptionVideoPlaybackStopped": "चलचित्र रुका हुआ", + "PluginUninstalledWithName": "{0} अनइंस्टॉल हुए", + "PluginInstalledWithName": "{0} इंस्टॉल हुए", + "Plugin": "प्लग-इन", + "Playlists": "प्लेलिस्ट", + "Photos": "तस्वीरें" } diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index acde84aaf..2da936cff 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -120,5 +120,7 @@ "Forced": "Kényszerített", "Default": "Alapértelmezett", "TaskOptimizeDatabaseDescription": "Tömöríti az adatbázist és csonkolja a szabad helyet. A feladat futtatása a könyvtár beolvasása után, vagy egyéb, adatbázis-módosítást igénylő változtatások végrehajtása javíthatja a teljesítményt.", - "TaskOptimizeDatabase": "Adatbázis optimalizálása" + "TaskOptimizeDatabase": "Adatbázis optimalizálása", + "TaskKeyframeExtractor": "Kulcskockák kibontása", + "TaskKeyframeExtractorDescription": "Kulcskockákat bont ki a videofájlokból, hogy pontosabb HLS lejátszási listákat hozzon létre. Ez a feladat hosszú ideig tarthat." } diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index 1b4a18deb..aaaf04712 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -120,5 +120,7 @@ "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.", "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teñşelgen jasynan asqan jazbalary joiady.", "TaskOptimizeDatabaseDescription": "Derekqordy qysyp, bos oryndy qysqartady. Būl tapsyrmany tasyğyşhanany skanerlegennen keiın nemese derekqorğa meñzeitın basqa özgertuler ıstelgennen keiın oryndau önımdılıktı damytuy mümkın.", - "TaskOptimizeDatabase": "Derekqordy oñtailandyru" + "TaskOptimizeDatabase": "Derekqordy oñtailandyru", + "TaskKeyframeExtractorDescription": "Naqtyraq HLS oynatu tızımderın jasau üşın beinefaildardan negızgı kadrlardy şyğarady. Būl tapsyrma ūzaq uaqytqa sozyluy mümkın.", + "TaskKeyframeExtractor": "Negızgı kadrlardy şyğaru" } diff --git a/Emby.Server.Implementations/Localization/Core/pr.json b/Emby.Server.Implementations/Localization/Core/pr.json index 81aa996d9..401e68b2a 100644 --- a/Emby.Server.Implementations/Localization/Core/pr.json +++ b/Emby.Server.Implementations/Localization/Core/pr.json @@ -1,7 +1,16 @@ { - "Books": "Libros", - "AuthenticationSucceededWithUserName": "{0} autentificado correctamente", + "Books": "Scrolls", + "AuthenticationSucceededWithUserName": "{0} passed yer trial", "Artists": "Artistas", "Songs": "Shantees", - "Albums": "Ships" + "Albums": "Tomes", + "Photos": "Paintings", + "NotificationOptionUserLockedOut": "Crewmate sent to the brig", + "HeaderContinueWatching": "Continue Yer Journey", + "Folders": "Chests", + "Application": "Captain", + "DeviceOnlineWithName": "{0} joined yer crew", + "DeviceOfflineWithName": "{0} abandoned ship", + "AppDeviceValues": "Captain: {0}, Ship: {1}", + "CameraImageUploadedFrom": "Yer looking glass has glimpsed another painting from {0}" } diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index dc3793f1b..dd1e5d0ee 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -120,5 +120,7 @@ "Forced": "Форсир-ые", "Default": "По умолчанию", "TaskOptimizeDatabaseDescription": "Сжимает базу данных и вырезает свободные места. Выполнение этой задачи после сканирования библиотеки или внесения других изменений, предполагающих модификации базы данных, может повысить производительность.", - "TaskOptimizeDatabase": "Оптимизация базы данных" + "TaskOptimizeDatabase": "Оптимизация базы данных", + "TaskKeyframeExtractorDescription": "Извлекаются ключевые кадры из видеофайлов для создания более точных списков плей-листов HLS. Эта задача может выполняться в течение длительного времени.", + "TaskKeyframeExtractor": "Извлечение ключевых кадров" } diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index 98d763fcd..5548a74d2 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -119,5 +119,7 @@ "Forced": "கட்டாயப்படுத்தப்பட்டது", "Default": "இயல்புநிலை", "TaskOptimizeDatabaseDescription": "தரவுத்தளத்தை சுருக்கி, இலவச இடத்தை குறைக்கிறது. நூலகத்தை ஸ்கேன் செய்தபின் அல்லது தரவுத்தள மாற்றங்களைக் குறிக்கும் பிற மாற்றங்களைச் செய்தபின் இந்த பணியை இயக்குவது செயல்திறனை மேம்படுத்தக்கூடும்.", - "TaskOptimizeDatabase": "தரவுத்தளத்தை மேம்படுத்தவும்" + "TaskOptimizeDatabase": "தரவுத்தளத்தை மேம்படுத்தவும்", + "TaskKeyframeExtractorDescription": "மிகவும் துல்லியமான HLS பிளேலிஸ்ட்களை உருவாக்க வீடியோ கோப்புகளிலிருந்து கீஃப்ரேம்களைப் பிரித்தெடுக்கிறது. இந்த பணி நீண்ட காலமாக இருக்கலாம்.", + "TaskKeyframeExtractor": "கீஃப்ரேம் எக்ஸ்ட்ராக்டர்" } diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index d0e08d8ee..a9268c7d5 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -119,5 +119,7 @@ "Forced": "Bắt Buộc", "Default": "Mặc Định", "TaskOptimizeDatabaseDescription": "Thu gọn cơ sở dữ liệu và cắt bớt dung lượng trống. Chạy tác vụ này sau khi quét thư viện hoặc thực hiện các thay đổi khác ngụ ý sửa đổi cơ sở dữ liệu có thể cải thiện hiệu suất.", - "TaskOptimizeDatabase": "Tối ưu hóa cơ sở dữ liệu" + "TaskOptimizeDatabase": "Tối ưu hóa cơ sở dữ liệu", + "TaskKeyframeExtractor": "Trích Xuất Khung Hình", + "TaskKeyframeExtractorDescription": "Trích xuất khung hình chính từ các tệp video để tạo danh sách phát HLS chính xác hơn. Tác vụ này có thể chạy trong một thời gian dài." } diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index ac4eb644b..23d2819c3 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -120,5 +120,7 @@ "Forced": "强制的", "Default": "默认", "TaskOptimizeDatabaseDescription": "压缩数据库并优化可用空间,在扫描库或执行其他数据库修改后运行此任务可能会提高性能。", - "TaskOptimizeDatabase": "优化数据库" + "TaskOptimizeDatabase": "优化数据库", + "TaskKeyframeExtractorDescription": "从视频文件中提取关键帧以创建更准确的HLS播放列表。这项任务可能需要很长时间。", + "TaskKeyframeExtractor": "关键帧提取器" } diff --git a/Emby.Server.Implementations/Localization/Core/zh-HK.json b/Emby.Server.Implementations/Localization/Core/zh-HK.json index 1cc97bc27..ac74da67d 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-HK.json +++ b/Emby.Server.Implementations/Localization/Core/zh-HK.json @@ -103,7 +103,7 @@ "TaskCleanTranscodeDescription": "刪除超過一天的轉碼文件。", "TaskCleanTranscode": "清理轉碼目錄", "TaskUpdatePluginsDescription": "下載並安裝配置為自動更新的插件的更新。", - "TaskRefreshPeopleDescription": "更新媒體庫中演員和導演的metadata。", + "TaskRefreshPeopleDescription": "更新媒體庫中演員和導演的元數據。", "TaskCleanLogsDescription": "刪除超過{0}天的日誌文件。", "TaskCleanLogs": "清理日誌目錄", "TaskRefreshLibrary": "掃描媒體庫", diff --git a/Emby.Server.Implementations/Sorting/IndexNumberComparer.cs b/Emby.Server.Implementations/Sorting/IndexNumberComparer.cs new file mode 100644 index 000000000..e39280a10 --- /dev/null +++ b/Emby.Server.Implementations/Sorting/IndexNumberComparer.cs @@ -0,0 +1,50 @@ +using System; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Sorting; +using MediaBrowser.Model.Querying; + +namespace Emby.Server.Implementations.Sorting +{ + /// <summary> + /// Class IndexNumberComparer. + /// </summary> + public class IndexNumberComparer : IBaseItemComparer + { + /// <summary> + /// Gets the name. + /// </summary> + /// <value>The name.</value> + public string Name => ItemSortBy.IndexNumber; + + /// <summary> + /// Compares the specified x. + /// </summary> + /// <param name="x">The x.</param> + /// <param name="y">The y.</param> + /// <returns>System.Int32.</returns> + public int Compare(BaseItem? x, BaseItem? y) + { + if (x == null) + { + throw new ArgumentNullException(nameof(x)); + } + + if (y == null) + { + throw new ArgumentNullException(nameof(y)); + } + + if (!x.IndexNumber.HasValue) + { + return -1; + } + + if (!y.IndexNumber.HasValue) + { + return 1; + } + + return x.IndexNumber.Value.CompareTo(y.IndexNumber.Value); + } + } +} diff --git a/Emby.Server.Implementations/Sorting/ParentIndexNumberComparer.cs b/Emby.Server.Implementations/Sorting/ParentIndexNumberComparer.cs new file mode 100644 index 000000000..ffc4e0cad --- /dev/null +++ b/Emby.Server.Implementations/Sorting/ParentIndexNumberComparer.cs @@ -0,0 +1,50 @@ +using System; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Sorting; +using MediaBrowser.Model.Querying; + +namespace Emby.Server.Implementations.Sorting +{ + /// <summary> + /// Class ParentIndexNumberComparer. + /// </summary> + public class ParentIndexNumberComparer : IBaseItemComparer + { + /// <summary> + /// Gets the name. + /// </summary> + /// <value>The name.</value> + public string Name => ItemSortBy.ParentIndexNumber; + + /// <summary> + /// Compares the specified x. + /// </summary> + /// <param name="x">The x.</param> + /// <param name="y">The y.</param> + /// <returns>System.Int32.</returns> + public int Compare(BaseItem? x, BaseItem? y) + { + if (x == null) + { + throw new ArgumentNullException(nameof(x)); + } + + if (y == null) + { + throw new ArgumentNullException(nameof(y)); + } + + if (!x.ParentIndexNumber.HasValue) + { + return -1; + } + + if (!y.ParentIndexNumber.HasValue) + { + return 1; + } + + return x.ParentIndexNumber.Value.CompareTo(y.ParentIndexNumber.Value); + } + } +} diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a47650a32..f8ba85af1 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -126,7 +126,8 @@ namespace Emby.Server.Implementations.TV parentsFolders.ToList()) .Cast<Episode>() .Where(episode => !string.IsNullOrEmpty(episode.SeriesPresentationUniqueKey)) - .Select(GetUniqueSeriesKey); + .Select(GetUniqueSeriesKey) + .ToList(); // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items, options); @@ -134,13 +135,21 @@ namespace Emby.Server.Implementations.TV return GetResult(episodes, request); } - public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable<string> seriesKeys, DtoOptions dtoOptions) + public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IReadOnlyList<string> seriesKeys, DtoOptions dtoOptions) { // Avoid implicitly captured closure var currentUser = user; var allNextUp = seriesKeys - .Select(i => GetNextUp(i, currentUser, dtoOptions, request.Rewatching)); + .Select(i => GetNextUp(i, currentUser, dtoOptions, false)); + + if (request.EnableRewatching) + { + allNextUp = allNextUp.Concat( + seriesKeys.Select(i => GetNextUp(i, currentUser, dtoOptions, true)) + ) + .OrderByDescending(i => i.Item1); + } // If viewing all next up for all series, remove first episodes // But if that returns empty, keep those first episodes (avoid completely empty view) diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 5d39d906f..636130543 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -68,7 +68,7 @@ namespace Jellyfin.Api.Controllers /// <param name="nextUpDateCutoff">Optional. Starting date of shows to show in Next Up section.</param> /// <param name="enableTotalRecordCount">Whether to enable the total records count. Defaults to true.</param> /// <param name="disableFirstEpisode">Whether to disable sending the first episode in a series as next up.</param> - /// <param name="rewatching">Whether to get a rewatching next up instead of standard next up.</param> + /// <param name="enableRewatching">Whether to include watched episode in next up results.</param> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the next up episodes.</returns> [HttpGet("NextUp")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] DateTime? nextUpDateCutoff, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool disableFirstEpisode = false, - [FromQuery] bool rewatching = false) + [FromQuery] bool enableRewatching = false) { var options = new DtoOptions { Fields = fields } .AddClientFields(Request) @@ -103,7 +103,7 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount, DisableFirstEpisode = disableFirstEpisode, NextUpDateCutoff = nextUpDateCutoff ?? DateTime.MinValue, - Rewatching = rewatching + EnableRewatching = enableRewatching }, options); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index e70b79837..c8762b7c5 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -458,9 +458,12 @@ namespace Jellyfin.Api.Helpers var audioCodec = state.ActualOutputAudioCodec; var videoCodec = state.ActualOutputVideoCodec; var hardwareAccelerationTypeString = _serverConfigurationManager.GetEncodingOptions().HardwareAccelerationType; - HardwareEncodingType? hardwareAccelerationType = string.IsNullOrEmpty(hardwareAccelerationTypeString) - ? null - : (HardwareEncodingType)Enum.Parse(typeof(HardwareEncodingType), hardwareAccelerationTypeString, true); + HardwareEncodingType? hardwareAccelerationType = null; + if (!string.IsNullOrEmpty(hardwareAccelerationTypeString) + && Enum.TryParse<HardwareEncodingType>(hardwareAccelerationTypeString, out var parsedHardwareAccelerationType)) + { + hardwareAccelerationType = parsedHardwareAccelerationType; + } _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo { diff --git a/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs index 21f153623..afd7aee5d 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs @@ -58,13 +58,18 @@ namespace Jellyfin.Server.Migrations.Routines foreach (var row in authenticatedDevices) { + var dateCreatedStr = row[9].ToString(); + _ = DateTime.TryParse(dateCreatedStr, out var dateCreated); + var dateLastActivityStr = row[10].ToString(); + _ = DateTime.TryParse(dateLastActivityStr, out var dateLastActivity); + if (row[6].IsDbNull()) { dbContext.ApiKeys.Add(new ApiKey(row[3].ToString()) { AccessToken = row[1].ToString(), - DateCreated = row[9].ToDateTime(), - DateLastActivity = row[10].ToDateTime() + DateCreated = dateCreated, + DateLastActivity = dateLastActivity }); } else @@ -78,8 +83,8 @@ namespace Jellyfin.Server.Migrations.Routines { AccessToken = row[1].ToString(), IsActive = row[8].ToBool(), - DateCreated = row[9].ToDateTime(), - DateLastActivity = row[10].ToDateTime() + DateCreated = dateCreated, + DateLastActivity = dateLastActivity }); } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 0f62e8e1e..c52732858 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -887,7 +887,7 @@ namespace MediaBrowser.Controller.Entities return Name; } - public string GetInternalMetadataPath() + public virtual string GetInternalMetadataPath() { var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 44589aa22..f7248acac 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -84,7 +84,6 @@ namespace MediaBrowser.Controller.MediaEncoding { "vaapi", hwEncoder + "_vaapi" }, { "videotoolbox", hwEncoder + "_videotoolbox" }, { "v4l2m2m", hwEncoder + "_v4l2m2m" }, - { "omx", hwEncoder + "_omx" }, }; if (!string.IsNullOrEmpty(hwType) @@ -581,13 +580,13 @@ namespace MediaBrowser.Controller.MediaEncoding options); } - private string GetVaapiDeviceArgs(string renderNodePath, string kernelDriver, string driver, string alias) + private string GetVaapiDeviceArgs(string renderNodePath, string driver, string kernelDriver, string alias) { alias ??= VaapiAlias; renderNodePath = renderNodePath ?? "/dev/dri/renderD128"; - var options = string.IsNullOrEmpty(kernelDriver) || string.IsNullOrEmpty(driver) + var options = string.IsNullOrEmpty(driver) ? renderNodePath - : ",kernel_driver=" + kernelDriver + ",driver=" + driver; + : ",driver=" + driver + (string.IsNullOrEmpty(kernelDriver) ? string.Empty : ",kernel_driver=" + kernelDriver); return string.Format( CultureInfo.InvariantCulture, @@ -602,7 +601,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (OperatingSystem.IsLinux()) { // derive qsv from vaapi device - return GetVaapiDeviceArgs(null, "i915", "iHD", VaapiAlias) + arg + "@" + VaapiAlias; + return GetVaapiDeviceArgs(null, "iHD", "i915", VaapiAlias) + arg + "@" + VaapiAlias; } if (OperatingSystem.IsWindows()) @@ -691,7 +690,19 @@ namespace MediaBrowser.Controller.MediaEncoding return string.Empty; } - args.Append(GetVaapiDeviceArgs(options.VaapiDevice, null, null, VaapiAlias)); + if (_mediaEncoder.IsVaapiDeviceInteliHD) + { + args.Append(GetVaapiDeviceArgs(null, "iHD", null, VaapiAlias)); + } + else if (_mediaEncoder.IsVaapiDeviceInteli965) + { + args.Append(GetVaapiDeviceArgs(null, "i965", null, VaapiAlias)); + } + else + { + args.Append(GetVaapiDeviceArgs(options.VaapiDevice, null, null, VaapiAlias)); + } + var filterDevArgs = GetFilterHwDeviceArgs(VaapiAlias); if (isHwTonemapAvailable && IsOpenclFullSupported()) @@ -771,10 +782,6 @@ namespace MediaBrowser.Controller.MediaEncoding args.Append(GetCudaDeviceArgs(0, CudaAlias)) .Append(GetFilterHwDeviceArgs(CudaAlias)); - - // workaround for "No decoder surfaces left" error, - // but will increase vram usage. https://trac.ffmpeg.org/ticket/7562 - args.Append(" -extra_hw_frames 3"); } else if (string.Equals(optHwaccelType, "amf", StringComparison.OrdinalIgnoreCase)) { @@ -1585,10 +1592,8 @@ namespace MediaBrowser.Controller.MediaEncoding if (!string.IsNullOrEmpty(profile)) { - if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) { - // not supported by h264_omx param += " -profile:v:0 " + profile; } } @@ -1627,8 +1632,7 @@ namespace MediaBrowser.Controller.MediaEncoding // NVENC cannot adjust the given level, just throw an error. // level option may cause corrupted frames on AMD VAAPI. } - else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) - || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) + else if (!string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) { param += " -level " + level; } @@ -4288,11 +4292,6 @@ namespace MediaBrowser.Controller.MediaEncoding { return GetVideotoolboxVidDecoder(state, options, videoStream, bitDepth); } - - if (string.Equals(options.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase)) - { - return GetOmxVidDecoder(state, options, videoStream, bitDepth); - } } var whichCodec = videoStream.Codec; @@ -4431,7 +4430,8 @@ namespace MediaBrowser.Controller.MediaEncoding { if (options.EnableEnhancedNvdecDecoder && isCudaSupported && isCodecAvailable) { - return " -hwaccel cuda" + (outputHwSurface ? " -hwaccel_output_format cuda" : string.Empty) + (isAv1 ? " -c:v av1" : string.Empty); + // set -threads 1 to nvdec decoder explicitly since it doesn't implement threading support. + return " -hwaccel cuda" + (outputHwSurface ? " -hwaccel_output_format cuda" : string.Empty) + " -threads 1" + (isAv1 ? " -c:v av1" : string.Empty); } } @@ -4767,43 +4767,6 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } - public string GetOmxVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth) - { - if (!OperatingSystem.IsLinux() - || !string.Equals(options.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase)) - { - return null; - } - - var is8bitSwFormatsOmx = string.Equals("yuv420p", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase); - - if (is8bitSwFormatsOmx) - { - if (string.Equals("avc", videoStream.Codec, StringComparison.OrdinalIgnoreCase) - || string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)) - { - return GetHwDecoderName(options, "h264", "mmal", "h264", bitDepth); - } - - if (string.Equals("mpeg2video", videoStream.Codec, StringComparison.OrdinalIgnoreCase)) - { - return GetHwDecoderName(options, "mpeg2", "mmal", "mpeg2video", bitDepth); - } - - if (string.Equals("mpeg4", videoStream.Codec, StringComparison.OrdinalIgnoreCase)) - { - return GetHwDecoderName(options, "mpeg4", "mmal", "mpeg4", bitDepth); - } - - if (string.Equals("vc1", videoStream.Codec, StringComparison.OrdinalIgnoreCase)) - { - return GetHwDecoderName(options, "vc1", "mmal", "vc1", bitDepth); - } - } - - return null; - } - /// <summary> /// Gets the number of threads. /// </summary> diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index fe3069934..20d372d7a 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -44,18 +44,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "mpeg4_cuvid", "vp8_cuvid", "vp9_cuvid", - "av1_cuvid", - "h264_mmal", - "mpeg2_mmal", - "mpeg4_mmal", - "vc1_mmal", - "h264_opencl", - "hevc_opencl", - "mpeg2_opencl", - "mpeg4_opencl", - "vp8_opencl", - "vp9_opencl", - "vc1_opencl" + "av1_cuvid" }; private static readonly string[] _requiredEncoders = new[] @@ -82,8 +71,6 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc_nvenc", "h264_vaapi", "hevc_vaapi", - "h264_omx", - "hevc_omx", "h264_v4l2m2m", "h264_videotoolbox", "hevc_videotoolbox" diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index 7207795b0..786b20e9e 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -200,5 +200,19 @@ namespace MediaBrowser.Model.IO void SetAttributes(string path, bool isHidden, bool readOnly); IEnumerable<FileSystemMetadata> GetDrives(); + + /// <summary> + /// Determines whether the directory exists. + /// </summary> + /// <param name="path">The path.</param> + /// <returns>Whether the path exists.</returns> + bool DirectoryExists(string path); + + /// <summary> + /// Determines whether the file exists. + /// </summary> + /// <param name="path">The path.</param> + /// <returns>Whether the path exists.</returns> + bool FileExists(string path); } } diff --git a/MediaBrowser.Model/Querying/ItemSortBy.cs b/MediaBrowser.Model/Querying/ItemSortBy.cs index 0b846bb96..0a28acf37 100644 --- a/MediaBrowser.Model/Querying/ItemSortBy.cs +++ b/MediaBrowser.Model/Querying/ItemSortBy.cs @@ -102,5 +102,9 @@ namespace MediaBrowser.Model.Querying public const string DateLastContentAdded = "DateLastContentAdded"; public const string SeriesDatePlayed = "SeriesDatePlayed"; + + public const string ParentIndexNumber = "ParentIndexNumber"; + + public const string IndexNumber = "IndexNumber"; } } diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index 7c65fda1a..133d6a916 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Model.Querying EnableTotalRecordCount = true; DisableFirstEpisode = false; NextUpDateCutoff = DateTime.MinValue; - Rewatching = false; + EnableRewatching = false; } /// <summary> @@ -86,6 +86,6 @@ namespace MediaBrowser.Model.Querying /// <summary> /// Gets or sets a value indicating whether getting rewatching next up list. /// </summary> - public bool Rewatching { get; set; } + public bool EnableRewatching { get; set; } } } diff --git a/MediaBrowser.Model/Session/GeneralCommand.cs b/MediaBrowser.Model/Session/GeneralCommand.cs index 29528c110..757b19b31 100644 --- a/MediaBrowser.Model/Session/GeneralCommand.cs +++ b/MediaBrowser.Model/Session/GeneralCommand.cs @@ -2,20 +2,26 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; -namespace MediaBrowser.Model.Session +namespace MediaBrowser.Model.Session; + +public class GeneralCommand { - public class GeneralCommand + public GeneralCommand() + : this(new Dictionary<string, string>()) + { + } + + [JsonConstructor] + public GeneralCommand(Dictionary<string, string> arguments) { - public GeneralCommand() - { - Arguments = new Dictionary<string, string>(); - } + Arguments = arguments; + } - public GeneralCommandType Name { get; set; } + public GeneralCommandType Name { get; set; } - public Guid ControllingUserId { get; set; } + public Guid ControllingUserId { get; set; } - public Dictionary<string, string> Arguments { get; } - } + public Dictionary<string, string> Arguments { get; } } diff --git a/MediaBrowser.Model/Session/HardwareEncodingType.cs b/MediaBrowser.Model/Session/HardwareEncodingType.cs index 0db5697d3..f5753467a 100644 --- a/MediaBrowser.Model/Session/HardwareEncodingType.cs +++ b/MediaBrowser.Model/Session/HardwareEncodingType.cs @@ -21,28 +21,18 @@ NVENC = 2, /// <summary> - /// OpenMax OMX. + /// Video4Linux2 V4L2. /// </summary> - OMX = 3, - - /// <summary> - /// Exynos V4L2 MFC. - /// </summary> - V4L2M2M = 4, - - /// <summary> - /// MediaCodec Android. - /// </summary> - MediaCodec = 5, + V4L2M2M = 3, /// <summary> /// Video Acceleration API (VAAPI). /// </summary> - VAAPI = 6, + VAAPI = 4, /// <summary> /// Video ToolBox. /// </summary> - VideoToolBox = 7 + VideoToolBox = 5 } } diff --git a/MediaBrowser.Providers/MediaInfo/AudioResolver.cs b/MediaBrowser.Providers/MediaInfo/AudioResolver.cs index ff90eeffb..0bdf447ba 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioResolver.cs @@ -3,6 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; namespace MediaBrowser.Providers.MediaInfo { @@ -16,13 +17,20 @@ namespace MediaBrowser.Providers.MediaInfo /// </summary> /// <param name="localizationManager">The localization manager.</param> /// <param name="mediaEncoder">The media encoder.</param> + /// <param name="fileSystem">The file system.</param> /// <param name="namingOptions">The <see cref="NamingOptions"/> object containing FileExtensions, MediaDefaultFlags, MediaForcedFlags and MediaFlagDelimiters.</param> public AudioResolver( ILocalizationManager localizationManager, IMediaEncoder mediaEncoder, + IFileSystem fileSystem, NamingOptions namingOptions) - : base(localizationManager, mediaEncoder, namingOptions, DlnaProfileType.Audio) - { + : base( + localizationManager, + mediaEncoder, + fileSystem, + namingOptions, + DlnaProfileType.Audio) + { } } } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index 560e20dae..fcd3f28d4 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -19,9 +19,9 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; -using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging; @@ -58,11 +58,12 @@ namespace MediaBrowser.Providers.MediaInfo ISubtitleManager subtitleManager, IChapterManager chapterManager, ILibraryManager libraryManager, + IFileSystem fileSystem, NamingOptions namingOptions) { _logger = logger; - _audioResolver = new AudioResolver(localization, mediaEncoder, namingOptions); - _subtitleResolver = new SubtitleResolver(localization, mediaEncoder, namingOptions); + _audioResolver = new AudioResolver(localization, mediaEncoder, fileSystem, namingOptions); + _subtitleResolver = new SubtitleResolver(localization, mediaEncoder, fileSystem, namingOptions); _videoProber = new FFProbeVideoInfo( _logger, mediaSourceManager, diff --git a/MediaBrowser.Providers/MediaInfo/MediaInfoResolver.cs b/MediaBrowser.Providers/MediaInfo/MediaInfoResolver.cs index 40b45faf5..39be405ec 100644 --- a/MediaBrowser.Providers/MediaInfo/MediaInfoResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/MediaInfoResolver.cs @@ -14,6 +14,7 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Providers.MediaInfo @@ -24,16 +25,6 @@ namespace MediaBrowser.Providers.MediaInfo public abstract class MediaInfoResolver { /// <summary> - /// The <see cref="CompareOptions"/> instance. - /// </summary> - private const CompareOptions CompareOptions = System.Globalization.CompareOptions.IgnoreCase | System.Globalization.CompareOptions.IgnoreNonSpace | System.Globalization.CompareOptions.IgnoreSymbols; - - /// <summary> - /// The <see cref="CompareInfo"/> instance. - /// </summary> - private readonly CompareInfo _compareInfo = CultureInfo.InvariantCulture.CompareInfo; - - /// <summary> /// The <see cref="ExternalPathParser"/> instance. /// </summary> private readonly ExternalPathParser _externalPathParser; @@ -43,6 +34,8 @@ namespace MediaBrowser.Providers.MediaInfo /// </summary> private readonly IMediaEncoder _mediaEncoder; + private readonly IFileSystem _fileSystem; + /// <summary> /// The <see cref="NamingOptions"/> instance. /// </summary> @@ -58,15 +51,18 @@ namespace MediaBrowser.Providers.MediaInfo /// </summary> /// <param name="localizationManager">The localization manager.</param> /// <param name="mediaEncoder">The media encoder.</param> + /// <param name="fileSystem">The file system.</param> /// <param name="namingOptions">The <see cref="NamingOptions"/> object containing FileExtensions, MediaDefaultFlags, MediaForcedFlags and MediaFlagDelimiters.</param> /// <param name="type">The <see cref="DlnaProfileType"/> of the parsed file.</param> protected MediaInfoResolver( ILocalizationManager localizationManager, IMediaEncoder mediaEncoder, + IFileSystem fileSystem, NamingOptions namingOptions, DlnaProfileType type) { _mediaEncoder = mediaEncoder; + _fileSystem = fileSystem; _namingOptions = namingOptions; _type = type; _externalPathParser = new ExternalPathParser(namingOptions, localizationManager, _type); @@ -148,28 +144,33 @@ namespace MediaBrowser.Providers.MediaInfo // Check if video folder exists string folder = video.ContainingFolderPath; - if (!Directory.Exists(folder)) + if (!_fileSystem.DirectoryExists(folder)) { return Array.Empty<ExternalPathParserResult>(); } - var externalPathInfos = new List<ExternalPathParserResult>(); - var files = directoryService.GetFilePaths(folder, clearCache).ToList(); - files.AddRange(directoryService.GetFilePaths(video.GetInternalMetadataPath(), clearCache)); + var internalMetadataPath = video.GetInternalMetadataPath(); + if (_fileSystem.DirectoryExists(internalMetadataPath)) + { + files.AddRange(directoryService.GetFilePaths(internalMetadataPath, clearCache)); + } if (!files.Any()) { return Array.Empty<ExternalPathParserResult>(); } + var externalPathInfos = new List<ExternalPathParserResult>(); + ReadOnlySpan<char> prefix = video.FileNameWithoutExtension; foreach (var file in files) { - var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); - if (_compareInfo.IsPrefix(fileNameWithoutExtension, video.FileNameWithoutExtension, CompareOptions, out int matchLength) - && (fileNameWithoutExtension.Length == matchLength || _namingOptions.MediaFlagDelimiters.Contains(fileNameWithoutExtension[matchLength].ToString()))) + var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.AsSpan()); + if (fileNameWithoutExtension.Length >= prefix.Length + && prefix.Equals(fileNameWithoutExtension[..prefix.Length], StringComparison.OrdinalIgnoreCase) + && (fileNameWithoutExtension.Length == prefix.Length || _namingOptions.MediaFlagDelimiters.Contains(fileNameWithoutExtension[prefix.Length]))) { - var externalPathInfo = _externalPathParser.ParseFile(file, fileNameWithoutExtension[matchLength..]); + var externalPathInfo = _externalPathParser.ParseFile(file, fileNameWithoutExtension[prefix.Length..].ToString()); if (externalPathInfo != null) { diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs index 289036fda..4b9ba944a 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs @@ -3,6 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; namespace MediaBrowser.Providers.MediaInfo { @@ -16,13 +17,20 @@ namespace MediaBrowser.Providers.MediaInfo /// </summary> /// <param name="localizationManager">The localization manager.</param> /// <param name="mediaEncoder">The media encoder.</param> + /// <param name="fileSystem">The file system.</param> /// <param name="namingOptions">The <see cref="NamingOptions"/> object containing FileExtensions, MediaDefaultFlags, MediaForcedFlags and MediaFlagDelimiters.</param> public SubtitleResolver( ILocalizationManager localizationManager, IMediaEncoder mediaEncoder, + IFileSystem fileSystem, NamingOptions namingOptions) - : base(localizationManager, mediaEncoder, namingOptions, DlnaProfileType.Subtitle) - { + : base( + localizationManager, + mediaEncoder, + fileSystem, + namingOptions, + DlnaProfileType.Subtitle) + { } } } diff --git a/MediaBrowser.Providers/Plugins/StudioImages/Plugin.cs b/MediaBrowser.Providers/Plugins/StudioImages/Plugin.cs index e0ab31b56..f4941565f 100644 --- a/MediaBrowser.Providers/Plugins/StudioImages/Plugin.cs +++ b/MediaBrowser.Providers/Plugins/StudioImages/Plugin.cs @@ -12,8 +12,7 @@ namespace MediaBrowser.Providers.Plugins.StudioImages { public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages { - // TODO change this for a Jellyfin-hosted repository. - public const string DefaultServer = "https://raw.github.com/MediaBrowser/MediaBrowser.Resources/master/images/imagesbyname"; + public const string DefaultServer = "https://raw.github.com/jellyfin/emby-artwork/master/studios"; public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer) diff --git a/MediaBrowser.Providers/Plugins/StudioImages/StudiosImageProvider.cs b/MediaBrowser.Providers/Plugins/StudioImages/StudiosImageProvider.cs index 3a3048cec..e81324a6b 100644 --- a/MediaBrowser.Providers/Plugins/StudioImages/StudiosImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/StudioImages/StudiosImageProvider.cs @@ -110,19 +110,19 @@ namespace MediaBrowser.Providers.Studios private string GetUrl(string image, string filename) { - return string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}.jpg", repositoryUrl, image, filename); + return string.Format(CultureInfo.InvariantCulture, "{0}/images/{1}/{2}.jpg", repositoryUrl, image, filename); } private Task<string> EnsureThumbsList(string file, CancellationToken cancellationToken) { - string url = string.Format(CultureInfo.InvariantCulture, "{0}/studiothumbs.txt", repositoryUrl); + string url = string.Format(CultureInfo.InvariantCulture, "{0}/thumbs.txt", repositoryUrl); return EnsureList(url, file, _fileSystem, cancellationToken); } private Task<string> EnsurePosterList(string file, CancellationToken cancellationToken) { - string url = string.Format(CultureInfo.InvariantCulture, "{0}/studioposters.txt", repositoryUrl); + string url = string.Format(CultureInfo.InvariantCulture, "{0}/posters.txt", repositoryUrl); return EnsureList(url, file, _fileSystem, cancellationToken); } diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/AudioResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/AudioResolverTests.cs index 381d6c72d..aec523882 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/AudioResolverTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/AudioResolverTests.cs @@ -11,6 +11,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Providers.MediaInfo; using Moq; using Xunit; @@ -45,7 +46,13 @@ public class AudioResolverTests } })); - _audioResolver = new AudioResolver(localizationManager, mediaEncoder.Object, new NamingOptions()); + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MediaInfoResolverTests.VideoDirectoryRegex))) + .Returns(true); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MediaInfoResolverTests.MetadataDirectoryRegex))) + .Returns(true); + + _audioResolver = new AudioResolver(localizationManager, mediaEncoder.Object, fileSystem.Object, new NamingOptions()); } [Theory] diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/MediaInfoResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/MediaInfoResolverTests.cs index 926ec5c91..98b4a6ccf 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/MediaInfoResolverTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/MediaInfoResolverTests.cs @@ -15,6 +15,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Providers.MediaInfo; using Moq; @@ -25,9 +26,9 @@ namespace Jellyfin.Providers.Tests.MediaInfo; public class MediaInfoResolverTests { public const string VideoDirectoryPath = "Test Data/Video"; - private const string VideoDirectoryRegex = @"Test Data[/\\]Video"; - private const string MetadataDirectoryPath = "library/00/00000000000000000000000000000000"; - private const string MetadataDirectoryRegex = @"library.*"; + public const string VideoDirectoryRegex = @"Test Data[/\\]Video"; + public const string MetadataDirectoryPath = "library/00/00000000000000000000000000000000"; + public const string MetadataDirectoryRegex = @"library.*"; private readonly ILocalizationManager _localizationManager; private readonly MediaInfoResolver _subtitleResolver; @@ -61,13 +62,19 @@ public class MediaInfoResolverTests } })); - _subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, new NamingOptions()); + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsAny<string>())) + .Returns(false); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(VideoDirectoryRegex))) + .Returns(true); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MetadataDirectoryRegex))) + .Returns(true); + + _subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, fileSystem.Object, new NamingOptions()); } - [Theory] - [InlineData("https://url.com/My.Video.mkv")] - [InlineData("non-existent/path")] - public void GetExternalFiles_BadPaths_ReturnsNoSubtitles(string path) + [Fact] + public void GetExternalFiles_BadProtocol_ReturnsNoSubtitles() { // need a media source manager capable of returning something other than file protocol var mediaSourceManager = new Mock<IMediaSourceManager>(); @@ -77,27 +84,67 @@ public class MediaInfoResolverTests var video = new Movie { - Path = path + Path = "https://url.com/My.Video.mkv" }; - var files = _subtitleResolver.GetExternalFiles(video, Mock.Of<IDirectoryService>(), false); + Assert.Empty(_subtitleResolver.GetExternalFiles(video, Mock.Of<IDirectoryService>(), false)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void GetExternalFiles_MissingDirectory_DirectoryNotQueried(bool metadataDirectory) + { + BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>(); + + string containingFolderPath, metadataPath; + + if (metadataDirectory) + { + containingFolderPath = VideoDirectoryPath; + metadataPath = "invalid"; + } + else + { + containingFolderPath = "invalid"; + metadataPath = MetadataDirectoryPath; + } + + var video = new Mock<Movie>(); + video.Setup(m => m.Path) + .Returns(VideoDirectoryPath + "/My.Video.mkv"); + video.Setup(m => m.ContainingFolderPath) + .Returns(containingFolderPath); + video.Setup(m => m.GetInternalMetadataPath()) + .Returns(metadataPath); - Assert.Empty(files); + string pathNotFoundRegex = metadataDirectory ? MetadataDirectoryRegex : VideoDirectoryRegex; + + var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict); + // any path other than test target exists and provides an empty listing + directoryService.Setup(ds => ds.GetFilePaths(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())) + .Returns(Array.Empty<string>()); + + _subtitleResolver.GetExternalFiles(video.Object, directoryService.Object, false); + + directoryService.Verify( + ds => ds.GetFilePaths(It.IsRegex(pathNotFoundRegex), It.IsAny<bool>(), It.IsAny<bool>()), + Times.Never); } [Theory] - [InlineData("My.Video.srt", null)] // exact - [InlineData("My.Video.en.srt", "eng")] - [InlineData("MyVideo.en.srt", "eng")] // shorter title - [InlineData("My _ Video.en.srt", "eng")] // longer title - [InlineData("My.Video.en.srt", "eng", true)] - public void GetExternalFiles_FuzzyMatching_MatchesAndParsesToken(string file, string? language, bool metadataDirectory = false) + [InlineData("My.Video.mkv", "My.Video.srt", null)] + [InlineData("My.Video.mkv", "My.Video.en.srt", "eng")] + [InlineData("My.Video.mkv", "My.Video.en.srt", "eng", true)] + [InlineData("Example Movie (2021).mp4", "Example Movie (2021).English.Srt", "eng")] + [InlineData("[LTDB] Who Framed Roger Rabbit (1998) - [Bluray-1080p].mkv", "[LTDB] Who Framed Roger Rabbit (1998) - [Bluray-1080p].en.srt", "eng")] + public void GetExternalFiles_NameMatching_MatchesAndParsesToken(string movie, string file, string? language, bool metadataDirectory = false) { BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>(); var video = new Movie { - Path = VideoDirectoryPath + "/My.Video.mkv" + Path = VideoDirectoryPath + "/" + movie }; var directoryService = GetDirectoryServiceForExternalFile(file, metadataDirectory); @@ -110,12 +157,13 @@ public class MediaInfoResolverTests } [Theory] + [InlineData("cover.jpg")] [InlineData("My.Video.mp3")] [InlineData("My.Video.png")] [InlineData("My.Video.txt")] [InlineData("My.Video Sequel.srt")] [InlineData("Some.Other.Video.srt")] - public void GetExternalFiles_FuzzyMatching_RejectsNonMatches(string file) + public void GetExternalFiles_NameMatching_RejectsNonMatches(string file) { BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>(); @@ -132,7 +180,6 @@ public class MediaInfoResolverTests [Theory] [InlineData("https://url.com/My.Video.mkv")] - [InlineData("non-existent/path")] [InlineData(VideoDirectoryPath)] // valid but no files found for this test public async void GetExternalStreams_BadPaths_ReturnsNoSubtitles(string path) { @@ -152,8 +199,9 @@ public class MediaInfoResolverTests .Returns(Array.Empty<string>()); var mediaEncoder = Mock.Of<IMediaEncoder>(MockBehavior.Strict); + var fileSystem = Mock.Of<IFileSystem>(); - var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder, new NamingOptions()); + var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder, fileSystem, new NamingOptions()); var streams = await subtitleResolver.GetExternalStreamsAsync(video, 0, directoryService.Object, false, CancellationToken.None); @@ -252,7 +300,13 @@ public class MediaInfoResolverTests MediaStreams = inputStreams.ToList() })); - var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, new NamingOptions()); + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(VideoDirectoryRegex))) + .Returns(true); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MetadataDirectoryRegex))) + .Returns(true); + + var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, fileSystem.Object, new NamingOptions()); var directoryService = GetDirectoryServiceForExternalFile(file); var streams = await subtitleResolver.GetExternalStreamsAsync(video, 0, directoryService, false, CancellationToken.None); @@ -291,7 +345,7 @@ public class MediaInfoResolverTests var files = new string[fileCount]; for (int i = 0; i < fileCount; i++) { - files[i] = $"{VideoDirectoryPath}/MyVideo.{i}.srt"; + files[i] = $"{VideoDirectoryPath}/My.Video.{i}.srt"; } var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict); @@ -318,7 +372,13 @@ public class MediaInfoResolverTests MediaStreams = GenerateMediaStreams() })); - var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, new NamingOptions()); + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(VideoDirectoryRegex))) + .Returns(true); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MetadataDirectoryRegex))) + .Returns(true); + + var subtitleResolver = new SubtitleResolver(_localizationManager, mediaEncoder.Object, fileSystem.Object, new NamingOptions()); int startIndex = 1; var streams = await subtitleResolver.GetExternalStreamsAsync(video, startIndex, directoryService.Object, false, CancellationToken.None); diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs index 0f1086f59..0e6457ce3 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs @@ -11,6 +11,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Providers.MediaInfo; using Moq; using Xunit; @@ -45,7 +46,13 @@ public class SubtitleResolverTests } })); - _subtitleResolver = new SubtitleResolver(localizationManager, mediaEncoder.Object, new NamingOptions()); + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MediaInfoResolverTests.VideoDirectoryRegex))) + .Returns(true); + fileSystem.Setup(fs => fs.DirectoryExists(It.IsRegex(MediaInfoResolverTests.MetadataDirectoryRegex))) + .Returns(true); + + _subtitleResolver = new SubtitleResolver(localizationManager, mediaEncoder.Object, fileSystem.Object, new NamingOptions()); } [Theory] diff --git a/tests/Jellyfin.Providers.Tests/Test Data/Video/My.Video.mkv b/tests/Jellyfin.Providers.Tests/Test Data/Video/My.Video.mkv deleted file mode 100644 index e69de29bb..000000000 --- a/tests/Jellyfin.Providers.Tests/Test Data/Video/My.Video.mkv +++ /dev/null |
