diff --git a/.dockerignore b/.dockerignore index fc4d8ed26..45e543525 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,10 @@ .git .dockerignore Dockerfile +Dockerfile.arm +Dockerfile.arm64 CONTRIBUTORS.md README.md +deployment/*/dist +deployment/*/pkg-dist +deployment/collect-dist/ diff --git a/.drone.yml b/.drone.yml index c6d41b555..98db4884b 100644 --- a/.drone.yml +++ b/.drone.yml @@ -9,4 +9,4 @@ steps: - name: build image: microsoft/dotnet:2-sdk commands: - - dotnet publish --configuration release --output /release + - dotnet publish --configuration release --output /release Jellyfin.Server diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..b2891188d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,131 @@ +# With more recent updates Visual Studio 2017 supports EditorConfig files out of the box +# Visual Studio Code needs an extension: https://github.com/editorconfig/editorconfig-vscode +# For emacs, vim, np++ and other editors, see here: https://github.com/editorconfig +############################### +# Core EditorConfig Options # +############################### +root = true +# All files +[*] +indent_style = space +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf +max_line_length = null + +# XML indentation +[*.{csproj,xml}] +indent_size = 2 +############################### +# .NET Coding Conventions # +############################### +[*.{cs,vb}] +# Organize usings +dotnet_sort_system_directives_first = true +# this. preferences +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_readonly_field = true:suggestion +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent +dotnet_prefer_inferred_tuple_names = true:suggestion +dotnet_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +############################### +# Naming Conventions # +############################### +# Style Definitions +dotnet_naming_style.pascal_case_style.capitalization = pascal_case +# Use PascalCase for constant fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.applicable_accessibilities = * +dotnet_naming_symbols.constant_fields.required_modifiers = const +############################### +# C# Coding Conventions # +############################### +[*.cs] +# var preferences +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_var_elsewhere = true:silent +# Expression-bodied members +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +# Null-checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion +# Expression-level preferences +csharp_prefer_braces = true:silent +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +############################### +# C# Formatting Rules # +############################### +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation preferences +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left +# Space preferences +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +# Wrapping preferences +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true +############################### +# VB Coding Conventions # +############################### +[*.vb] +# Modifier preferences +visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..4abd39cfc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a bug report +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Logs** +Please paste any log errors. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**System (please complete the following information):** + - OS: [e.g. Docker, Debian, Windows] + - Browser: [e.g. Firefox, Chrome, Safari] + - Jellyfin Version: [e.g. 10.0.1] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/enhancement-request.md b/.github/ISSUE_TEMPLATE/enhancement-request.md new file mode 100644 index 000000000..57c0d4cae --- /dev/null +++ b/.github/ISSUE_TEMPLATE/enhancement-request.md @@ -0,0 +1,20 @@ +--- +name: Enhancement request +about: Suggest an modification to an existing feature +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..a2ce07245 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,14 @@ +--- +name: Feature request +about: Suggest a new feature +title: '' +labels: feature +assignees: '' + +--- + +**Describe the feature you'd like** +A clear and concise description of what you want to happen. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..b2b3cf241 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,9 @@ +Ensure your title is short, descriptive, and in the imperative mood (Fix X, Change Y, instead of Fixed X, Changed Y). +For a good inspiration of what to write in commit messages and PRs please review https://chris.beams.io/posts/git-commit/ and our https://jellyfin.readthedocs.io/en/latest/developer-docs/contributing/ page. + +**Changes** +Describe your changes here in 1-5 sentences. + +**Issues** +Tag any issues that this PR solves here. +Fixes # diff --git a/.gitignore b/.gitignore index 9bbfd9b74..aef666272 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,3 @@ -!* - .directory ################# @@ -49,6 +47,8 @@ ProgramData-UI*/ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. +.vs/ + # User-specific files *.suo *.user @@ -204,7 +204,6 @@ $RECYCLE.BIN/ # Mac crap .DS_Store - ############# ## Python ############# @@ -234,22 +233,34 @@ pip-log.txt #Mr Developer .mr.developer.cfg -MediaBrowser.WebDashboard/dashboard-ui/.idea/ -/.vs ########## # Rider ########## .idea/ +########## +# Visual Studio Code +########## +.vscode/ + ######################### -# Debian build artifacts +# Build artifacts ######################### -debian/.debhelper/ -debian/files -debian/jellyfin.substvars -debian/jellyfin/ - +# Artifacts for debian-x64 +deployment/debian-package-x64/pkg-src/.debhelper/ +deployment/debian-package-x64/pkg-src/*.debhelper +deployment/debian-package-x64/pkg-src/debhelper-build-stamp +deployment/debian-package-x64/pkg-src/files +deployment/debian-package-x64/pkg-src/jellyfin.substvars +deployment/debian-package-x64/pkg-src/jellyfin/ # Don't ignore the debian/bin folder -!debian/bin/ +!deployment/debian-package-x64/pkg-src/bin/ + +deployment/**/dist/ +deployment/**/pkg-dist/ +deployment/**/pkg-dist-tmp/ +deployment/collect-dist/ + +jellyfin_version.ini diff --git a/.gitmodules b/.gitmodules index 31a58ecf1..7aeb94dfc 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "ThirdParty/taglib-sharp"] path = ThirdParty/taglib-sharp url = https://github.com/mono/taglib-sharp.git +[submodule "MediaBrowser.WebDashboard/jellyfin-web"] + path = MediaBrowser.WebDashboard/jellyfin-web + url = https://github.com/jellyfin/jellyfin-web.git diff --git a/BDInfo/BDInfo.csproj b/BDInfo/BDInfo.csproj index 403ecec4e..b2c752d0c 100644 --- a/BDInfo/BDInfo.csproj +++ b/BDInfo/BDInfo.csproj @@ -1,4 +1,8 @@ - + + + + + diff --git a/BDInfo/BDInfoSettings.cs b/BDInfo/BDInfoSettings.cs index 7abb67499..f4cb30016 100644 --- a/BDInfo/BDInfoSettings.cs +++ b/BDInfo/BDInfoSettings.cs @@ -1,105 +1,33 @@ - + namespace BDInfo { class BDInfoSettings { - public static bool GenerateStreamDiagnostics - { - get - { - return true; - } - } + public static bool GenerateStreamDiagnostics => true; - public static bool EnableSSIF - { - get - { - return true; - } - } + public static bool EnableSSIF => true; - public static bool AutosaveReport - { - get - { - return false; - } - } + public static bool AutosaveReport => false; - public static bool GenerateFrameDataFile - { - get - { - return false; - } - } + public static bool GenerateFrameDataFile => false; - public static bool FilterLoopingPlaylists - { - get - { - return true; - } - } + public static bool FilterLoopingPlaylists => true; - public static bool FilterShortPlaylists - { - get - { - return false; - } - } + public static bool FilterShortPlaylists => false; - public static int FilterShortPlaylistsValue - { - get - { - return 0; - } - } + public static int FilterShortPlaylistsValue => 0; - public static bool UseImagePrefix - { - get - { - return false; - } - } + public static bool UseImagePrefix => false; - public static string UseImagePrefixValue - { - get - { - return null; - } - } + public static string UseImagePrefixValue => null; /// /// Setting this to false throws an IComparer error on some discs. /// - public static bool KeepStreamOrder - { - get - { - return true; - } - } + public static bool KeepStreamOrder => true; - public static bool GenerateTextSummary - { - get - { - return false; - } - } + public static bool GenerateTextSummary => false; - public static string LastPath - { - get - { - return string.Empty; - } - } + public static string LastPath => string.Empty; } } diff --git a/BDInfo/BDROM.cs b/BDInfo/BDROM.cs index f00d9825a..4cd636023 100644 --- a/BDInfo/BDROM.cs +++ b/BDInfo/BDROM.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -22,7 +22,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Text; namespace BDInfo { @@ -72,12 +71,11 @@ namespace BDInfo public event OnPlaylistFileScanError PlaylistFileScanError; - public BDROM( - string path, IFileSystem fileSystem, ITextEncoding textEncoding) + public BDROM(string path, IFileSystem fileSystem) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } _fileSystem = fileSystem; @@ -164,17 +162,17 @@ namespace BDInfo if (DirectoryPLAYLIST != null) { FileSystemMetadata[] files = GetFiles(DirectoryPLAYLIST.FullName, ".mpls").ToArray(); - foreach (FileSystemMetadata file in files) + foreach (var file in files) { PlaylistFiles.Add( - file.Name.ToUpper(), new TSPlaylistFile(this, file, _fileSystem, textEncoding)); + file.Name.ToUpper(), new TSPlaylistFile(this, file, _fileSystem)); } } if (DirectorySTREAM != null) { FileSystemMetadata[] files = GetFiles(DirectorySTREAM.FullName, ".m2ts").ToArray(); - foreach (FileSystemMetadata file in files) + foreach (var file in files) { StreamFiles.Add( file.Name.ToUpper(), new TSStreamFile(file, _fileSystem)); @@ -184,17 +182,17 @@ namespace BDInfo if (DirectoryCLIPINF != null) { FileSystemMetadata[] files = GetFiles(DirectoryCLIPINF.FullName, ".clpi").ToArray(); - foreach (FileSystemMetadata file in files) + foreach (var file in files) { StreamClipFiles.Add( - file.Name.ToUpper(), new TSStreamClipFile(file, _fileSystem, textEncoding)); + file.Name.ToUpper(), new TSStreamClipFile(file, _fileSystem)); } } if (DirectorySSIF != null) { FileSystemMetadata[] files = GetFiles(DirectorySSIF.FullName, ".ssif").ToArray(); - foreach (FileSystemMetadata file in files) + foreach (var file in files) { InterleavedFiles.Add( file.Name.ToUpper(), new TSInterleavedFile(file)); @@ -214,8 +212,8 @@ namespace BDInfo public void Scan() { - List errorStreamClipFiles = new List(); - foreach (TSStreamClipFile streamClipFile in StreamClipFiles.Values) + var errorStreamClipFiles = new List(); + foreach (var streamClipFile in StreamClipFiles.Values) { try { @@ -235,11 +233,11 @@ namespace BDInfo break; } } - else throw ex; + else throw; } } - foreach (TSStreamFile streamFile in StreamFiles.Values) + foreach (var streamFile in StreamFiles.Values) { string ssifName = Path.GetFileNameWithoutExtension(streamFile.Name) + ".SSIF"; if (InterleavedFiles.ContainsKey(ssifName)) @@ -252,8 +250,8 @@ namespace BDInfo StreamFiles.Values.CopyTo(streamFiles, 0); Array.Sort(streamFiles, CompareStreamFiles); - List errorPlaylistFiles = new List(); - foreach (TSPlaylistFile playlistFile in PlaylistFiles.Values) + var errorPlaylistFiles = new List(); + foreach (var playlistFile in PlaylistFiles.Values) { try { @@ -273,19 +271,19 @@ namespace BDInfo break; } } - else throw ex; + else throw; } } - List errorStreamFiles = new List(); - foreach (TSStreamFile streamFile in streamFiles) + var errorStreamFiles = new List(); + foreach (var streamFile in streamFiles) { try { - List playlists = new List(); - foreach (TSPlaylistFile playlist in PlaylistFiles.Values) + var playlists = new List(); + foreach (var playlist in PlaylistFiles.Values) { - foreach (TSStreamClip streamClip in playlist.StreamClips) + foreach (var streamClip in playlist.StreamClips) { if (streamClip.Name == streamFile.Name) { @@ -310,16 +308,16 @@ namespace BDInfo break; } } - else throw ex; + else throw; } } - foreach (TSPlaylistFile playlistFile in PlaylistFiles.Values) + foreach (var playlistFile in PlaylistFiles.Values) { playlistFile.Initialize(); if (!Is50Hz) { - foreach (TSVideoStream videoStream in playlistFile.VideoStreams) + foreach (var videoStream in playlistFile.VideoStreams) { if (videoStream.FrameRate == TSFrameRate.FRAMERATE_25 || videoStream.FrameRate == TSFrameRate.FRAMERATE_50) @@ -336,7 +334,7 @@ namespace BDInfo { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } FileSystemMetadata dir = _fileSystem.GetDirectoryInfo(path); @@ -369,7 +367,7 @@ namespace BDInfo if (dir != null) { FileSystemMetadata[] children = _fileSystem.GetDirectories(dir.FullName).ToArray(); - foreach (FileSystemMetadata child in children) + foreach (var child in children) { if (string.Equals(child.Name, name, StringComparison.OrdinalIgnoreCase)) { @@ -378,7 +376,7 @@ namespace BDInfo } if (searchDepth > 0) { - foreach (FileSystemMetadata child in children) + foreach (var child in children) { GetDirectory( name, child, searchDepth - 1); @@ -395,7 +393,7 @@ namespace BDInfo //if (!ExcludeDirs.Contains(directoryInfo.Name.ToUpper())) // TODO: Keep? { FileSystemMetadata[] pathFiles = _fileSystem.GetFiles(directoryInfo.FullName).ToArray(); - foreach (FileSystemMetadata pathFile in pathFiles) + foreach (var pathFile in pathFiles) { if (pathFile.Extension.ToUpper() == ".SSIF") { @@ -405,7 +403,7 @@ namespace BDInfo } FileSystemMetadata[] pathChildren = _fileSystem.GetDirectories(directoryInfo.FullName).ToArray(); - foreach (FileSystemMetadata pathChild in pathChildren) + foreach (var pathChild in pathChildren) { size += GetDirectorySize(pathChild); } diff --git a/BDInfo/LanguageCodes.cs b/BDInfo/LanguageCodes.cs index 90d0bccc4..ab2693ffb 100644 --- a/BDInfo/LanguageCodes.cs +++ b/BDInfo/LanguageCodes.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // diff --git a/BDInfo/Properties/AssemblyInfo.cs b/BDInfo/Properties/AssemblyInfo.cs index aa44da190..788cf7366 100644 --- a/BDInfo/Properties/AssemblyInfo.cs +++ b/BDInfo/Properties/AssemblyInfo.cs @@ -1,29 +1,21 @@ -using System.Resources; using System.Reflection; -using System.Runtime.CompilerServices; +using System.Resources; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BDInfo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BDInfo")] -[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2016 CinemaSquid. Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1")] \ No newline at end of file +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] diff --git a/BDInfo/ReadMe.txt b/BDInfo/ReadMe.txt index 68326d560..e70b0b66c 100644 --- a/BDInfo/ReadMe.txt +++ b/BDInfo/ReadMe.txt @@ -1,5 +1,5 @@ -The source is taken from the BDRom folder of this project: +The source is taken from the BDRom folder of this project: http://www.cinemasquid.com/blu-ray/tools/bdinfo -BDInfoSettings was taken from the FormSettings class, and changed so that the settings all return defaults. \ No newline at end of file +BDInfoSettings was taken from the FormSettings class, and changed so that the settings all return defaults. diff --git a/BDInfo/TSCodecAC3.cs b/BDInfo/TSCodecAC3.cs index 144141c30..35d306a19 100644 --- a/BDInfo/TSCodecAC3.cs +++ b/BDInfo/TSCodecAC3.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -24,7 +24,7 @@ namespace BDInfo { public abstract class TSCodecAC3 { - private static byte[] eac3_blocks = new byte[] { 1, 2, 3, 6 }; + private static byte[] eac3_blocks = new byte[] { 1, 2, 3, 6 }; public static void Scan( TSAudioStream stream, diff --git a/BDInfo/TSCodecAVC.cs b/BDInfo/TSCodecAVC.cs index 43c6d6f85..5833d169f 100644 --- a/BDInfo/TSCodecAVC.cs +++ b/BDInfo/TSCodecAVC.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // diff --git a/BDInfo/TSCodecDTS.cs b/BDInfo/TSCodecDTS.cs index 58eb60fc5..ff94cb702 100644 --- a/BDInfo/TSCodecDTS.cs +++ b/BDInfo/TSCodecDTS.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -148,7 +148,7 @@ namespace BDInfo stream.IsVBR = true; stream.IsInitialized = true; break; - + default: stream.IsVBR = false; stream.IsInitialized = true; diff --git a/BDInfo/TSCodecDTSHD.cs b/BDInfo/TSCodecDTSHD.cs index 169a8077f..57a136d2d 100644 --- a/BDInfo/TSCodecDTSHD.cs +++ b/BDInfo/TSCodecDTSHD.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -22,9 +22,9 @@ namespace BDInfo { public abstract class TSCodecDTSHD { - private static int[] SampleRates = new int[] + private static int[] SampleRates = new int[] { 0x1F40, 0x3E80, 0x7D00, 0x0FA00, 0x1F400, 0x5622, 0x0AC44, 0x15888, 0x2B110, 0x56220, 0x2EE0, 0x5DC0, 0x0BB80, 0x17700, 0x2EE00, 0x5DC00 }; - + public static void Scan( TSAudioStream stream, TSStreamBuffer buffer, @@ -131,7 +131,7 @@ namespace BDInfo else { AssetSizes[i] = buffer.ReadBits(16) + 1; - } + } } for (int i = 0; i < nuNumAssets; i++) { @@ -189,7 +189,7 @@ namespace BDInfo } stream.SampleRate = SampleRates[nuMaxSampleRate]; stream.BitDepth = nuBitResolution; - + stream.LFE = 0; if ((nuSpkrActivityMask & 0x8) == 0x8) { @@ -211,7 +211,7 @@ namespace BDInfo // TODO if (stream.CoreStream != null) { - TSAudioStream coreStream = (TSAudioStream)stream.CoreStream; + var coreStream = (TSAudioStream)stream.CoreStream; if (coreStream.AudioMode == TSAudioMode.Extended && stream.ChannelCount == 5) { @@ -240,7 +240,7 @@ namespace BDInfo stream.IsInitialized = true; } stream.IsInitialized = (stream.BitRate > 0 ? true : false); - } + } } } } diff --git a/BDInfo/TSCodecLPCM.cs b/BDInfo/TSCodecLPCM.cs index d12674f0e..5709d8689 100644 --- a/BDInfo/TSCodecLPCM.cs +++ b/BDInfo/TSCodecLPCM.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // diff --git a/BDInfo/TSCodecMPEG2.cs b/BDInfo/TSCodecMPEG2.cs index 3413a06e9..8bcd07d02 100644 --- a/BDInfo/TSCodecMPEG2.cs +++ b/BDInfo/TSCodecMPEG2.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -33,7 +33,7 @@ namespace BDInfo int pictureParse = 0; int sequenceHeaderParse = 0; int extensionParse = 0; - int sequenceExtensionParse = 0; + int sequenceExtensionParse = 0; for (int i = 0; i < buffer.Length; i++) { @@ -189,7 +189,7 @@ namespace BDInfo #if DEBUG if (sequenceExtensionParse == 0) { - uint sequenceExtension = + uint sequenceExtension = ((parse & 0x8) >> 3); if (sequenceExtension == 0) { diff --git a/BDInfo/TSCodecMVC.cs b/BDInfo/TSCodecMVC.cs index 80fed3886..abff0c1b0 100644 --- a/BDInfo/TSCodecMVC.cs +++ b/BDInfo/TSCodecMVC.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // diff --git a/BDInfo/TSCodecTrueHD.cs b/BDInfo/TSCodecTrueHD.cs index baf4fa3df..5e81e162c 100644 --- a/BDInfo/TSCodecTrueHD.cs +++ b/BDInfo/TSCodecTrueHD.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -36,7 +36,7 @@ namespace BDInfo for (int i = 0; i < buffer.Length; i++) { sync = (sync << 8) + buffer.ReadByte(); - if (sync == 0xF8726FBA) + if (sync == 0xF8726FBA) { syncFound = true; break; @@ -63,7 +63,7 @@ namespace BDInfo int ratebits = buffer.ReadBits(4); if (ratebits != 0xF) { - stream.SampleRate = + stream.SampleRate = (((ratebits & 8) > 0 ? 44100 : 48000) << (ratebits & 7)); } int temp1 = buffer.ReadBits(8); @@ -149,9 +149,9 @@ namespace BDInfo int peak_bitrate = buffer.ReadBits(15); peak_bitrate = (peak_bitrate * stream.SampleRate) >> 4; - double peak_bitdepth = - (double)peak_bitrate / - (stream.ChannelCount + stream.LFE) / + double peak_bitdepth = + (double)peak_bitrate / + (stream.ChannelCount + stream.LFE) / stream.SampleRate; if (peak_bitdepth > 14) { @@ -164,7 +164,7 @@ namespace BDInfo #if DEBUG System.Diagnostics.Debug.WriteLine(string.Format( - "{0}\t{1}\t{2:F2}", + "{0}\t{1}\t{2:F2}", stream.PID, peak_bitrate, peak_bitdepth)); #endif /* diff --git a/BDInfo/TSCodecVC1.cs b/BDInfo/TSCodecVC1.cs index 164ef8c47..e2fbbf692 100644 --- a/BDInfo/TSCodecVC1.cs +++ b/BDInfo/TSCodecVC1.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -50,18 +50,18 @@ namespace BDInfo { if ((parse & 0x80000000) == 0) { - pictureType = + pictureType = (uint)((parse & 0x78000000) >> 13); } else { - pictureType = + pictureType = (uint)((parse & 0x3c000000) >> 12); } } else { - pictureType = + pictureType = (uint)((parse & 0xf0000000) >> 14); } diff --git a/BDInfo/TSInterleavedFile.cs b/BDInfo/TSInterleavedFile.cs index 44a16bbaa..0f35cfb2a 100644 --- a/BDInfo/TSInterleavedFile.cs +++ b/BDInfo/TSInterleavedFile.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -17,7 +17,6 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //============================================================================= -using System.IO; using MediaBrowser.Model.IO; // TODO: Do more interesting things here... diff --git a/BDInfo/TSPlaylistFile.cs b/BDInfo/TSPlaylistFile.cs index da6fd37cc..8c98d44d7 100644 --- a/BDInfo/TSPlaylistFile.cs +++ b/BDInfo/TSPlaylistFile.cs @@ -23,14 +23,12 @@ using System.Collections.Generic; using System.IO; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Text; namespace BDInfo { public class TSPlaylistFile { private readonly IFileSystem _fileSystem; - private readonly ITextEncoding _textEncoding; private FileSystemMetadata FileInfo = null; public string FileType = null; public bool IsInitialized = false; @@ -42,7 +40,7 @@ namespace BDInfo public List Chapters = new List(); - public Dictionary Streams = + public Dictionary Streams = new Dictionary(); public Dictionary PlaylistStreams = new Dictionary(); @@ -50,45 +48,41 @@ namespace BDInfo new List(); public List> AngleStreams = new List>(); - public List> AngleClips = + public List> AngleClips = new List>(); public int AngleCount = 0; - public List SortedStreams = + public List SortedStreams = new List(); - public List VideoStreams = + public List VideoStreams = new List(); - public List AudioStreams = + public List AudioStreams = new List(); - public List TextStreams = + public List TextStreams = new List(); - public List GraphicsStreams = + public List GraphicsStreams = new List(); - public TSPlaylistFile( - BDROM bdrom, - FileSystemMetadata fileInfo, IFileSystem fileSystem, ITextEncoding textEncoding) + public TSPlaylistFile(BDROM bdrom, + FileSystemMetadata fileInfo, IFileSystem fileSystem) { BDROM = bdrom; FileInfo = fileInfo; _fileSystem = fileSystem; - _textEncoding = textEncoding; Name = fileInfo.Name.ToUpper(); } - public TSPlaylistFile( - BDROM bdrom, + public TSPlaylistFile(BDROM bdrom, string name, - List clips, IFileSystem fileSystem, ITextEncoding textEncoding) + List clips, IFileSystem fileSystem) { BDROM = bdrom; Name = name; _fileSystem = fileSystem; - _textEncoding = textEncoding; IsCustom = true; - foreach (TSStreamClip clip in clips) + foreach (var clip in clips) { - TSStreamClip newClip = new TSStreamClip( + var newClip = new TSStreamClip( clip.StreamFile, clip.StreamClipFile); newClip.Name = clip.Name; @@ -124,7 +118,7 @@ namespace BDInfo get { ulong size = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { size += clip.InterleavedFileSize; } @@ -136,7 +130,7 @@ namespace BDInfo get { ulong size = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { size += clip.FileSize; } @@ -148,7 +142,7 @@ namespace BDInfo get { double length = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { if (clip.AngleIndex == 0) { @@ -164,7 +158,7 @@ namespace BDInfo get { double length = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { length += clip.Length; } @@ -177,7 +171,7 @@ namespace BDInfo get { ulong size = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { if (clip.AngleIndex == 0) { @@ -193,7 +187,7 @@ namespace BDInfo get { ulong size = 0; - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { size += clip.PacketSize; } @@ -264,7 +258,7 @@ namespace BDInfo int itemCount = ReadInt16(data, ref pos); int subitemCount = ReadInt16(data, ref pos); - List chapterClips = new List(); + var chapterClips = new List(); for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) { int itemStart = pos; @@ -311,7 +305,7 @@ namespace BDInfo if (outTime < 0) outTime &= 0x7FFFFFFF; double timeOut = (double)outTime / 45000; - TSStreamClip streamClip = new TSStreamClip( + var streamClip = new TSStreamClip( streamFile, streamClipFile); streamClip.Name = streamFileName; //TODO @@ -362,7 +356,7 @@ namespace BDInfo FileInfo.Name, angleClipFileName)); } - TSStreamClip angleClip = + var angleClip = new TSStreamClip(angleFile, angleClipFile); angleClip.AngleIndex = angle + 1; angleClip.TimeIn = streamClip.TimeIn; @@ -388,46 +382,46 @@ namespace BDInfo #if DEBUG Debug.WriteLine(string.Format( - "{0} : {1} -> V:{2} A:{3} PG:{4} IG:{5} 2A:{6} 2V:{7} PIP:{8}", - Name, streamFileName, streamCountVideo, streamCountAudio, streamCountPG, streamCountIG, + "{0} : {1} -> V:{2} A:{3} PG:{4} IG:{5} 2A:{6} 2V:{7} PIP:{8}", + Name, streamFileName, streamCountVideo, streamCountAudio, streamCountPG, streamCountIG, streamCountSecondaryAudio, streamCountSecondaryVideo, streamCountPIP)); #endif for (int i = 0; i < streamCountVideo; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; } for (int i = 0; i < streamCountAudio; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; } for (int i = 0; i < streamCountPG; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; } for (int i = 0; i < streamCountIG; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; } for (int i = 0; i < streamCountSecondaryAudio; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; pos += 2; } for (int i = 0; i < streamCountSecondaryVideo; i++) { - TSStream stream = CreatePlaylistStream(data, ref pos); + var stream = CreatePlaylistStream(data, ref pos); if (stream != null) PlaylistStreams[stream.PID] = stream; pos += 6; } /* * TODO - * + * for (int i = 0; i < streamCountPIP; i++) { TSStream stream = CreatePlaylistStream(data, ref pos); @@ -446,7 +440,7 @@ namespace BDInfo chapterIndex < chapterCount; chapterIndex++) { - int chapterType = data[pos+1]; + int chapterType = data[pos + 1]; if (chapterType == 1) { @@ -459,7 +453,7 @@ namespace BDInfo ((long)data[pos + 6] << 8) + ((long)data[pos + 7]); - TSStreamClip streamClip = chapterClips[streamFileIndex]; + var streamClip = chapterClips[streamFileIndex]; double chapterSeconds = (double)chapterTime / 45000; @@ -499,8 +493,8 @@ namespace BDInfo { LoadStreamClips(); - Dictionary> clipTimes = new Dictionary>(); - foreach (TSStreamClip clip in StreamClips) + var clipTimes = new Dictionary>(); + foreach (var clip in StreamClips) { if (clip.AngleIndex == 0) { @@ -568,7 +562,7 @@ namespace BDInfo int streamLength = data[pos++]; int streamPos = pos; - TSStreamType streamType = (TSStreamType)data[pos++]; + var streamType = (TSStreamType)data[pos++]; switch (streamType) { case TSStreamType.MVC_VIDEO: @@ -580,11 +574,11 @@ namespace BDInfo case TSStreamType.MPEG2_VIDEO: case TSStreamType.VC1_VIDEO: - TSVideoFormat videoFormat = (TSVideoFormat) + var videoFormat = (TSVideoFormat) (data[pos] >> 4); - TSFrameRate frameRate = (TSFrameRate) + var frameRate = (TSFrameRate) (data[pos] & 0xF); - TSAspectRatio aspectRatio = (TSAspectRatio) + var aspectRatio = (TSAspectRatio) (data[pos + 1] >> 4); stream = new TSVideoStream(); @@ -618,9 +612,9 @@ namespace BDInfo int audioFormat = ReadByte(data, ref pos); - TSChannelLayout channelLayout = (TSChannelLayout) + var channelLayout = (TSChannelLayout) (audioFormat >> 4); - TSSampleRate sampleRate = (TSSampleRate) + var sampleRate = (TSSampleRate) (audioFormat & 0xF); string audioLanguage = ReadString(data, 3, ref pos); @@ -713,7 +707,7 @@ namespace BDInfo { referenceClip = StreamClips[0]; } - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { if (clip.StreamClipFile.Streams.Count > referenceClip.StreamClipFile.Streams.Count) { @@ -739,12 +733,12 @@ namespace BDInfo } } - foreach (TSStream clipStream + foreach (var clipStream in referenceClip.StreamClipFile.Streams.Values) { if (!Streams.ContainsKey(clipStream.PID)) { - TSStream stream = clipStream.Clone(); + var stream = clipStream.Clone(); Streams[clipStream.PID] = stream; if (!IsCustom && !PlaylistStreams.ContainsKey(stream.PID)) @@ -780,7 +774,7 @@ namespace BDInfo referenceClip.StreamFile.Streams.ContainsKey(4114) && !Streams.ContainsKey(4114)) { - TSStream stream = referenceClip.StreamFile.Streams[4114].Clone(); + var stream = referenceClip.StreamFile.Streams[4114].Clone(); Streams[4114] = stream; if (stream.IsVideoStream) { @@ -788,12 +782,12 @@ namespace BDInfo } } - foreach (TSStream clipStream + foreach (var clipStream in referenceClip.StreamFile.Streams.Values) { if (Streams.ContainsKey(clipStream.PID)) { - TSStream stream = Streams[clipStream.PID]; + var stream = Streams[clipStream.PID]; if (stream.StreamType != clipStream.StreamType) continue; @@ -812,8 +806,8 @@ namespace BDInfo else if (stream.IsAudioStream && clipStream.IsAudioStream) { - TSAudioStream audioStream = (TSAudioStream)stream; - TSAudioStream clipAudioStream = (TSAudioStream)clipStream; + var audioStream = (TSAudioStream)stream; + var clipAudioStream = (TSAudioStream)clipStream; if (clipAudioStream.ChannelCount > audioStream.ChannelCount) { @@ -864,7 +858,7 @@ namespace BDInfo SortedStreams.Add(stream); for (int i = 0; i < AngleCount; i++) { - TSStream angleStream = stream.Clone(); + var angleStream = stream.Clone(); angleStream.AngleIndex = i + 1; AngleStreams[i][angleStream.PID] = angleStream; SortedStreams.Add(angleStream); @@ -901,7 +895,7 @@ namespace BDInfo public void ClearBitrates() { - foreach (TSStreamClip clip in StreamClips) + foreach (var clip in StreamClips) { clip.PayloadBytes = 0; clip.PacketCount = 0; @@ -909,7 +903,7 @@ namespace BDInfo if (clip.StreamFile != null) { - foreach (TSStream stream in clip.StreamFile.Streams.Values) + foreach (var stream in clip.StreamFile.Streams.Values) { stream.PayloadBytes = 0; stream.PacketCount = 0; @@ -924,7 +918,7 @@ namespace BDInfo } } - foreach (TSStream stream in SortedStreams) + foreach (var stream in SortedStreams) { stream.PayloadBytes = 0; stream.PacketCount = 0; @@ -955,7 +949,7 @@ namespace BDInfo } public int CompareVideoStreams( - TSVideoStream x, + TSVideoStream x, TSVideoStream y) { if (x == null && y == null) @@ -996,7 +990,7 @@ namespace BDInfo } public int CompareAudioStreams( - TSAudioStream x, + TSAudioStream x, TSAudioStream y) { if (x == y) @@ -1246,8 +1240,7 @@ namespace BDInfo int count, ref int pos) { - string val = - _textEncoding.GetASCIIEncoding().GetString(data, pos, count); + string val = Encoding.ASCII.GetString(data, pos, count); pos += count; diff --git a/BDInfo/TSStream.cs b/BDInfo/TSStream.cs index 5afb81c5e..3c30a8597 100644 --- a/BDInfo/TSStream.cs +++ b/BDInfo/TSStream.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -109,7 +109,7 @@ namespace BDInfo public TSDescriptor Clone() { - TSDescriptor descriptor = + var descriptor = new TSDescriptor(Name, (byte)Value.Length); Value.CopyTo(descriptor.Value, 0); return descriptor; @@ -142,26 +142,17 @@ namespace BDInfo public double PacketSeconds = 0; public int AngleIndex = 0; - public ulong PacketSize - { - get - { - return PacketCount * 192; - } - } + public ulong PacketSize => PacketCount * 192; private string _LanguageCode; public string LanguageCode { - get - { - return _LanguageCode; - } - set + get => _LanguageCode; + set { _LanguageCode = value; LanguageName = LanguageCodes.GetName(value); - } + } } public bool IsVideoStream @@ -398,16 +389,10 @@ namespace BDInfo } } - public virtual string Description - { - get - { - return ""; - } - } + public virtual string Description => ""; public abstract TSStream Clone(); - + protected void CopyTo(TSStream stream) { stream.PID = PID; @@ -419,7 +404,7 @@ namespace BDInfo if (Descriptors != null) { stream.Descriptors = new List(); - foreach (TSDescriptor descriptor in Descriptors) + foreach (var descriptor in Descriptors) { stream.Descriptors.Add(descriptor.Clone()); } @@ -435,7 +420,7 @@ namespace BDInfo public int Width; public int Height; - public bool IsInterlaced; + public bool IsInterlaced; public int FrameRateEnumerator; public int FrameRateDenominator; public TSAspectRatio AspectRatio; @@ -444,10 +429,7 @@ namespace BDInfo private TSVideoFormat _VideoFormat; public TSVideoFormat VideoFormat { - get - { - return _VideoFormat; - } + get => _VideoFormat; set { _VideoFormat = value; @@ -488,10 +470,7 @@ namespace BDInfo private TSFrameRate _FrameRate; public TSFrameRate FrameRate { - get - { - return _FrameRate; - } + get => _FrameRate; set { _FrameRate = value; @@ -574,14 +553,14 @@ namespace BDInfo public override TSStream Clone() { - TSVideoStream stream = new TSVideoStream(); + var stream = new TSVideoStream(); CopyTo(stream); stream.VideoFormat = _VideoFormat; stream.FrameRate = _FrameRate; stream.Width = Width; stream.Height = Height; - stream.IsInterlaced = IsInterlaced; + stream.IsInterlaced = IsInterlaced; stream.FrameRateEnumerator = FrameRateEnumerator; stream.FrameRateDenominator = FrameRateDenominator; stream.AspectRatio = AspectRatio; @@ -748,7 +727,7 @@ namespace BDInfo public override TSStream Clone() { - TSAudioStream stream = new TSAudioStream(); + var stream = new TSAudioStream(); CopyTo(stream); stream.SampleRate = SampleRate; @@ -777,7 +756,7 @@ namespace BDInfo public override TSStream Clone() { - TSGraphicsStream stream = new TSGraphicsStream(); + var stream = new TSGraphicsStream(); CopyTo(stream); return stream; } @@ -793,7 +772,7 @@ namespace BDInfo public override TSStream Clone() { - TSTextStream stream = new TSTextStream(); + var stream = new TSTextStream(); CopyTo(stream); return stream; } diff --git a/BDInfo/TSStreamBuffer.cs b/BDInfo/TSStreamBuffer.cs index 2f9094876..30bd1a3f4 100644 --- a/BDInfo/TSStreamBuffer.cs +++ b/BDInfo/TSStreamBuffer.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -37,21 +37,9 @@ namespace BDInfo Stream = new MemoryStream(Buffer); } - public long Length - { - get - { - return (long)BufferLength; - } - } + public long Length => (long)BufferLength; - public long Position - { - get - { - return Stream.Position; - } - } + public long Position => Stream.Position; public void Add( byte[] buffer, @@ -123,7 +111,7 @@ namespace BDInfo data += (Stream.ReadByte() << shift); shift -= 8; } - BitVector32 vector = new BitVector32(data); + var vector = new BitVector32(data); int value = 0; for (int i = SkipBits; i < SkipBits + bits; i++) diff --git a/BDInfo/TSStreamClip.cs b/BDInfo/TSStreamClip.cs index d7592a71a..295eeb6b1 100644 --- a/BDInfo/TSStreamClip.cs +++ b/BDInfo/TSStreamClip.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -74,13 +74,7 @@ namespace BDInfo } } - public ulong PacketSize - { - get - { - return PacketCount * 192; - } - } + public ulong PacketSize => PacketCount * 192; public ulong PacketBitRate { @@ -96,11 +90,11 @@ namespace BDInfo public bool IsCompatible(TSStreamClip clip) { - foreach (TSStream stream1 in StreamFile.Streams.Values) + foreach (var stream1 in StreamFile.Streams.Values) { if (clip.StreamFile.Streams.ContainsKey(stream1.PID)) { - TSStream stream2 = clip.StreamFile.Streams[stream1.PID]; + var stream2 = clip.StreamFile.Streams[stream1.PID]; if (stream1.StreamType != stream2.StreamType) { return false; diff --git a/BDInfo/TSStreamClipFile.cs b/BDInfo/TSStreamClipFile.cs index f2accb88d..3396f4c71 100644 --- a/BDInfo/TSStreamClipFile.cs +++ b/BDInfo/TSStreamClipFile.cs @@ -23,28 +23,24 @@ using System.Collections.Generic; using System.IO; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Text; namespace BDInfo { public class TSStreamClipFile { private readonly IFileSystem _fileSystem; - private readonly ITextEncoding _textEncoding; public FileSystemMetadata FileInfo = null; public string FileType = null; public bool IsValid = false; public string Name = null; public Dictionary Streams = - new Dictionary(); + new Dictionary(); - public TSStreamClipFile( - FileSystemMetadata fileInfo, IFileSystem fileSystem, ITextEncoding textEncoding) + public TSStreamClipFile(FileSystemMetadata fileInfo, IFileSystem fileSystem) { FileInfo = fileInfo; _fileSystem = fileSystem; - _textEncoding = textEncoding; Name = fileInfo.Name.ToUpper(); } @@ -69,8 +65,8 @@ namespace BDInfo byte[] fileType = new byte[8]; Array.Copy(data, 0, fileType, 0, fileType.Length); - - FileType = _textEncoding.GetASCIIEncoding().GetString(fileType, 0, fileType.Length); + + FileType = Encoding.ASCII.GetString(fileType, 0, fileType.Length); if (FileType != "HDMV0100" && FileType != "HDMV0200") { @@ -78,7 +74,7 @@ namespace BDInfo "Clip info file {0} has an unknown file type {1}.", FileInfo.Name, FileType)); } -#if DEBUG +#if DEBUG Debug.WriteLine(string.Format( "\tFileType: {0}", FileType)); #endif @@ -110,12 +106,12 @@ namespace BDInfo TSStream stream = null; ushort PID = (ushort) - ((clipData[streamOffset] << 8) + + ((clipData[streamOffset] << 8) + clipData[streamOffset + 1]); - + streamOffset += 2; - TSStreamType streamType = (TSStreamType) + var streamType = (TSStreamType) clipData[streamOffset + 1]; switch (streamType) { @@ -127,18 +123,18 @@ namespace BDInfo case TSStreamType.MPEG1_VIDEO: case TSStreamType.MPEG2_VIDEO: case TSStreamType.VC1_VIDEO: - { - TSVideoFormat videoFormat = (TSVideoFormat) - (clipData[streamOffset + 2] >> 4); - TSFrameRate frameRate = (TSFrameRate) - (clipData[streamOffset + 2] & 0xF); - TSAspectRatio aspectRatio = (TSAspectRatio) - (clipData[streamOffset + 3] >> 4); + { + var videoFormat = (TSVideoFormat) + (clipData[streamOffset + 2] >> 4); + var frameRate = (TSFrameRate) + (clipData[streamOffset + 2] & 0xF); + var aspectRatio = (TSAspectRatio) + (clipData[streamOffset + 3] >> 4); - stream = new TSVideoStream(); - ((TSVideoStream)stream).VideoFormat = videoFormat; - ((TSVideoStream)stream).AspectRatio = aspectRatio; - ((TSVideoStream)stream).FrameRate = frameRate; + stream = new TSVideoStream(); + ((TSVideoStream)stream).VideoFormat = videoFormat; + ((TSVideoStream)stream).AspectRatio = aspectRatio; + ((TSVideoStream)stream).FrameRate = frameRate; #if DEBUG Debug.WriteLine(string.Format( "\t{0} {1} {2} {3} {4}", @@ -148,8 +144,8 @@ namespace BDInfo frameRate, aspectRatio)); #endif - } - break; + } + break; case TSStreamType.AC3_AUDIO: case TSStreamType.AC3_PLUS_AUDIO: @@ -162,23 +158,22 @@ namespace BDInfo case TSStreamType.LPCM_AUDIO: case TSStreamType.MPEG1_AUDIO: case TSStreamType.MPEG2_AUDIO: - { - byte[] languageBytes = new byte[3]; - Array.Copy(clipData, streamOffset + 3, - languageBytes, 0, languageBytes.Length); - string languageCode = - _textEncoding.GetASCIIEncoding().GetString(languageBytes, 0, languageBytes.Length); + { + byte[] languageBytes = new byte[3]; + Array.Copy(clipData, streamOffset + 3, + languageBytes, 0, languageBytes.Length); + string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length); - TSChannelLayout channelLayout = (TSChannelLayout) - (clipData[streamOffset + 2] >> 4); - TSSampleRate sampleRate = (TSSampleRate) - (clipData[streamOffset + 2] & 0xF); + var channelLayout = (TSChannelLayout) + (clipData[streamOffset + 2] >> 4); + var sampleRate = (TSSampleRate) + (clipData[streamOffset + 2] & 0xF); - stream = new TSAudioStream(); - ((TSAudioStream)stream).LanguageCode = languageCode; - ((TSAudioStream)stream).ChannelLayout = channelLayout; - ((TSAudioStream)stream).SampleRate = TSAudioStream.ConvertSampleRate(sampleRate); - ((TSAudioStream)stream).LanguageCode = languageCode; + stream = new TSAudioStream(); + ((TSAudioStream)stream).LanguageCode = languageCode; + ((TSAudioStream)stream).ChannelLayout = channelLayout; + ((TSAudioStream)stream).SampleRate = TSAudioStream.ConvertSampleRate(sampleRate); + ((TSAudioStream)stream).LanguageCode = languageCode; #if DEBUG Debug.WriteLine(string.Format( "\t{0} {1} {2} {3} {4}", @@ -188,20 +183,19 @@ namespace BDInfo channelLayout, sampleRate)); #endif - } - break; + } + break; case TSStreamType.INTERACTIVE_GRAPHICS: case TSStreamType.PRESENTATION_GRAPHICS: - { - byte[] languageBytes = new byte[3]; - Array.Copy(clipData, streamOffset + 2, - languageBytes, 0, languageBytes.Length); - string languageCode = - _textEncoding.GetASCIIEncoding().GetString(languageBytes, 0, languageBytes.Length); + { + byte[] languageBytes = new byte[3]; + Array.Copy(clipData, streamOffset + 2, + languageBytes, 0, languageBytes.Length); + string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length); stream = new TSGraphicsStream(); - stream.LanguageCode = languageCode; + stream.LanguageCode = languageCode; #if DEBUG Debug.WriteLine(string.Format( "\t{0} {1} {2}", @@ -209,16 +203,15 @@ namespace BDInfo streamType, languageCode)); #endif - } - break; + } + break; case TSStreamType.SUBTITLE: - { - byte[] languageBytes = new byte[3]; - Array.Copy(clipData, streamOffset + 3, - languageBytes, 0, languageBytes.Length); - string languageCode = - _textEncoding.GetASCIIEncoding().GetString(languageBytes, 0, languageBytes.Length); + { + byte[] languageBytes = new byte[3]; + Array.Copy(clipData, streamOffset + 3, + languageBytes, 0, languageBytes.Length); + string languageCode = Encoding.ASCII.GetString(languageBytes, 0, languageBytes.Length); #if DEBUG Debug.WriteLine(string.Format( "\t{0} {1} {2}", @@ -227,9 +220,9 @@ namespace BDInfo languageCode)); #endif stream = new TSTextStream(); - stream.LanguageCode = languageCode; - } - break; + stream.LanguageCode = languageCode; + } + break; } if (stream != null) @@ -240,7 +233,7 @@ namespace BDInfo } streamOffset += clipData[streamOffset] + 1; - } + } IsValid = true; } finally diff --git a/BDInfo/TSStreamFile.cs b/BDInfo/TSStreamFile.cs index cfd402434..ecf6609e2 100644 --- a/BDInfo/TSStreamFile.cs +++ b/BDInfo/TSStreamFile.cs @@ -1,4 +1,4 @@ -//============================================================================ +//============================================================================ // BDInfo - Blu-ray Video and Audio Analysis Tool // Copyright © 2010 Cinema Squid // @@ -283,7 +283,7 @@ namespace BDInfo bool isAVC = false; bool isMVC = false; - foreach (TSStream finishedStream in Streams.Values) + foreach (var finishedStream in Streams.Values) { if (!finishedStream.IsInitialized) { @@ -327,10 +327,10 @@ namespace BDInfo UpdateStreamBitrate(PID, PTSPID, PTS, PTSDiff); } - foreach (TSPlaylistFile playlist in Playlists) + foreach (var playlist in Playlists) { double packetSeconds = 0; - foreach (TSStreamClip clip in playlist.StreamClips) + foreach (var clip in playlist.StreamClips) { if (clip.AngleIndex == 0) { @@ -339,7 +339,7 @@ namespace BDInfo } if (packetSeconds > 0) { - foreach (TSStream playlistStream in playlist.SortedStreams) + foreach (var playlistStream in playlist.SortedStreams) { if (playlistStream.IsVBR) { @@ -366,14 +366,14 @@ namespace BDInfo { if (Playlists == null) return; - TSStreamState streamState = StreamStates[PID]; + var streamState = StreamStates[PID]; double streamTime = (double)PTS / 90000; double streamInterval = (double)PTSDiff / 90000; double streamOffset = streamTime + streamInterval; - foreach (TSPlaylistFile playlist in Playlists) + foreach (var playlist in Playlists) { - foreach (TSStreamClip clip in playlist.StreamClips) + foreach (var clip in playlist.StreamClips) { if (clip.Name != this.Name) continue; @@ -390,15 +390,15 @@ namespace BDInfo clip.PacketSeconds = streamOffset - clip.TimeIn; } - Dictionary playlistStreams = playlist.Streams; - if (clip.AngleIndex > 0 && + var playlistStreams = playlist.Streams; + if (clip.AngleIndex > 0 && clip.AngleIndex < playlist.AngleStreams.Count + 1) { playlistStreams = playlist.AngleStreams[clip.AngleIndex - 1]; } if (playlistStreams.ContainsKey(PID)) { - TSStream stream = playlistStreams[PID]; + var stream = playlistStreams[PID]; stream.PayloadBytes += streamState.WindowBytes; stream.PacketCount += streamState.WindowPackets; @@ -425,13 +425,13 @@ namespace BDInfo if (Streams.ContainsKey(PID)) { - TSStream stream = Streams[PID]; + var stream = Streams[PID]; stream.PayloadBytes += streamState.WindowBytes; stream.PacketCount += streamState.WindowPackets; - + if (stream.IsVideoStream) { - TSStreamDiagnostics diag = new TSStreamDiagnostics(); + var diag = new TSStreamDiagnostics(); diag.Marker = (double)PTS / 90000; diag.Interval = (double)PTSDiff / 90000; diag.Bytes = streamState.WindowBytes; @@ -457,7 +457,7 @@ namespace BDInfo int dataSize = 16384; Stream fileStream = null; try - { + { string fileName; if (BDInfoSettings.EnableSSIF && InterleavedFile != null) @@ -482,13 +482,13 @@ namespace BDInfo StreamStates.Clear(); StreamDiagnostics.Clear(); - TSPacketParser parser = + var parser = new TSPacketParser(); - + long fileLength = (uint)fileStream.Length; byte[] buffer = new byte[dataSize]; int bufferLength = 0; - while ((bufferLength = + while ((bufferLength = fileStream.Read(buffer, 0, buffer.Length)) > 0) { int offset = 0; @@ -536,80 +536,80 @@ namespace BDInfo switch (parser.HeaderParse) { case 2: - { - parser.TransportErrorIndicator = - (byte)((buffer[i] >> 7) & 0x1); - parser.PayloadUnitStartIndicator = - (byte)((buffer[i] >> 6) & 0x1); - parser.TransportPriority = - (byte)((buffer[i] >> 5) & 0x1); - parser.PID = - (ushort)((buffer[i] & 0x1f) << 8); - } - break; + { + parser.TransportErrorIndicator = + (byte)((buffer[i] >> 7) & 0x1); + parser.PayloadUnitStartIndicator = + (byte)((buffer[i] >> 6) & 0x1); + parser.TransportPriority = + (byte)((buffer[i] >> 5) & 0x1); + parser.PID = + (ushort)((buffer[i] & 0x1f) << 8); + } + break; case 1: - { - parser.PID |= (ushort)buffer[i]; - if (Streams.ContainsKey(parser.PID)) { - parser.Stream = Streams[parser.PID]; + parser.PID |= (ushort)buffer[i]; + if (Streams.ContainsKey(parser.PID)) + { + parser.Stream = Streams[parser.PID]; + } + else + { + parser.Stream = null; + } + if (!StreamStates.ContainsKey(parser.PID)) + { + StreamStates[parser.PID] = new TSStreamState(); + } + parser.StreamState = StreamStates[parser.PID]; + parser.StreamState.TotalPackets++; + parser.StreamState.WindowPackets++; + parser.TotalPackets++; } - else - { - parser.Stream = null; - } - if (!StreamStates.ContainsKey(parser.PID)) - { - StreamStates[parser.PID] = new TSStreamState(); - } - parser.StreamState = StreamStates[parser.PID]; - parser.StreamState.TotalPackets++; - parser.StreamState.WindowPackets++; - parser.TotalPackets++; - } - break; + break; case 0: - { - parser.TransportScramblingControl = - (byte)((buffer[i] >> 6) & 0x3); - parser.AdaptionFieldControl = - (byte)((buffer[i] >> 4) & 0x3); - - if ((parser.AdaptionFieldControl & 0x2) == 0x2) { - parser.AdaptionFieldState = true; - } - if (parser.PayloadUnitStartIndicator == 1) - { - if (parser.PID == 0) - { - parser.PATSectionStart = true; - } - else if (parser.PID == parser.PMTPID) - { - parser.PMTSectionStart = true; - } - else if (parser.StreamState != null && - parser.StreamState.TransferState) - { - parser.StreamState.TransferState = false; - parser.StreamState.TransferCount++; + parser.TransportScramblingControl = + (byte)((buffer[i] >> 6) & 0x3); + parser.AdaptionFieldControl = + (byte)((buffer[i] >> 4) & 0x3); - bool isFinished = ScanStream( - parser.Stream, - parser.StreamState, - parser.StreamState.StreamBuffer); - - if (!isFullScan && isFinished) + if ((parser.AdaptionFieldControl & 0x2) == 0x2) + { + parser.AdaptionFieldState = true; + } + if (parser.PayloadUnitStartIndicator == 1) + { + if (parser.PID == 0) { - return; + parser.PATSectionStart = true; + } + else if (parser.PID == parser.PMTPID) + { + parser.PMTSectionStart = true; + } + else if (parser.StreamState != null && + parser.StreamState.TransferState) + { + parser.StreamState.TransferState = false; + parser.StreamState.TransferCount++; + + bool isFinished = ScanStream( + parser.Stream, + parser.StreamState, + parser.StreamState.StreamBuffer); + + if (!isFullScan && isFinished) + { + return; + } } } } - } - break; + break; } } else if (parser.AdaptionFieldState) @@ -670,7 +670,8 @@ namespace BDInfo parser.PAT[parser.PATOffset++] = buffer[i++]; parser.PATSectionLength--; parser.PacketLength--; - } --i; + } + --i; if (parser.PATSectionLength == 0) { @@ -680,10 +681,10 @@ namespace BDInfo for (int k = 0; k < (parser.PATOffset - 4); k += 4) { uint programNumber = (uint) - ((parser.PAT[k] << 8) + + ((parser.PAT[k] << 8) + parser.PAT[k + 1]); - ushort programPID = (ushort) + ushort programPID = (ushort) (((parser.PAT[k + 2] & 0x1F) << 8) + parser.PAT[k + 3]); @@ -801,7 +802,8 @@ namespace BDInfo PMT[parser.PMTOffset++] = buffer[i++]; --parser.PMTSectionLength; --parser.PacketLength; - } --i; + } + --i; if (parser.PMTSectionLength == 0) { @@ -837,7 +839,7 @@ namespace BDInfo if (!Streams.ContainsKey(streamPID)) { - List streamDescriptors = + var streamDescriptors = new List(); /* @@ -985,7 +987,7 @@ namespace BDInfo parser.PMTProgramDescriptorLength = buffer[i]; parser.PMTProgramDescriptors.Add( new TSDescriptor( - parser.PMTProgramDescriptor, + parser.PMTProgramDescriptor, parser.PMTProgramDescriptorLength)); break; } @@ -994,11 +996,11 @@ namespace BDInfo { --parser.PMTProgramDescriptorLength; - TSDescriptor descriptor = parser.PMTProgramDescriptors[ + var descriptor = parser.PMTProgramDescriptors[ parser.PMTProgramDescriptors.Count - 1]; int valueIndex = - descriptor.Value.Length - + descriptor.Value.Length - parser.PMTProgramDescriptorLength - 1; descriptor.Value[valueIndex] = buffer[i]; @@ -1020,19 +1022,19 @@ namespace BDInfo parser.SyncState = false; } } - else if (parser.Stream != null && - parser.StreamState != null && + else if (parser.Stream != null && + parser.StreamState != null && parser.TransportScramblingControl == 0) { - TSStream stream = parser.Stream; - TSStreamState streamState = parser.StreamState; + var stream = parser.Stream; + var streamState = parser.StreamState; streamState.Parse = (streamState.Parse << 8) + buffer[i]; if (streamState.TransferState) { - if ((bufferLength - i) >= streamState.PacketLength && + if ((bufferLength - i) >= streamState.PacketLength && streamState.PacketLength > 0) { offset = streamState.PacketLength; @@ -1085,7 +1087,7 @@ namespace BDInfo --parser.PacketLength; bool headerFound = false; - if (stream.IsVideoStream && + if (stream.IsVideoStream && streamState.Parse == 0x000001FD) { headerFound = true; @@ -1170,18 +1172,18 @@ namespace BDInfo (byte)(streamState.Parse & 0xFF); #endif break; - + case 1: - streamState.PESHeaderFlags = + streamState.PESHeaderFlags = (byte)(streamState.Parse & 0xFF); #if DEBUG streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 0: - streamState.PESHeaderLength = + streamState.PESHeaderLength = (byte)(streamState.Parse & 0xFF); #if DEBUG streamState.PESHeader[streamState.PESHeaderIndex++] = @@ -1211,48 +1213,48 @@ namespace BDInfo switch (streamState.PTSParse) { case 4: - streamState.PTSTemp = + streamState.PTSTemp = ((streamState.Parse & 0xE) << 29); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif break; - + case 3: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFF) << 22); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 2: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFE) << 14); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 1: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFF) << 7); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 0: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFE) >> 1); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); -#endif +#endif streamState.PTS = streamState.PTSTemp; if (streamState.PTS > streamState.PTSLast) @@ -1260,13 +1262,13 @@ namespace BDInfo if (streamState.PTSLast > 0) { streamState.PTSTransfer = (streamState.PTS - streamState.PTSLast); - } + } streamState.PTSLast = streamState.PTS; } streamState.PTSDiff = streamState.PTS - streamState.DTSPrev; - if (streamState.PTSCount > 0 && + if (streamState.PTSCount > 0 && stream.IsVideoStream) { UpdateStreamBitrates(stream.PID, streamState.PTS, streamState.PTSDiff); @@ -1280,7 +1282,7 @@ namespace BDInfo } Length = (double)(parser.PTSLast - parser.PTSFirst) / 90000; } - + streamState.DTSPrev = streamState.PTS; streamState.PTSCount++; if (streamState.PESHeaderLength == 0) @@ -1299,46 +1301,46 @@ namespace BDInfo switch (streamState.DTSParse) { case 9: - streamState.PTSTemp = + streamState.PTSTemp = ((streamState.Parse & 0xE) << 29); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 8: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFF) << 22); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 7: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFE) << 14); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif break; - + case 6: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFF) << 7); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 5: - streamState.PTSTemp |= + streamState.PTSTemp |= ((streamState.Parse & 0xFE) >> 1); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif streamState.PTS = streamState.PTSTemp; @@ -1347,48 +1349,48 @@ namespace BDInfo streamState.PTSLast = streamState.PTS; } break; - + case 4: - streamState.DTSTemp = + streamState.DTSTemp = ((streamState.Parse & 0xE) << 29); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif break; - + case 3: - streamState.DTSTemp |= + streamState.DTSTemp |= ((streamState.Parse & 0xFF) << 22); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif break; - + case 2: - streamState.DTSTemp |= + streamState.DTSTemp |= ((streamState.Parse & 0xFE) << 14); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif break; - + case 1: - streamState.DTSTemp |= + streamState.DTSTemp |= ((streamState.Parse & 0xFF) << 7); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xFF); #endif break; - + case 0: - streamState.DTSTemp |= + streamState.DTSTemp |= ((streamState.Parse & 0xFE) >> 1); #if DEBUG - streamState.PESHeader[streamState.PESHeaderIndex++] = + streamState.PESHeader[streamState.PESHeaderIndex++] = (byte)(streamState.Parse & 0xff); #endif streamState.PTSDiff = streamState.DTSTemp - streamState.DTSPrev; @@ -1459,7 +1461,7 @@ namespace BDInfo ulong PTSLast = 0; ulong PTSDiff = 0; - foreach (TSStream stream in Streams.Values) + foreach (var stream in Streams.Values) { if (!stream.IsVideoStream) continue; @@ -1482,8 +1484,8 @@ namespace BDInfo } private TSStream CreateStream( - ushort streamPID, - byte streamType, + ushort streamPID, + byte streamType, List streamDescriptors) { TSStream stream = null; @@ -1495,10 +1497,10 @@ namespace BDInfo case TSStreamType.MPEG1_VIDEO: case TSStreamType.MPEG2_VIDEO: case TSStreamType.VC1_VIDEO: - { - stream = new TSVideoStream(); - } - break; + { + stream = new TSVideoStream(); + } + break; case TSStreamType.AC3_AUDIO: case TSStreamType.AC3_PLUS_AUDIO: @@ -1511,23 +1513,23 @@ namespace BDInfo case TSStreamType.LPCM_AUDIO: case TSStreamType.MPEG1_AUDIO: case TSStreamType.MPEG2_AUDIO: - { - stream = new TSAudioStream(); - } - break; + { + stream = new TSAudioStream(); + } + break; case TSStreamType.INTERACTIVE_GRAPHICS: case TSStreamType.PRESENTATION_GRAPHICS: - { - stream = new TSGraphicsStream(); - } - break; + { + stream = new TSGraphicsStream(); + } + break; case TSStreamType.SUBTITLE: - { - stream = new TSTextStream(); - } - break; + { + stream = new TSTextStream(); + } + break; default: break; @@ -1548,6 +1550,6 @@ namespace BDInfo } return stream; - } + } } } diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6517b63cd..8ae6c81a8 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -10,7 +10,11 @@ - [Bond_009](https://github.com/Bond-009) - [AnthonyLavado](https://github.com/anthonylavado) - [sparky8251](https://github.com/sparky8251) - - [LeoVerto](https://github.com/LeoVerto] + - [LeoVerto](https://github.com/LeoVerto) + - [grafixeyehero](https://github.com/grafixeyehero) + - [cvium](https://github.com/cvium) + - [wtayl0r](https://github.com/wtayl0r) + - [TtheCreator](https://github.com/Tthecreator) # Emby Contributors diff --git a/Dockerfile b/Dockerfile index 47414ad12..b014afcd2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,24 +1,37 @@ ARG DOTNET_VERSION=2 + +# Download ffmpeg first to allow quicker rebuild of other layers +FROM alpine as ffmpeg +ARG FFMPEG_URL=https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz +RUN wget ${FFMPEG_URL} -O - | tar Jxf - \ + && mkdir ffmpeg-bin \ + && mv ffmpeg*/ffmpeg ffmpeg-bin \ + && mv ffmpeg*/ffprobe ffmpeg-bin + + FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder WORKDIR /repo COPY . . RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \ && dotnet clean \ - && dotnet publish --configuration release --output /jellyfin + && dotnet publish \ + --configuration release \ + --output /jellyfin \ + Jellyfin.Server + FROM microsoft/dotnet:${DOTNET_VERSION}-runtime COPY --from=builder /jellyfin /jellyfin +COPY --from=ffmpeg /ffmpeg-bin/* /usr/bin/ EXPOSE 8096 - VOLUME /config /media -ARG FFMPEG_URL=https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz -RUN apt update \ - && apt install -y xz-utils \ - && curl ${FFMPEG_URL} | tar Jxf - -C /usr/bin --wildcards --strip-components=1 ffmpeg*/ffmpeg ffmpeg*/ffprobe \ - && apt remove -y xz-utils - -ENTRYPOINT if [ -n "$PUID$PGUID" ]; \ - then echo "PUID/PGID are deprecated. Use Docker user param." >&2; exit 1; \ - else dotnet /jellyfin/jellyfin.dll -programdata /config; fi +# libfontconfig1 is required for Skia +RUN apt-get update \ + && apt-get install --no-install-recommends --no-install-suggests -y \ + libfontconfig1 \ + && apt-get clean autoclean \ + && apt-get autoremove \ + && rm -rf /var/lib/{apt,dpkg,cache,log} +ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config diff --git a/Dockerfile.aarch64 b/Dockerfile.aarch64 deleted file mode 100644 index da4acc841..000000000 --- a/Dockerfile.aarch64 +++ /dev/null @@ -1,17 +0,0 @@ -ARG DOTNET_VERSION=3.0 - -FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder -WORKDIR /repo -COPY . . -RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \ - && find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \; \ - && dotnet clean \ - && dotnet publish --configuration release --output /jellyfin - -FROM microsoft/dotnet:${DOTNET_VERSION}-runtime -COPY --from=builder /jellyfin /jellyfin -EXPOSE 8096 -RUN apt update \ - && apt install -y ffmpeg -VOLUME /config /media -ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config diff --git a/Dockerfile.arm b/Dockerfile.arm new file mode 100644 index 000000000..239fdd1c1 --- /dev/null +++ b/Dockerfile.arm @@ -0,0 +1,24 @@ +ARG DOTNET_VERSION=3.0 + + +FROM microsoft/dotnet:${DOTNET_VERSION}-sdk-stretch-arm32v7 as builder +WORKDIR /repo +COPY . . +#TODO Remove or update the sed line when we update dotnet version. +RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \ + && find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \; \ + && dotnet clean -maxcpucount:1 \ + && dotnet publish \ + -maxcpucount:1 \ + --configuration release \ + --output /jellyfin \ + Jellyfin.Server + + +FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm32v7 +COPY --from=builder /jellyfin /jellyfin +EXPOSE 8096 +RUN apt-get update \ + && apt-get install -y ffmpeg +VOLUME /config /media +ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 new file mode 100644 index 000000000..6d7aa2118 --- /dev/null +++ b/Dockerfile.arm64 @@ -0,0 +1,33 @@ +# Requires binfm_misc registration for aarch64 +# https://github.com/multiarch/qemu-user-static#binfmt_misc-register +ARG DOTNET_VERSION=3.0 + + +FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu +FROM alpine as qemu_extract +COPY --from=qemu /usr/bin qemu_user_static.tgz +RUN tar -xzvf qemu_user_static.tgz + + +FROM microsoft/dotnet:${DOTNET_VERSION}-sdk-stretch-arm64v8 as builder +COPY --from=qemu_extract qemu-* /usr/bin +WORKDIR /repo +COPY . . +#TODO Remove or update the sed line when we update dotnet version. +RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \ + && find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \; \ + && dotnet clean \ + && dotnet publish \ + --configuration release \ + --output /jellyfin \ + Jellyfin.Server + + +FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm64v8 +COPY --from=qemu_extract qemu-* /usr/bin +COPY --from=builder /jellyfin /jellyfin +EXPOSE 8096 +RUN apt-get update \ + && apt-get install -y ffmpeg +VOLUME /config /media +ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config diff --git a/DvdLib/BigEndianBinaryReader.cs b/DvdLib/BigEndianBinaryReader.cs index 56d9db825..b3b2eabd5 100644 --- a/DvdLib/BigEndianBinaryReader.cs +++ b/DvdLib/BigEndianBinaryReader.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System; using System.IO; namespace DvdLib diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj index 403ecec4e..b2c752d0c 100644 --- a/DvdLib/DvdLib.csproj +++ b/DvdLib/DvdLib.csproj @@ -1,4 +1,8 @@ - + + + + + diff --git a/DvdLib/Ifo/AudioAttributes.cs b/DvdLib/Ifo/AudioAttributes.cs index 5b3b9fd9a..b76f9fc05 100644 --- a/DvdLib/Ifo/AudioAttributes.cs +++ b/DvdLib/Ifo/AudioAttributes.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace DvdLib.Ifo { public enum AudioCodec diff --git a/DvdLib/Ifo/Cell.cs b/DvdLib/Ifo/Cell.cs index d0f442e36..268ab897e 100644 --- a/DvdLib/Ifo/Cell.cs +++ b/DvdLib/Ifo/Cell.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; namespace DvdLib.Ifo diff --git a/DvdLib/Ifo/CellPlaybackInfo.cs b/DvdLib/Ifo/CellPlaybackInfo.cs index ae3883eaa..e588e51ac 100644 --- a/DvdLib/Ifo/CellPlaybackInfo.cs +++ b/DvdLib/Ifo/CellPlaybackInfo.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; namespace DvdLib.Ifo diff --git a/DvdLib/Ifo/CellPositionInfo.cs b/DvdLib/Ifo/CellPositionInfo.cs index 2e0715940..2b973e083 100644 --- a/DvdLib/Ifo/CellPositionInfo.cs +++ b/DvdLib/Ifo/CellPositionInfo.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; namespace DvdLib.Ifo diff --git a/DvdLib/Ifo/Chapter.cs b/DvdLib/Ifo/Chapter.cs index 802c6ce62..bd3bd9704 100644 --- a/DvdLib/Ifo/Chapter.cs +++ b/DvdLib/Ifo/Chapter.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace DvdLib.Ifo { public class Chapter diff --git a/DvdLib/Ifo/Dvd.cs b/DvdLib/Ifo/Dvd.cs index 508c23db4..f784be83e 100644 --- a/DvdLib/Ifo/Dvd.cs +++ b/DvdLib/Ifo/Dvd.cs @@ -1,9 +1,7 @@ -using System; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; -using System.Diagnostics; +using System.Linq; using MediaBrowser.Model.IO; namespace DvdLib.Ifo @@ -33,10 +31,9 @@ namespace DvdLib.Ifo foreach (var ifo in allIfos) { var num = ifo.Name.Split('_').ElementAtOrDefault(1); - ushort ifoNumber; var numbersRead = new List(); - if (!string.IsNullOrEmpty(num) && ushort.TryParse(num, out ifoNumber) && !numbersRead.Contains(ifoNumber)) + if (!string.IsNullOrEmpty(num) && ushort.TryParse(num, out var ifoNumber) && !numbersRead.Contains(ifoNumber)) { ReadVTS(ifoNumber, ifo.FullName); numbersRead.Add(ifoNumber); @@ -47,7 +44,7 @@ namespace DvdLib.Ifo { using (var vmgFs = _fileSystem.GetFileStream(vmgPath.FullName, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) { - using (BigEndianBinaryReader vmgRead = new BigEndianBinaryReader(vmgFs)) + using (var vmgRead = new BigEndianBinaryReader(vmgFs)) { vmgFs.Seek(0x3E, SeekOrigin.Begin); _titleSetCount = vmgRead.ReadUInt16(); @@ -73,7 +70,7 @@ namespace DvdLib.Ifo read.BaseStream.Seek(6, SeekOrigin.Current); for (uint titleNum = 1; titleNum <= _titleCount; titleNum++) { - Title t = new Title(titleNum); + var t = new Title(titleNum); t.ParseTT_SRPT(read); Titles.Add(t); } @@ -81,7 +78,7 @@ namespace DvdLib.Ifo private void ReadVTS(ushort vtsNum, List allFiles) { - var filename = String.Format("VTS_{0:00}_0.IFO", vtsNum); + var filename = string.Format("VTS_{0:00}_0.IFO", vtsNum); var vtsPath = allFiles.FirstOrDefault(i => string.Equals(i.Name, filename, StringComparison.OrdinalIgnoreCase)) ?? allFiles.FirstOrDefault(i => string.Equals(i.Name, Path.ChangeExtension(filename, ".bup"), StringComparison.OrdinalIgnoreCase)); @@ -100,7 +97,7 @@ namespace DvdLib.Ifo using (var vtsFs = _fileSystem.GetFileStream(vtsPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read)) { - using (BigEndianBinaryReader vtsRead = new BigEndianBinaryReader(vtsFs)) + using (var vtsRead = new BigEndianBinaryReader(vtsFs)) { // Read VTS_PTT_SRPT vtsFs.Seek(0xC8, SeekOrigin.Begin); @@ -121,7 +118,7 @@ namespace DvdLib.Ifo { uint chapNum = 1; vtsFs.Seek(baseAddr + offsets[titleNum], SeekOrigin.Begin); - Title t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum + 1)); + var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum + 1)); if (t == null) continue; do @@ -151,11 +148,11 @@ namespace DvdLib.Ifo vtsFs.Seek(3, SeekOrigin.Current); uint vtsPgcOffset = vtsRead.ReadUInt32(); - Title t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum)); + var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum)); if (t != null) t.AddPgc(vtsRead, startByte + vtsPgcOffset, entryPgc, pgcNum); } } } } } -} \ No newline at end of file +} diff --git a/DvdLib/Ifo/DvdTime.cs b/DvdLib/Ifo/DvdTime.cs index f565f5fdf..3688089ec 100644 --- a/DvdLib/Ifo/DvdTime.cs +++ b/DvdLib/Ifo/DvdTime.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System; namespace DvdLib.Ifo { @@ -20,7 +17,7 @@ namespace DvdLib.Ifo else if ((data[3] & 0x40) != 0) FrameRate = 25; } - private byte GetBCDValue(byte data) + private static byte GetBCDValue(byte data) { return (byte)((((data & 0xF0) >> 4) * 10) + (data & 0x0F)); } diff --git a/DvdLib/Ifo/PgcCommandTable.cs b/DvdLib/Ifo/PgcCommandTable.cs index 2ead78cef..d329fcba2 100644 --- a/DvdLib/Ifo/PgcCommandTable.cs +++ b/DvdLib/Ifo/PgcCommandTable.cs @@ -1,7 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; namespace DvdLib.Ifo { diff --git a/DvdLib/Ifo/Program.cs b/DvdLib/Ifo/Program.cs index 48870d9dd..af08afa35 100644 --- a/DvdLib/Ifo/Program.cs +++ b/DvdLib/Ifo/Program.cs @@ -1,7 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; namespace DvdLib.Ifo { diff --git a/DvdLib/Ifo/ProgramChain.cs b/DvdLib/Ifo/ProgramChain.cs index 6b4e5fa32..80889738f 100644 --- a/DvdLib/Ifo/ProgramChain.cs +++ b/DvdLib/Ifo/ProgramChain.cs @@ -1,8 +1,6 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; +using System.Linq; namespace DvdLib.Ifo { @@ -68,7 +66,7 @@ namespace DvdLib.Ifo ProhibitedUserOperations = (UserOperation)br.ReadUInt32(); AudioStreamControl = br.ReadBytes(16); SubpictureStreamControl = br.ReadBytes(128); - + _nextProgramNumber = br.ReadUInt16(); _prevProgramNumber = br.ReadUInt16(); _goupProgramNumber = br.ReadUInt16(); @@ -89,7 +87,7 @@ namespace DvdLib.Ifo br.BaseStream.Seek(startPos + _cellPositionOffset, SeekOrigin.Begin); for (int cellNum = 0; cellNum < _cellCount; cellNum++) { - Cell c = new Cell(); + var c = new Cell(); c.ParsePosition(br); Cells.Add(c); } @@ -101,12 +99,12 @@ namespace DvdLib.Ifo } br.BaseStream.Seek(startPos + _programMapOffset, SeekOrigin.Begin); - List cellNumbers = new List(); + var cellNumbers = new List(); for (int progNum = 0; progNum < _programCount; progNum++) cellNumbers.Add(br.ReadByte() - 1); for (int i = 0; i < cellNumbers.Count; i++) { - int max = (i + 1 == cellNumbers.Count) ? _cellCount : cellNumbers[i+1]; + int max = (i + 1 == cellNumbers.Count) ? _cellCount : cellNumbers[i + 1]; Programs.Add(new Program(Cells.Where((c, idx) => idx >= cellNumbers[i] && idx < max).ToList())); } } diff --git a/DvdLib/Ifo/Title.cs b/DvdLib/Ifo/Title.cs index 70deb45bf..335e92992 100644 --- a/DvdLib/Ifo/Title.cs +++ b/DvdLib/Ifo/Title.cs @@ -1,7 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; namespace DvdLib.Ifo @@ -20,7 +17,7 @@ namespace DvdLib.Ifo public ProgramChain EntryProgramChain { get; private set; } public readonly List ProgramChains; - public readonly List Chapters; + public readonly List Chapters; public Title(uint titleNum) { @@ -53,7 +50,7 @@ namespace DvdLib.Ifo long curPos = br.BaseStream.Position; br.BaseStream.Seek(startByte, SeekOrigin.Begin); - ProgramChain pgc = new ProgramChain(pgcNum); + var pgc = new ProgramChain(pgcNum); pgc.ParseHeader(br); ProgramChains.Add(pgc); if (entryPgc) EntryProgramChain = pgc; diff --git a/DvdLib/Ifo/UserOperation.cs b/DvdLib/Ifo/UserOperation.cs index c3cffd487..757a5a05d 100644 --- a/DvdLib/Ifo/UserOperation.cs +++ b/DvdLib/Ifo/UserOperation.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System; namespace DvdLib.Ifo { diff --git a/DvdLib/Ifo/VideoAttributes.cs b/DvdLib/Ifo/VideoAttributes.cs index b2d375942..8b3996715 100644 --- a/DvdLib/Ifo/VideoAttributes.cs +++ b/DvdLib/Ifo/VideoAttributes.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace DvdLib.Ifo { public enum VideoCodec diff --git a/DvdLib/Properties/AssemblyInfo.cs b/DvdLib/Properties/AssemblyInfo.cs index cca792684..5fc055d1f 100644 --- a/DvdLib/Properties/AssemblyInfo.cs +++ b/DvdLib/Properties/AssemblyInfo.cs @@ -1,29 +1,21 @@ -using System.Resources; using System.Reflection; -using System.Runtime.CompilerServices; +using System.Resources; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DvdLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("DvdLib")] -[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1")] \ No newline at end of file +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs index 194ae73e0..01c9fe50f 100644 --- a/Emby.Dlna/Api/DlnaServerService.cs +++ b/Emby.Dlna/Api/DlnaServerService.cs @@ -1,14 +1,14 @@ -using MediaBrowser.Controller.Dlna; using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; -using MediaBrowser.Model.Services; -using MediaBrowser.Common.Extensions; -using System.Text; -using MediaBrowser.Controller.Net; using System.Linq; +using System.Text; +using System.Threading.Tasks; using Emby.Dlna.Main; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Services; namespace Emby.Dlna.Api { @@ -115,29 +115,11 @@ namespace Emby.Dlna.Api public IRequest Request { get; set; } private IHttpResultFactory _resultFactory; - private IContentDirectory ContentDirectory - { - get - { - return DlnaEntryPoint.Current.ContentDirectory; - } - } + private IContentDirectory ContentDirectory => DlnaEntryPoint.Current.ContentDirectory; - private IConnectionManager ConnectionManager - { - get - { - return DlnaEntryPoint.Current.ConnectionManager; - } - } + private IConnectionManager ConnectionManager => DlnaEntryPoint.Current.ConnectionManager; - private IMediaReceiverRegistrar MediaReceiverRegistrar - { - get - { - return DlnaEntryPoint.Current.MediaReceiverRegistrar; - } - } + private IMediaReceiverRegistrar MediaReceiverRegistrar => DlnaEntryPoint.Current.MediaReceiverRegistrar; public DlnaServerService(IDlnaManager dlnaManager, IHttpResultFactory httpResultFactory) { @@ -227,7 +209,7 @@ namespace Emby.Dlna.Api // TODO: Work out what this is doing. if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) || string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase) || - string.Equals(first, "jellyfin", StringComparison.OrdinalIgnoreCase )) + string.Equals(first, "jellyfin", StringComparison.OrdinalIgnoreCase)) { index++; } @@ -259,7 +241,7 @@ namespace Emby.Dlna.Api var cacheLength = TimeSpan.FromDays(365); var cacheKey = Request.RawUrl.GetMD5(); - return _resultFactory.GetStaticResult(Request, cacheKey, null, cacheLength, contentType, () => Task.FromResult(_dlnaManager.GetIcon(request.Filename).Stream)); + return _resultFactory.GetStaticResult(Request, cacheKey, null, cacheLength, contentType, () => Task.FromResult(_dlnaManager.GetIcon(request.Filename).Stream)); } public object Subscribe(ProcessContentDirectoryEventRequest request) diff --git a/Emby.Dlna/Api/DlnaService.cs b/Emby.Dlna/Api/DlnaService.cs index fec610d23..7f51f477a 100644 --- a/Emby.Dlna/Api/DlnaService.cs +++ b/Emby.Dlna/Api/DlnaService.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Dlna; @@ -80,4 +80,4 @@ namespace Emby.Dlna.Api _dlnaManager.CreateProfile(request); } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs index 7e61c3d6d..3e325c41c 100644 --- a/Emby.Dlna/Common/Argument.cs +++ b/Emby.Dlna/Common/Argument.cs @@ -1,12 +1,12 @@ - + namespace Emby.Dlna.Common -{ +{ public class Argument { - public string Name { get; set; } + public string Name { get; set; } - public string Direction { get; set; } + public string Direction { get; set; } - public string RelatedStateVariable { get; set; } + public string RelatedStateVariable { get; set; } } } diff --git a/Emby.Dlna/Common/DeviceIcon.cs b/Emby.Dlna/Common/DeviceIcon.cs index 27ae92d6f..3a91b952e 100644 --- a/Emby.Dlna/Common/DeviceIcon.cs +++ b/Emby.Dlna/Common/DeviceIcon.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna.Common { public class DeviceIcon diff --git a/Emby.Dlna/Common/DeviceService.cs b/Emby.Dlna/Common/DeviceService.cs index 0d91dbe76..c60d65291 100644 --- a/Emby.Dlna/Common/DeviceService.cs +++ b/Emby.Dlna/Common/DeviceService.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna.Common { public class DeviceService diff --git a/Emby.Dlna/Common/ServiceAction.cs b/Emby.Dlna/Common/ServiceAction.cs index 1bcc6a1d6..5e030d396 100644 --- a/Emby.Dlna/Common/ServiceAction.cs +++ b/Emby.Dlna/Common/ServiceAction.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Dlna.Common { diff --git a/Emby.Dlna/Common/StateVariable.cs b/Emby.Dlna/Common/StateVariable.cs index 571e17d06..4ca84bf51 100644 --- a/Emby.Dlna/Common/StateVariable.cs +++ b/Emby.Dlna/Common/StateVariable.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System; namespace Emby.Dlna.Common diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index 6ab337752..0ebb490a1 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna.Configuration { public class DlnaOptions diff --git a/Emby.Dlna/ConfigurationExtension.cs b/Emby.Dlna/ConfigurationExtension.cs index f19f0dfb5..82d726e01 100644 --- a/Emby.Dlna/ConfigurationExtension.cs +++ b/Emby.Dlna/ConfigurationExtension.cs @@ -1,6 +1,6 @@ -using MediaBrowser.Common.Configuration; -using Emby.Dlna.Configuration; using System.Collections.Generic; +using Emby.Dlna.Configuration; +using MediaBrowser.Common.Configuration; namespace Emby.Dlna { diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index ab747d189..cc427f2a1 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -1,8 +1,8 @@ -using MediaBrowser.Common.Net; +using System.Collections.Generic; +using Emby.Dlna.Service; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; -using Emby.Dlna.Service; -using System.Collections.Generic; using MediaBrowser.Model.Xml; using Microsoft.Extensions.Logging; diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs index 0666eda22..f5873455a 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs @@ -1,6 +1,6 @@ -using Emby.Dlna.Common; -using Emby.Dlna.Service; using System.Collections.Generic; +using Emby.Dlna.Common; +using Emby.Dlna.Service; namespace Emby.Dlna.ConnectionManager { @@ -11,7 +11,7 @@ namespace Emby.Dlna.ConnectionManager return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(), GetStateVariables()); } - private IEnumerable GetStateVariables() + private static IEnumerable GetStateVariables() { var list = new List(); diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index 7e3e5f650..16211c61f 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -1,12 +1,11 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using Emby.Dlna.Server; -using Emby.Dlna.Service; -using MediaBrowser.Model.Dlna; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using Emby.Dlna.Service; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.ConnectionManager { diff --git a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs index 9b22b7773..b7727b558 100644 --- a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs @@ -1,5 +1,5 @@ -using Emby.Dlna.Common; using System.Collections.Generic; +using Emby.Dlna.Common; namespace Emby.Dlna.ConnectionManager { @@ -19,7 +19,7 @@ namespace Emby.Dlna.ConnectionManager return list; } - private ServiceAction PrepareForConnection() + private static ServiceAction PrepareForConnection() { var action = new ServiceAction { @@ -77,8 +77,8 @@ namespace Emby.Dlna.ConnectionManager return action; } - - private ServiceAction GetCurrentConnectionInfo() + + private static ServiceAction GetCurrentConnectionInfo() { var action = new ServiceAction { diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index 7c809a952..cd21599d0 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -1,18 +1,18 @@ -using MediaBrowser.Common.Net; +using System; +using System.Collections.Generic; +using Emby.Dlna.Service; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using Emby.Dlna.Service; -using MediaBrowser.Model.Dlna; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.TV; +using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.ContentDirectory { diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs index facc25214..15fdb36c4 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs @@ -1,6 +1,6 @@ -using Emby.Dlna.Common; -using Emby.Dlna.Service; using System.Collections.Generic; +using Emby.Dlna.Common; +using Emby.Dlna.Service; namespace Emby.Dlna.ContentDirectory { @@ -8,11 +8,11 @@ namespace Emby.Dlna.ContentDirectory { public string GetXml() { - return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(), + return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(), GetStateVariables()); } - private IEnumerable GetStateVariables() + private static IEnumerable GetStateVariables() { var list = new List(); diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 57d4078a5..2f6a0ecee 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1,19 +1,3 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Library; -using Emby.Dlna.Didl; -using Emby.Dlna.Server; -using Emby.Dlna.Service; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; using System.Globalization; @@ -21,17 +5,28 @@ using System.IO; using System.Linq; using System.Text; using System.Threading; -using System.Threading.Tasks; using System.Xml; +using Emby.Dlna.Didl; +using Emby.Dlna.Service; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.TV; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Querying; using MediaBrowser.Model.Xml; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Controller.LiveTv; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.ContentDirectory { @@ -197,9 +192,7 @@ namespace Emby.Dlna.ContentDirectory public string GetValueOrDefault(IDictionary sparams, string key, string defaultValue) { - string val; - - if (sparams.TryGetValue(key, out val)) + if (sparams.TryGetValue(key, out string val)) { return val; } @@ -221,14 +214,12 @@ namespace Emby.Dlna.ContentDirectory int? requestedCount = null; int? start = 0; - int requestedVal; - if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0) + if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out var requestedVal) && requestedVal > 0) { requestedCount = requestedVal; } - int startVal; - if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0) + if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out var startVal) && startVal > 0) { start = startVal; } @@ -247,7 +238,7 @@ namespace Emby.Dlna.ContentDirectory var dlnaOptions = _config.GetDlnaConfiguration(); - using (XmlWriter writer = XmlWriter.Create(builder, settings)) + using (var writer = XmlWriter.Create(builder, settings)) { //writer.WriteStartDocument(); @@ -311,7 +302,7 @@ namespace Emby.Dlna.ContentDirectory var resXML = builder.ToString(); - return new [] + return new[] { new KeyValuePair("Result", resXML), new KeyValuePair("NumberReturned", provided.ToString(_usCulture)), @@ -339,14 +330,12 @@ namespace Emby.Dlna.ContentDirectory int? requestedCount = null; int? start = 0; - int requestedVal; - if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0) + if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out var requestedVal) && requestedVal > 0) { requestedCount = requestedVal; } - int startVal; - if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0) + if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out var startVal) && startVal > 0) { start = startVal; } @@ -363,7 +352,7 @@ namespace Emby.Dlna.ContentDirectory int totalCount = 0; int provided = 0; - using (XmlWriter writer = XmlWriter.Create(builder, settings)) + using (var writer = XmlWriter.Create(builder, settings)) { //writer.WriteStartDocument(); @@ -1144,7 +1133,7 @@ namespace Emby.Dlna.ContentDirectory StartIndex = query.StartIndex, UserId = query.User.Id - }, new [] { parent }, query.DtoOptions); + }, new[] { parent }, query.DtoOptions); return ToResult(result); } @@ -1298,7 +1287,6 @@ namespace Emby.Dlna.ContentDirectory private ServerItem ParseItemId(string id, User user) { - Guid itemId; StubType? stubType = null; // After using PlayTo, MediaMonkey sends a request to the server trying to get item info @@ -1324,7 +1312,7 @@ namespace Emby.Dlna.ContentDirectory } } - if (Guid.TryParse(id, out itemId)) + if (Guid.TryParse(id, out var itemId)) { var item = _libraryManager.GetItemById(itemId); diff --git a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs index 8e5c07ce2..e999314fa 100644 --- a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs @@ -1,5 +1,5 @@ -using Emby.Dlna.Common; using System.Collections.Generic; +using Emby.Dlna.Common; namespace Emby.Dlna.ContentDirectory { @@ -7,7 +7,7 @@ namespace Emby.Dlna.ContentDirectory { public IEnumerable GetActions() { - return new [] + return new[] { GetSearchCapabilitiesAction(), GetSortCapabilitiesAction(), @@ -20,7 +20,7 @@ namespace Emby.Dlna.ContentDirectory }; } - private ServiceAction GetGetSystemUpdateIDAction() + private static ServiceAction GetGetSystemUpdateIDAction() { var action = new ServiceAction { @@ -37,7 +37,7 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetSearchCapabilitiesAction() + private static ServiceAction GetSearchCapabilitiesAction() { var action = new ServiceAction { @@ -54,7 +54,7 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetSortCapabilitiesAction() + private static ServiceAction GetSortCapabilitiesAction() { var action = new ServiceAction { @@ -71,7 +71,7 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetX_GetFeatureListAction() + private static ServiceAction GetX_GetFeatureListAction() { var action = new ServiceAction { @@ -88,7 +88,7 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetSearchAction() + private static ServiceAction GetSearchAction() { var action = new ServiceAction { @@ -334,7 +334,7 @@ namespace Emby.Dlna.ContentDirectory return action; } - + private ServiceAction GetXSetBookmarkAction() { var action = new ServiceAction diff --git a/Emby.Dlna/ControlRequest.cs b/Emby.Dlna/ControlRequest.cs index 2b8ce844a..afd9a0b87 100644 --- a/Emby.Dlna/ControlRequest.cs +++ b/Emby.Dlna/ControlRequest.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; namespace Emby.Dlna diff --git a/Emby.Dlna/ControlResponse.cs b/Emby.Dlna/ControlResponse.cs index 889a6940c..d2b79fc58 100644 --- a/Emby.Dlna/ControlResponse.cs +++ b/Emby.Dlna/ControlResponse.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Dlna { @@ -15,4 +15,4 @@ namespace Emby.Dlna Headers = new Dictionary(); } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 7af48ae17..d2f635e56 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -1,4 +1,11 @@ -using MediaBrowser.Model.Extensions; +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml; +using Emby.Dlna.Configuration; +using Emby.Dlna.ContentDirectory; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; @@ -6,23 +13,15 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Playlists; -using Emby.Dlna.ContentDirectory; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; -using MediaBrowser.Controller.MediaEncoding; -using Emby.Dlna.Configuration; +using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Net; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.Didl { @@ -79,7 +78,7 @@ namespace Emby.Dlna.Didl using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8)) { - using (XmlWriter writer = XmlWriter.Create(builder, settings)) + using (var writer = XmlWriter.Create(builder, settings)) { //writer.WriteStartDocument(); @@ -375,7 +374,7 @@ namespace Emby.Dlna.Didl ? GetMimeType(filename) : mediaProfile.MimeType; - writer.WriteAttributeString("protocolInfo", String.Format( + writer.WriteAttributeString("protocolInfo", string.Format( "http-get:*:{0}:{1}", mimeType, contentFeatures @@ -573,7 +572,7 @@ namespace Emby.Dlna.Didl streamInfo.RunTimeTicks ?? 0, streamInfo.TranscodeSeekInfo); - writer.WriteAttributeString("protocolInfo", String.Format( + writer.WriteAttributeString("protocolInfo", string.Format( "http-get:*:{0}:{1}", mimeType, contentFeatures @@ -1017,7 +1016,7 @@ namespace Emby.Dlna.Didl var contentFeatures = new ContentFeatureBuilder(_profile) .BuildImageHeader(format, width, height, imageInfo.IsDirectStream, org_Pn); - writer.WriteAttributeString("protocolInfo", String.Format( + writer.WriteAttributeString("protocolInfo", string.Format( "http-get:*:{0}:{1}", GetMimeType("file." + format), contentFeatures diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs index 2c9a1ea18..a0e67870e 100644 --- a/Emby.Dlna/Didl/Filter.cs +++ b/Emby.Dlna/Didl/Filter.cs @@ -1,6 +1,5 @@ -using MediaBrowser.Model.Extensions; using System; -using System.Collections.Generic; +using MediaBrowser.Model.Extensions; namespace Emby.Dlna.Didl { diff --git a/Emby.Dlna/Didl/StringWriterWithEncoding.cs b/Emby.Dlna/Didl/StringWriterWithEncoding.cs index b5c565801..c3c4bd393 100644 --- a/Emby.Dlna/Didl/StringWriterWithEncoding.cs +++ b/Emby.Dlna/Didl/StringWriterWithEncoding.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; +using System; using System.IO; using System.Text; -using System.Threading.Tasks; namespace Emby.Dlna.Didl { @@ -53,9 +51,6 @@ namespace Emby.Dlna.Didl _encoding = encoding; } - public override Encoding Encoding - { - get { return (null == _encoding) ? base.Encoding : _encoding; } - } + public override Encoding Encoding => (null == _encoding) ? base.Encoding : _encoding; } } diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 48a33757b..f795b58cb 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -1,24 +1,22 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Dlna; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Plugins; -using Emby.Dlna.Profiles; -using Emby.Dlna.Server; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Drawing; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; +using Emby.Dlna.Profiles; +using Emby.Dlna.Server; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Drawing; using MediaBrowser.Model.IO; using MediaBrowser.Model.Reflection; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Dlna { @@ -34,16 +32,17 @@ namespace Emby.Dlna private readonly Dictionary> _profiles = new Dictionary>(StringComparer.Ordinal); - public DlnaManager(IXmlSerializer xmlSerializer, + public DlnaManager( + IXmlSerializer xmlSerializer, IFileSystem fileSystem, IApplicationPaths appPaths, - ILogger logger, + ILoggerFactory loggerFactory, IJsonSerializer jsonSerializer, IServerApplicationHost appHost, IAssemblyInfo assemblyInfo) { _xmlSerializer = xmlSerializer; _fileSystem = fileSystem; _appPaths = appPaths; - _logger = logger; + _logger = loggerFactory.CreateLogger("Dlna"); _jsonSerializer = jsonSerializer; _appHost = appHost; _assemblyInfo = assemblyInfo; @@ -95,7 +94,7 @@ namespace Emby.Dlna { if (deviceInfo == null) { - throw new ArgumentNullException("deviceInfo"); + throw new ArgumentNullException(nameof(deviceInfo)); } var profile = GetProfiles() @@ -207,7 +206,7 @@ namespace Emby.Dlna { if (headers == null) { - throw new ArgumentNullException("headers"); + throw new ArgumentNullException(nameof(headers)); } // Convert to case insensitive @@ -241,9 +240,7 @@ namespace Emby.Dlna return false; } - string value; - - if (headers.TryGetValue(header.Name, out value)) + if (headers.TryGetValue(header.Name, out string value)) { switch (header.Match) { @@ -263,21 +260,9 @@ namespace Emby.Dlna return false; } - private string UserProfilesPath - { - get - { - return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user"); - } - } + private string UserProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user"); - private string SystemProfilesPath - { - get - { - return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system"); - } - } + private string SystemProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system"); private IEnumerable GetProfiles(string path, DeviceProfileType type) { @@ -302,8 +287,7 @@ namespace Emby.Dlna { lock (_profiles) { - Tuple profileTuple; - if (_profiles.TryGetValue(path, out profileTuple)) + if (_profiles.TryGetValue(path, out Tuple profileTuple)) { return profileTuple.Item2; } @@ -335,7 +319,7 @@ namespace Emby.Dlna { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } var info = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase)); diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index c58144e00..71ded2337 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -1,4 +1,8 @@ - + + + + + diff --git a/Emby.Dlna/EventSubscriptionResponse.cs b/Emby.Dlna/EventSubscriptionResponse.cs index 1c405e601..6dc1aacf4 100644 --- a/Emby.Dlna/EventSubscriptionResponse.cs +++ b/Emby.Dlna/EventSubscriptionResponse.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Dlna { diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs index ea9ba3f22..b4ff3ec1d 100644 --- a/Emby.Dlna/Eventing/EventManager.cs +++ b/Emby.Dlna/Eventing/EventManager.cs @@ -1,7 +1,3 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Dlna; -using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -9,6 +5,9 @@ using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.Eventing { @@ -83,9 +82,7 @@ namespace Emby.Dlna.Eventing // Starts with SECOND- header = header.Split('-').Last(); - int val; - - if (int.TryParse(header, NumberStyles.Integer, _usCulture, out val)) + if (int.TryParse(header, NumberStyles.Integer, _usCulture, out var val)) { return val; } @@ -98,8 +95,7 @@ namespace Emby.Dlna.Eventing { _logger.LogDebug("Cancelling event subscription {0}", subscriptionId); - EventSubscription sub; - _subscriptions.TryRemove(subscriptionId, out sub); + _subscriptions.TryRemove(subscriptionId, out EventSubscription sub); return new EventSubscriptionResponse { @@ -130,9 +126,7 @@ namespace Emby.Dlna.Eventing private EventSubscription GetSubscription(string id, bool throwOnMissing) { - EventSubscription e; - - if (!_subscriptions.TryGetValue(id, out e) && throwOnMissing) + if (!_subscriptions.TryGetValue(id, out EventSubscription e) && throwOnMissing) { throw new ResourceNotFoundException("Event with Id " + id + " not found."); } diff --git a/Emby.Dlna/Eventing/EventSubscription.cs b/Emby.Dlna/Eventing/EventSubscription.cs index adb042d6c..eb8781e0c 100644 --- a/Emby.Dlna/Eventing/EventSubscription.cs +++ b/Emby.Dlna/Eventing/EventSubscription.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Emby.Dlna.Eventing { @@ -23,12 +23,6 @@ namespace Emby.Dlna.Eventing TriggerCount++; } - public bool IsExpired - { - get - { - return SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow; - } - } + public bool IsExpired => SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow; } } diff --git a/Emby.Dlna/IConnectionManager.cs b/Emby.Dlna/IConnectionManager.cs index 5f889a34c..855c4454d 100644 --- a/Emby.Dlna/IConnectionManager.cs +++ b/Emby.Dlna/IConnectionManager.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna { public interface IConnectionManager : IEventManager, IUpnpService diff --git a/Emby.Dlna/IContentDirectory.cs b/Emby.Dlna/IContentDirectory.cs index d63af4ef2..b54a17c00 100644 --- a/Emby.Dlna/IContentDirectory.cs +++ b/Emby.Dlna/IContentDirectory.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna { public interface IContentDirectory : IEventManager, IUpnpService diff --git a/Emby.Dlna/IEventManager.cs b/Emby.Dlna/IEventManager.cs index e90476fe3..4f67a1b9b 100644 --- a/Emby.Dlna/IEventManager.cs +++ b/Emby.Dlna/IEventManager.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna { public interface IEventManager diff --git a/Emby.Dlna/IMediaReceiverRegistrar.cs b/Emby.Dlna/IMediaReceiverRegistrar.cs index cb43221e5..5dde01f58 100644 --- a/Emby.Dlna/IMediaReceiverRegistrar.cs +++ b/Emby.Dlna/IMediaReceiverRegistrar.cs @@ -1,4 +1,4 @@ - + namespace Emby.Dlna { public interface IMediaReceiverRegistrar : IEventManager, IUpnpService diff --git a/Emby.Dlna/IUpnpService.cs b/Emby.Dlna/IUpnpService.cs index caae87ba3..ab8aa4619 100644 --- a/Emby.Dlna/IUpnpService.cs +++ b/Emby.Dlna/IUpnpService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Dlna { @@ -10,7 +10,7 @@ namespace Emby.Dlna /// The headers. /// System.String. string GetServiceXml(IDictionary headers); - + /// /// Processes the control request. /// diff --git a/Emby.Dlna/Images/logo120.jpg b/Emby.Dlna/Images/logo120.jpg index 9a0e199a3..c70f4db0d 100644 Binary files a/Emby.Dlna/Images/logo120.jpg and b/Emby.Dlna/Images/logo120.jpg differ diff --git a/Emby.Dlna/Images/logo120.png b/Emby.Dlna/Images/logo120.png index c7fc5c1ce..321c47729 100644 Binary files a/Emby.Dlna/Images/logo120.png and b/Emby.Dlna/Images/logo120.png differ diff --git a/Emby.Dlna/Images/logo240.jpg b/Emby.Dlna/Images/logo240.jpg index 74cb2c429..da1cb5e07 100644 Binary files a/Emby.Dlna/Images/logo240.jpg and b/Emby.Dlna/Images/logo240.jpg differ diff --git a/Emby.Dlna/Images/logo240.png b/Emby.Dlna/Images/logo240.png index d229ed24c..64c828129 100644 Binary files a/Emby.Dlna/Images/logo240.png and b/Emby.Dlna/Images/logo240.png differ diff --git a/Emby.Dlna/Images/logo48.jpg b/Emby.Dlna/Images/logo48.jpg index 9822a8e2f..269bcf589 100644 Binary files a/Emby.Dlna/Images/logo48.jpg and b/Emby.Dlna/Images/logo48.jpg differ diff --git a/Emby.Dlna/Images/logo48.png b/Emby.Dlna/Images/logo48.png index 23007e155..b8fc14564 100644 Binary files a/Emby.Dlna/Images/logo48.png and b/Emby.Dlna/Images/logo48.png differ diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 6ab0767a5..1ab6014eb 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -1,4 +1,10 @@ -using MediaBrowser.Common.Configuration; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Emby.Dlna.PlayTo; +using Emby.Dlna.Ssdp; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; @@ -6,25 +12,19 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.TV; -using Emby.Dlna.PlayTo; -using Emby.Dlna.Ssdp; -using Microsoft.Extensions.Logging; -using System; -using System.Linq; -using System.Threading.Tasks; -using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Threading; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; using Rssdp; using Rssdp.Infrastructure; -using System.Threading; namespace Emby.Dlna.Main { @@ -75,11 +75,11 @@ namespace Emby.Dlna.Main IUserDataManager userDataManager, ILocalizationManager localizationManager, IMediaSourceManager mediaSourceManager, - IDeviceDiscovery deviceDiscovery, - IMediaEncoder mediaEncoder, - ISocketFactory socketFactory, - ITimerFactory timerFactory, - IEnvironmentInfo environmentInfo, + IDeviceDiscovery deviceDiscovery, + IMediaEncoder mediaEncoder, + ISocketFactory socketFactory, + ITimerFactory timerFactory, + IEnvironmentInfo environmentInfo, INetworkManager networkManager, IUserViewManager userViewManager, IXmlReaderSettingsFactory xmlReaderSettingsFactory, @@ -104,19 +104,19 @@ namespace Emby.Dlna.Main _networkManager = networkManager; _logger = loggerFactory.CreateLogger("Dlna"); - ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager, - userDataManager, - imageProcessor, - libraryManager, - config, - userManager, - _logger, - httpClient, - localizationManager, - mediaSourceManager, + ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager, + userDataManager, + imageProcessor, + libraryManager, + config, + userManager, + _logger, + httpClient, + localizationManager, + mediaSourceManager, userViewManager, - mediaEncoder, - xmlReaderSettingsFactory, + mediaEncoder, + xmlReaderSettingsFactory, tvSeriesManager); ConnectionManager = new ConnectionManager.ConnectionManager(dlnaManager, config, _logger, httpClient, xmlReaderSettingsFactory); @@ -271,18 +271,18 @@ namespace Emby.Dlna.Main var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), //How long SSDP clients can cache this info. - Location = uri, // Must point to the URL that serves your devices UPnP description document. + Location = uri, // Must point to the URL that serves your devices UPnP description document. FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", Uuid = udn - // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc. + // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc. }; SetProperies(device, fullService); _Publisher.AddDevice(device); - var embeddedDevices = new [] + var embeddedDevices = new[] { "urn:schemas-upnp-org:service:ContentDirectory:1", "urn:schemas-upnp-org:service:ConnectionManager:1", @@ -297,7 +297,7 @@ namespace Emby.Dlna.Main Manufacturer = device.Manufacturer, ModelName = device.ModelName, Uuid = udn - // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc. + // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc. }; SetProperies(embeddedDevice, subDevice); @@ -308,8 +308,7 @@ namespace Emby.Dlna.Main private string CreateUuid(string text) { - Guid guid; - if (!Guid.TryParse(text, out guid)) + if (!Guid.TryParse(text, out var guid)) { guid = text.GetMD5(); } diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs index d1a595de0..6257892b1 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs @@ -1,11 +1,10 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using Emby.Dlna.Server; -using Emby.Dlna.Service; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using Emby.Dlna.Service; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.MediaReceiverRegistrar { @@ -21,7 +20,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar throw new ResourceNotFoundException("Unexpected control request name: " + methodName); } - private IEnumerable> HandleIsAuthorized() + private static IEnumerable> HandleIsAuthorized() { return new Dictionary(StringComparer.OrdinalIgnoreCase) { @@ -29,7 +28,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar }; } - private IEnumerable> HandleIsValidated() + private static IEnumerable> HandleIsValidated() { return new Dictionary(StringComparer.OrdinalIgnoreCase) { diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index f07af0464..2b84528ea 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -1,11 +1,9 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Dlna; -using Emby.Dlna.Service; -using Microsoft.Extensions.Logging; -using System; using System.Collections.Generic; +using Emby.Dlna.Service; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.MediaReceiverRegistrar { diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs index bc4bee7c9..641341185 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs @@ -1,6 +1,6 @@ -using Emby.Dlna.Common; -using Emby.Dlna.Service; using System.Collections.Generic; +using Emby.Dlna.Common; +using Emby.Dlna.Service; namespace Emby.Dlna.MediaReceiverRegistrar { @@ -12,7 +12,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar GetStateVariables()); } - private IEnumerable GetStateVariables() + private static IEnumerable GetStateVariables() { var list = new List(); diff --git a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs index bce8bfaef..86429f605 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs @@ -1,5 +1,5 @@ -using Emby.Dlna.Common; using System.Collections.Generic; +using Emby.Dlna.Common; namespace Emby.Dlna.MediaReceiverRegistrar { @@ -7,7 +7,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar { public IEnumerable GetActions() { - return new [] + return new[] { GetIsValidated(), GetIsAuthorized(), @@ -19,7 +19,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar }; } - private ServiceAction GetIsValidated() + private static ServiceAction GetIsValidated() { var action = new ServiceAction { @@ -41,7 +41,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar return action; } - private ServiceAction GetIsAuthorized() + private static ServiceAction GetIsAuthorized() { var action = new ServiceAction { @@ -63,7 +63,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar return action; } - private ServiceAction GetRegisterDevice() + private static ServiceAction GetRegisterDevice() { var action = new ServiceAction { @@ -85,7 +85,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar return action; } - private ServiceAction GetGetValidationSucceededUpdateID() + private static ServiceAction GetGetValidationSucceededUpdateID() { var action = new ServiceAction { diff --git a/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs b/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs index 99aa50bd9..fdf435bcf 100644 --- a/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs +++ b/Emby.Dlna/PlayTo/CurrentIdEventArgs.cs @@ -1,9 +1,9 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { public class CurrentIdEventArgs : EventArgs { - public string Id { get; set; } + public string Id { get; set; } } } diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 13bed6b2f..68aa0a6a7 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -1,21 +1,17 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; -using Emby.Dlna.Common; -using Emby.Dlna.Ssdp; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net; -using System.Security; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Emby.Dlna.Common; using Emby.Dlna.Server; +using Emby.Dlna.Ssdp; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Threading; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.PlayTo { @@ -39,10 +35,7 @@ namespace Emby.Dlna.PlayTo RefreshVolumeIfNeeded(); return _volume; } - set - { - _volume = value; - } + set => _volume = value; } public TimeSpan? Duration { get; set; } @@ -50,41 +43,17 @@ namespace Emby.Dlna.PlayTo private TimeSpan _position = TimeSpan.FromSeconds(0); public TimeSpan Position { - get - { - return _position; - } - set - { - _position = value; - } + get => _position; + set => _position = value; } public TRANSPORTSTATE TransportState { get; private set; } - public bool IsPlaying - { - get - { - return TransportState == TRANSPORTSTATE.PLAYING; - } - } + public bool IsPlaying => TransportState == TRANSPORTSTATE.PLAYING; - public bool IsPaused - { - get - { - return TransportState == TRANSPORTSTATE.PAUSED || TransportState == TRANSPORTSTATE.PAUSED_PLAYBACK; - } - } + public bool IsPaused => TransportState == TRANSPORTSTATE.PAUSED || TransportState == TRANSPORTSTATE.PAUSED_PLAYBACK; - public bool IsStopped - { - get - { - return TransportState == TRANSPORTSTATE.STOPPED; - } - } + public bool IsStopped => TransportState == TRANSPORTSTATE.STOPPED; #endregion @@ -311,7 +280,7 @@ namespace Emby.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, String.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME")) + await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, string.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME")) .ConfigureAwait(false); RestartTimer(true); @@ -364,7 +333,7 @@ namespace Emby.Dlna.PlayTo private string CreateDidlMeta(string value) { if (string.IsNullOrEmpty(value)) - return String.Empty; + return string.Empty; return DescriptionXmlBuilder.Escape(value); } @@ -620,9 +589,7 @@ namespace Emby.Dlna.PlayTo if (transportStateValue != null) { - TRANSPORTSTATE state; - - if (Enum.TryParse(transportStateValue, true, out state)) + if (Enum.TryParse(transportStateValue, true, out TRANSPORTSTATE state)) { return state; } @@ -739,7 +706,7 @@ namespace Emby.Dlna.PlayTo if (track == null) { - //If track is null, some vendors do this, use GetMediaInfo instead + //If track is null, some vendors do this, use GetMediaInfo instead return new Tuple(true, null); } @@ -783,7 +750,7 @@ namespace Emby.Dlna.PlayTo { if (container == null) { - throw new ArgumentNullException("container"); + throw new ArgumentNullException(nameof(container)); } var url = container.GetValue(uPnpNamespaces.Res); @@ -810,7 +777,7 @@ namespace Emby.Dlna.PlayTo { if (container == null) { - throw new ArgumentNullException("container"); + throw new ArgumentNullException(nameof(container)); } var resElement = container.Element(uPnpNamespaces.Res); @@ -979,7 +946,7 @@ namespace Emby.Dlna.PlayTo if (modelDescription != null) deviceProperties.ModelDescription = modelDescription.Value; - deviceProperties.BaseUrl = String.Format("http://{0}:{1}", url.Host, url.Port); + deviceProperties.BaseUrl = string.Format("http://{0}:{1}", url.Host, url.Port); var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault(); @@ -1021,7 +988,7 @@ namespace Emby.Dlna.PlayTo { if (element == null) { - throw new ArgumentNullException("element"); + throw new ArgumentNullException(nameof(element)); } var mimeType = element.GetDescendantValue(uPnpNamespaces.ud.GetName("mimetype")); @@ -1173,7 +1140,7 @@ namespace Emby.Dlna.PlayTo public override string ToString() { - return String.Format("{0} - {1}", Properties.Name, Properties.BaseUrl); + return string.Format("{0} - {1}", Properties.Name, Properties.BaseUrl); } } } diff --git a/Emby.Dlna/PlayTo/DeviceInfo.cs b/Emby.Dlna/PlayTo/DeviceInfo.cs index d453a3d82..9e7c04bdb 100644 --- a/Emby.Dlna/PlayTo/DeviceInfo.cs +++ b/Emby.Dlna/PlayTo/DeviceInfo.cs @@ -1,6 +1,6 @@ -using Emby.Dlna.Common; -using MediaBrowser.Model.Dlna; using System.Collections.Generic; +using Emby.Dlna.Common; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.PlayTo { @@ -34,26 +34,14 @@ namespace Emby.Dlna.PlayTo private string _baseUrl = string.Empty; public string BaseUrl { - get - { - return _baseUrl; - } - set - { - _baseUrl = value; - } + get => _baseUrl; + set => _baseUrl = value; } public DeviceIcon Icon { get; set; } private readonly List _services = new List(); - public List Services - { - get - { - return _services; - } - } + public List Services => _services; public DeviceIdentification ToDeviceIdentification() { diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index c51f220ef..409b8442c 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -1,28 +1,25 @@ -using MediaBrowser.Controller.Dlna; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Session; -using Emby.Dlna.Didl; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Session; -using MediaBrowser.Model.System; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Emby.Dlna.Didl; using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Extensions; -using System.Net.Http; using MediaBrowser.Model.Services; +using MediaBrowser.Model.Session; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.PlayTo { @@ -47,18 +44,9 @@ namespace Emby.Dlna.PlayTo private readonly string _accessToken; private readonly DateTime _creationTime; - public bool IsSessionActive - { - get - { - return !_disposed && _device != null; - } - } + public bool IsSessionActive => !_disposed && _device != null; - public bool SupportsMediaControl - { - get { return IsSessionActive; } - } + public bool SupportsMediaControl => IsSessionActive; public PlayToController(SessionInfo session, ISessionManager sessionManager, ILibraryManager libraryManager, ILogger logger, IDlnaManager dlnaManager, IUserManager userManager, IImageProcessor imageProcessor, string serverAddress, string accessToken, IDeviceDiscovery deviceDiscovery, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IConfigurationManager config, IMediaEncoder mediaEncoder) { @@ -110,14 +98,11 @@ namespace Emby.Dlna.PlayTo { var info = e.Argument; - string nts; - info.Headers.TryGetValue("NTS", out nts); + info.Headers.TryGetValue("NTS", out string nts); - string usn; - if (!info.Headers.TryGetValue("USN", out usn)) usn = String.Empty; + if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty; - string nt; - if (!info.Headers.TryGetValue("NT", out nt)) nt = String.Empty; + if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty; if (usn.IndexOf(_device.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1 && !_disposed) @@ -439,13 +424,7 @@ namespace Emby.Dlna.PlayTo private int _currentPlaylistIndex; private readonly List _playlist = new List(); - private List Playlist - { - get - { - return _playlist; - } - } + private List Playlist => _playlist; private void AddItemFromId(Guid id, List list) { @@ -641,9 +620,7 @@ namespace Emby.Dlna.PlayTo private Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken) { - GeneralCommandType commandType; - - if (Enum.TryParse(command.Name, true, out commandType)) + if (Enum.TryParse(command.Name, true, out GeneralCommandType commandType)) { switch (commandType) { @@ -659,13 +636,9 @@ namespace Emby.Dlna.PlayTo return _device.ToggleMute(cancellationToken); case GeneralCommandType.SetAudioStreamIndex: { - string arg; - - if (command.Arguments.TryGetValue("Index", out arg)) + if (command.Arguments.TryGetValue("Index", out string arg)) { - int val; - - if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out val)) + if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var val)) { return SetAudioStreamIndex(val); } @@ -677,13 +650,9 @@ namespace Emby.Dlna.PlayTo } case GeneralCommandType.SetSubtitleStreamIndex: { - string arg; - - if (command.Arguments.TryGetValue("Index", out arg)) + if (command.Arguments.TryGetValue("Index", out string arg)) { - int val; - - if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out val)) + if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var val)) { return SetSubtitleStreamIndex(val); } @@ -695,13 +664,9 @@ namespace Emby.Dlna.PlayTo } case GeneralCommandType.SetVolume: { - string arg; - - if (command.Arguments.TryGetValue("Volume", out arg)) + if (command.Arguments.TryGetValue("Volume", out string arg)) { - int volume; - - if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out volume)) + if (int.TryParse(arg, NumberStyles.Integer, _usCulture, out var volume)) { return _device.SetVolume(volume, cancellationToken); } @@ -829,7 +794,7 @@ namespace Emby.Dlna.PlayTo { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } var parts = url.Split('/'); @@ -855,7 +820,7 @@ namespace Emby.Dlna.PlayTo { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } var request = new StreamParams @@ -896,8 +861,7 @@ namespace Emby.Dlna.PlayTo { var value = values.Get(name); - int result; - if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) + if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } @@ -909,8 +873,7 @@ namespace Emby.Dlna.PlayTo { var value = values.Get(name); - long result; - if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) + if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 47d00aad5..8e82e6f69 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -1,26 +1,23 @@ -using MediaBrowser.Common.Net; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Session; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Session; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; +using MediaBrowser.Model.Session; using MediaBrowser.Model.Threading; -using System.Threading; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Devices; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.PlayTo { @@ -81,11 +78,9 @@ namespace Emby.Dlna.PlayTo var info = e.Argument; - string usn; - if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty; + if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty; - string nt; - if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty; + if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty; string location = info.Location.ToString(); @@ -158,8 +153,7 @@ namespace Emby.Dlna.PlayTo _logger.LogDebug("Attempting to create PlayToController from location {0}", location); _logger.LogDebug("Logging session activity from location {0}", location); - string uuid; - if (info.Headers.TryGetValue("USN", out uuid)) + if (info.Headers.TryGetValue("USN", out string uuid)) { uuid = GetUuid(uuid); } @@ -170,7 +164,7 @@ namespace Emby.Dlna.PlayTo string deviceName = null; - var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersion.ToString(), uuid, deviceName, uri.OriginalString, null); + var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersion, uuid, deviceName, uri.OriginalString, null); var controller = sessionInfo.SessionControllers.OfType().FirstOrDefault(); diff --git a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs index b89f7a864..ffa56419b 100644 --- a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { @@ -6,4 +6,4 @@ namespace Emby.Dlna.PlayTo { public uBaseObject MediaInfo { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs index 17d2540a5..8cd8b47ac 100644 --- a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { diff --git a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs index 847c33ff7..2afdc324d 100644 --- a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { @@ -12,4 +12,4 @@ namespace Emby.Dlna.PlayTo public uBaseObject OldMediaInfo { get; set; } public uBaseObject NewMediaInfo { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/PlayTo/PlaylistItem.cs b/Emby.Dlna/PlayTo/PlaylistItem.cs index b60e6a6fb..1e62b61e9 100644 --- a/Emby.Dlna/PlayTo/PlaylistItem.cs +++ b/Emby.Dlna/PlayTo/PlaylistItem.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.PlayTo { @@ -12,4 +12,4 @@ namespace Emby.Dlna.PlayTo public DeviceProfile Profile { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs index e2d6e43c0..aceb634e3 100644 --- a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs +++ b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs @@ -1,10 +1,9 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Session; -using System; using System.Globalization; using System.IO; using System.Linq; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Session; namespace Emby.Dlna.PlayTo { @@ -49,7 +48,7 @@ namespace Emby.Dlna.PlayTo return playlistItem; } - private bool IsSupported(DirectPlayProfile profile, Photo item) + private static bool IsSupported(DirectPlayProfile profile, Photo item) { var mediaPath = item.Path; diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index bfd163bf1..1ad99fac5 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -1,13 +1,13 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; -using Emby.Dlna.Common; using System; using System.Globalization; using System.IO; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using System.Threading; +using Emby.Dlna.Common; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; namespace Emby.Dlna.PlayTo { @@ -25,10 +25,10 @@ namespace Emby.Dlna.PlayTo _config = config; } - public async Task SendCommandAsync(string baseUrl, - DeviceService service, - string command, - string postData, + public async Task SendCommandAsync(string baseUrl, + DeviceService service, + string command, + string postData, bool logRequest = true, string header = null) { @@ -47,7 +47,7 @@ namespace Emby.Dlna.PlayTo } } - private string NormalizeServiceUrl(string baseUrl, string serviceUrl) + private static string NormalizeServiceUrl(string baseUrl, string serviceUrl) { // If it's already a complete url, don't stick anything onto the front of it if (serviceUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase)) @@ -62,12 +62,12 @@ namespace Emby.Dlna.PlayTo } private readonly CultureInfo _usCulture = new CultureInfo("en-US"); - - public async Task SubscribeAsync(string url, - string ip, - int port, - string localIp, - int eventport, + + public async Task SubscribeAsync(string url, + string ip, + int port, + string localIp, + int eventport, int timeOut = 3600) { var options = new HttpRequestOptions @@ -121,9 +121,9 @@ namespace Emby.Dlna.PlayTo } } - private Task PostSoapDataAsync(string url, - string soapAction, - string postData, + private Task PostSoapDataAsync(string url, + string soapAction, + string postData, string header, bool logRequest, CancellationToken cancellationToken) diff --git a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs b/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs index 93d306a17..9f1690b04 100644 --- a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs +++ b/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs @@ -1,4 +1,4 @@ -namespace Emby.Dlna.PlayTo +namespace Emby.Dlna.PlayTo { public enum TRANSPORTSTATE { @@ -8,4 +8,4 @@ PAUSED_PLAYBACK, PAUSED } -} \ No newline at end of file +} diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 9e055f792..b96fa43e5 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -1,8 +1,8 @@ -using System; -using Emby.Dlna.Common; +using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; +using Emby.Dlna.Common; using Emby.Dlna.Ssdp; namespace Emby.Dlna.PlayTo @@ -12,27 +12,15 @@ namespace Emby.Dlna.PlayTo private List _stateVariables = new List(); public List StateVariables { - get - { - return _stateVariables; - } - set - { - _stateVariables = value; - } + get => _stateVariables; + set => _stateVariables = value; } private List _serviceActions = new List(); public List ServiceActions { - get - { - return _serviceActions; - } - set - { - _serviceActions = value; - } + get => _serviceActions; + set => _serviceActions = value; } public static TransportCommands Create(XDocument document) @@ -80,7 +68,7 @@ namespace Emby.Dlna.PlayTo { if (container == null) { - throw new ArgumentNullException("container"); + throw new ArgumentNullException(nameof(container)); } return new Argument @@ -171,7 +159,7 @@ namespace Emby.Dlna.PlayTo if (state != null) { var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ?? - state.AllowedValues.FirstOrDefault() ?? + state.AllowedValues.FirstOrDefault() ?? value; return string.Format("<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}", argument.Name, state.DataType ?? "string", sendValue); diff --git a/Emby.Dlna/PlayTo/TransportStateEventArgs.cs b/Emby.Dlna/PlayTo/TransportStateEventArgs.cs index c6a96f58c..7dcd39e10 100644 --- a/Emby.Dlna/PlayTo/TransportStateEventArgs.cs +++ b/Emby.Dlna/PlayTo/TransportStateEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { diff --git a/Emby.Dlna/PlayTo/UpnpContainer.cs b/Emby.Dlna/PlayTo/UpnpContainer.cs index 5bfc56bff..943e0347b 100644 --- a/Emby.Dlna/PlayTo/UpnpContainer.cs +++ b/Emby.Dlna/PlayTo/UpnpContainer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Xml.Linq; using Emby.Dlna.Ssdp; @@ -10,7 +10,7 @@ namespace Emby.Dlna.PlayTo { if (container == null) { - throw new ArgumentNullException("container"); + throw new ArgumentNullException(nameof(container)); } return new uBaseObject diff --git a/Emby.Dlna/PlayTo/uBaseObject.cs b/Emby.Dlna/PlayTo/uBaseObject.cs index 1de46317e..f29a126df 100644 --- a/Emby.Dlna/PlayTo/uBaseObject.cs +++ b/Emby.Dlna/PlayTo/uBaseObject.cs @@ -1,8 +1,8 @@ -using System; +using System; namespace Emby.Dlna.PlayTo { - public class uBaseObject + public class uBaseObject { public string Id { get; set; } @@ -26,7 +26,7 @@ namespace Emby.Dlna.PlayTo { if (obj == null) { - throw new ArgumentNullException("obj"); + throw new ArgumentNullException(nameof(obj)); } return string.Equals(Id, obj.Id); diff --git a/Emby.Dlna/PlayTo/uParser.cs b/Emby.Dlna/PlayTo/uParser.cs index 5caf83a9a..3a0ffffd4 100644 --- a/Emby.Dlna/PlayTo/uParser.cs +++ b/Emby.Dlna/PlayTo/uParser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; @@ -20,13 +20,13 @@ namespace Emby.Dlna.PlayTo if (document == null) return list; - + var item = (from result in document.Descendants("Result") select result).FirstOrDefault(); if (item == null) return list; - var uPnpResponse = XElement.Parse((String)item); + var uPnpResponse = XElement.Parse((string)item); var uObjects = from container in uPnpResponse.Elements(uPnpNamespaces.containers) select new uParserObject { Element = container }; diff --git a/Emby.Dlna/PlayTo/uParserObject.cs b/Emby.Dlna/PlayTo/uParserObject.cs index 4e75adf1f..87a7f69c6 100644 --- a/Emby.Dlna/PlayTo/uParserObject.cs +++ b/Emby.Dlna/PlayTo/uParserObject.cs @@ -1,4 +1,4 @@ -using System.Xml.Linq; +using System.Xml.Linq; namespace Emby.Dlna.PlayTo { @@ -6,4 +6,4 @@ namespace Emby.Dlna.PlayTo { public XElement Element { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/PlayTo/uPnpNamespaces.cs b/Emby.Dlna/PlayTo/uPnpNamespaces.cs index 81acb5e41..7132ecd15 100644 --- a/Emby.Dlna/PlayTo/uPnpNamespaces.cs +++ b/Emby.Dlna/PlayTo/uPnpNamespaces.cs @@ -1,4 +1,4 @@ -using System.Xml.Linq; +using System.Xml.Linq; namespace Emby.Dlna.PlayTo { diff --git a/Emby.Dlna/Profiles/DefaultProfile.cs b/Emby.Dlna/Profiles/DefaultProfile.cs index 1295c2f9a..ea50bd4a7 100644 --- a/Emby.Dlna/Profiles/DefaultProfile.cs +++ b/Emby.Dlna/Profiles/DefaultProfile.cs @@ -1,7 +1,5 @@ -using MediaBrowser.Model.Dlna; using System.Linq; -using System.Xml.Serialization; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/DenonAvrProfile.cs b/Emby.Dlna/Profiles/DenonAvrProfile.cs index b8a44396a..a73885191 100644 --- a/Emby.Dlna/Profiles/DenonAvrProfile.cs +++ b/Emby.Dlna/Profiles/DenonAvrProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/DirectTvProfile.cs b/Emby.Dlna/Profiles/DirectTvProfile.cs index 4243c1c9d..317c0976a 100644 --- a/Emby.Dlna/Profiles/DirectTvProfile.cs +++ b/Emby.Dlna/Profiles/DirectTvProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs index c1d1eede2..d501cce0d 100644 --- a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs +++ b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/Foobar2000Profile.cs b/Emby.Dlna/Profiles/Foobar2000Profile.cs index 69a5d05dd..947194bce 100644 --- a/Emby.Dlna/Profiles/Foobar2000Profile.cs +++ b/Emby.Dlna/Profiles/Foobar2000Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/LgTvProfile.cs b/Emby.Dlna/Profiles/LgTvProfile.cs index 79cf2ebfd..145685ab1 100644 --- a/Emby.Dlna/Profiles/LgTvProfile.cs +++ b/Emby.Dlna/Profiles/LgTvProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs index ffb735d8d..3f0bb4263 100644 --- a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs +++ b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs @@ -1,4 +1,3 @@ -using System.Xml.Serialization; using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/MarantzProfile.cs b/Emby.Dlna/Profiles/MarantzProfile.cs index b5b486a9c..162e284be 100644 --- a/Emby.Dlna/Profiles/MarantzProfile.cs +++ b/Emby.Dlna/Profiles/MarantzProfile.cs @@ -1,4 +1,3 @@ -using System.Xml.Serialization; using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs index 441933efa..53cae4e2f 100644 --- a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs +++ b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { @@ -14,9 +13,9 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"MediaMonkey", + FriendlyName = @"MediaMonkey", - Headers = new[] + Headers = new[] { new HttpHeaderInfo { diff --git a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs index 53d6a62bb..5f31ec484 100644 --- a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs +++ b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { @@ -218,4 +217,4 @@ namespace Emby.Dlna.Profiles }; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/Profiles/PopcornHourProfile.cs b/Emby.Dlna/Profiles/PopcornHourProfile.cs index b91089b1b..aefe8c44f 100644 --- a/Emby.Dlna/Profiles/PopcornHourProfile.cs +++ b/Emby.Dlna/Profiles/PopcornHourProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs index b55146ffd..51a1c8173 100644 --- a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs +++ b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { @@ -363,4 +362,4 @@ namespace Emby.Dlna.Profiles }; } } -} \ No newline at end of file +} diff --git a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs index d27a0e782..f840cfb34 100644 --- a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs +++ b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs @@ -1,4 +1,3 @@ -using System.Xml.Serialization; using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs index dd2ca7a7d..2af1d3b50 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs index 69a2f2b61..3de0b5192 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs index ef443e56e..889484bea 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs index 92e5cb086..acb90bd01 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs index 2bf65351e..e1808b205 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs index 75382067f..f8e8faa76 100644 --- a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { @@ -41,7 +40,7 @@ namespace Emby.Dlna.Profiles EnableSingleAlbumArtLimit = true; EnableAlbumArtInDidl = true; - + TranscodingProfiles = new[] { new TranscodingProfile diff --git a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs index 75fefa9a8..111f36e9b 100644 --- a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs index 1d55d91f9..d5efe4270 100644 --- a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs index 555ce419b..3b0228694 100644 --- a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs index b6e5bbea5..e860eae34 100644 --- a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyPs3Profile.cs b/Emby.Dlna/Profiles/SonyPs3Profile.cs index fc69d2dd3..88d064695 100644 --- a/Emby.Dlna/Profiles/SonyPs3Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs3Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/SonyPs4Profile.cs b/Emby.Dlna/Profiles/SonyPs4Profile.cs index 9b444ec24..499cf8803 100644 --- a/Emby.Dlna/Profiles/SonyPs4Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs4Profile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/WdtvLiveProfile.cs b/Emby.Dlna/Profiles/WdtvLiveProfile.cs index bab557674..bf7b1ab47 100644 --- a/Emby.Dlna/Profiles/WdtvLiveProfile.cs +++ b/Emby.Dlna/Profiles/WdtvLiveProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { @@ -17,7 +16,7 @@ namespace Emby.Dlna.Profiles { ModelName = "WD TV", - Headers = new [] + Headers = new[] { new HttpHeaderInfo {Name = "User-Agent", Value = "alphanetworks", Match = HeaderMatchType.Substring}, new HttpHeaderInfo diff --git a/Emby.Dlna/Profiles/XboxOneProfile.cs b/Emby.Dlna/Profiles/XboxOneProfile.cs index 46740cb31..710b891e3 100644 --- a/Emby.Dlna/Profiles/XboxOneProfile.cs +++ b/Emby.Dlna/Profiles/XboxOneProfile.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Dlna; -using System.Xml.Serialization; +using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles { diff --git a/Emby.Dlna/Profiles/Xml/Default.xml b/Emby.Dlna/Profiles/Xml/Default.xml index 9b862fec3..daac4135a 100644 --- a/Emby.Dlna/Profiles/Xml/Default.xml +++ b/Emby.Dlna/Profiles/Xml/Default.xml @@ -1,5 +1,6 @@ - + Generic Device Jellyfin https://github.com/jellyfin/jellyfin diff --git a/Emby.Dlna/Profiles/Xml/Denon AVR.xml b/Emby.Dlna/Profiles/Xml/Denon AVR.xml index 599726c51..c76cd9a89 100644 --- a/Emby.Dlna/Profiles/Xml/Denon AVR.xml +++ b/Emby.Dlna/Profiles/Xml/Denon AVR.xml @@ -1,5 +1,6 @@ - + Denon AVR Denon:\[AVR:.* diff --git a/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml b/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml index e640e86bf..f2ce68ab5 100644 --- a/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml +++ b/Emby.Dlna/Profiles/Xml/DirecTV HD-DVR.xml @@ -1,5 +1,6 @@ - + DirecTV HD-DVR ^DIRECTV.*$ diff --git a/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml b/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml index 615774adf..5ff497560 100644 --- a/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml +++ b/Emby.Dlna/Profiles/Xml/Dish Hopper-Joey.xml @@ -1,5 +1,6 @@ - + Dish Hopper-Joey Echostar Technologies LLC diff --git a/Emby.Dlna/Profiles/Xml/LG Smart TV.xml b/Emby.Dlna/Profiles/Xml/LG Smart TV.xml index 21dccf531..a0f0e0ee8 100644 --- a/Emby.Dlna/Profiles/Xml/LG Smart TV.xml +++ b/Emby.Dlna/Profiles/Xml/LG Smart TV.xml @@ -1,5 +1,6 @@ - + LG Smart TV LG.* diff --git a/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml b/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml index ac081bba3..55910c77f 100644 --- a/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml +++ b/Emby.Dlna/Profiles/Xml/Linksys DMA2100.xml @@ -1,5 +1,6 @@ - + Linksys DMA2100 DMA2100us diff --git a/Emby.Dlna/Profiles/Xml/Marantz.xml b/Emby.Dlna/Profiles/Xml/Marantz.xml index 2bbdecde8..a6345ab3f 100644 --- a/Emby.Dlna/Profiles/Xml/Marantz.xml +++ b/Emby.Dlna/Profiles/Xml/Marantz.xml @@ -1,5 +1,6 @@ - + Marantz Marantz diff --git a/Emby.Dlna/Profiles/Xml/MediaMonkey.xml b/Emby.Dlna/Profiles/Xml/MediaMonkey.xml index 955c30e85..2c2c3a1de 100644 --- a/Emby.Dlna/Profiles/Xml/MediaMonkey.xml +++ b/Emby.Dlna/Profiles/Xml/MediaMonkey.xml @@ -1,5 +1,6 @@ - + MediaMonkey MediaMonkey diff --git a/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml b/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml index 0da0e0926..934f0550d 100644 --- a/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml +++ b/Emby.Dlna/Profiles/Xml/Panasonic Viera.xml @@ -1,5 +1,6 @@ - + Panasonic Viera VIERA diff --git a/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml b/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml index 775d40b74..eab220fae 100644 --- a/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml +++ b/Emby.Dlna/Profiles/Xml/Popcorn Hour.xml @@ -1,5 +1,6 @@ - + Popcorn Hour Jellyfin https://github.com/jellyfin/jellyfin @@ -88,4 +89,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml b/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml index 1362d8c38..3e6f56e5b 100644 --- a/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml +++ b/Emby.Dlna/Profiles/Xml/Samsung Smart TV.xml @@ -1,5 +1,6 @@ - + Samsung Smart TV samsung.com @@ -124,4 +125,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml b/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml index dac2fdea4..74240b843 100644 --- a/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml +++ b/Emby.Dlna/Profiles/Xml/Sharp Smart TV.xml @@ -1,5 +1,6 @@ - + Sharp Smart TV Sharp @@ -56,4 +57,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2013.xml b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2013.xml index 0cb0c52c2..2c5614883 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2013.xml +++ b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2013.xml @@ -1,5 +1,6 @@ - + Sony Blu-ray Player 2013 BDP-2013 @@ -83,4 +84,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2014.xml b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2014.xml index 602c54f61..44f9821b3 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2014.xml +++ b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2014.xml @@ -1,5 +1,6 @@ - + Sony Blu-ray Player 2014 BDP-2014 @@ -83,4 +84,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2015.xml b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2015.xml index 701aba85f..a7d17c1a0 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2015.xml +++ b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2015.xml @@ -1,5 +1,6 @@ - + Sony Blu-ray Player 2015 BDP-2015 @@ -81,4 +82,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2016.xml b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2016.xml index 5f9012678..b42b1e84f 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2016.xml +++ b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player 2016.xml @@ -1,5 +1,6 @@ - + Sony Blu-ray Player 2016 BDP-2016 @@ -81,4 +82,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player.xml b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player.xml index 765d5d5fe..46857caf0 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player.xml +++ b/Emby.Dlna/Profiles/Xml/Sony Blu-ray Player.xml @@ -1,5 +1,6 @@ - + Sony Blu-ray Player Blu-ray Disc Player @@ -111,4 +112,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml index d84531758..f20e9fcb6 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml @@ -1,5 +1,6 @@ - + Sony Bravia (2010) KDL-\d{2}[EHLNPB]X\d[01]\d.* @@ -129,4 +130,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml index 8e376fbf9..49819ccfd 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml @@ -1,5 +1,6 @@ - + Sony Bravia (2011) KDL-\d{2}([A-Z]X\d2\d|CX400).* @@ -135,4 +136,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml index 92a04dc7a..aaad7b342 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml @@ -1,5 +1,6 @@ - + Sony Bravia (2012) KDL-\d{2}[A-Z]X\d5(\d|G).* @@ -111,4 +112,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml index 953ac0a43..8e2e8dbaa 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml @@ -1,5 +1,6 @@ - + Sony Bravia (2013) KDL-\d{2}[WR][5689]\d{2}A.* @@ -110,4 +111,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml index 34afe7e6e..17a6135e1 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml @@ -1,5 +1,6 @@ - + Sony Bravia (2014) (KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).* @@ -110,4 +111,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml index d1afc162c..df385135c 100644 --- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml +++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml @@ -1,5 +1,6 @@ - + Sony PlayStation 3 PLAYSTATION 3 @@ -101,4 +102,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml index 090abe417..20f50f6b6 100644 --- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml +++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml @@ -1,5 +1,6 @@ - + Sony PlayStation 4 PLAYSTATION 4 @@ -104,4 +105,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/WDTV Live.xml b/Emby.Dlna/Profiles/Xml/WDTV Live.xml index db4ce4722..05380e33a 100644 --- a/Emby.Dlna/Profiles/Xml/WDTV Live.xml +++ b/Emby.Dlna/Profiles/Xml/WDTV Live.xml @@ -1,5 +1,6 @@ - + WDTV Live WD TV @@ -90,4 +91,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/Xbox One.xml b/Emby.Dlna/Profiles/Xml/Xbox One.xml index 40e05f7fc..5f5cf1af3 100644 --- a/Emby.Dlna/Profiles/Xml/Xbox One.xml +++ b/Emby.Dlna/Profiles/Xml/Xbox One.xml @@ -1,5 +1,6 @@ - + Xbox One Xbox One @@ -122,4 +123,4 @@ - \ No newline at end of file + diff --git a/Emby.Dlna/Profiles/Xml/foobar2000.xml b/Emby.Dlna/Profiles/Xml/foobar2000.xml index 19dc10e83..f3eedb35c 100644 --- a/Emby.Dlna/Profiles/Xml/foobar2000.xml +++ b/Emby.Dlna/Profiles/Xml/foobar2000.xml @@ -1,5 +1,6 @@ - + foobar2000 foobar diff --git a/Emby.Dlna/Properties/AssemblyInfo.cs b/Emby.Dlna/Properties/AssemblyInfo.cs index 6f924f9e9..9d3a22c97 100644 --- a/Emby.Dlna/Properties/AssemblyInfo.cs +++ b/Emby.Dlna/Properties/AssemblyInfo.cs @@ -1,17 +1,15 @@ -using System.Resources; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Resources; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Emby.Dlna2")] +[assembly: AssemblyTitle("Emby.Dlna")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Dlna2")] -[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] @@ -19,12 +17,10 @@ using System.Runtime.InteropServices; // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Emby.Dlna/Server/DescriptionXmlBuilder.cs b/Emby.Dlna/Server/DescriptionXmlBuilder.cs index 0c0c367e4..e0ecbee43 100644 --- a/Emby.Dlna/Server/DescriptionXmlBuilder.cs +++ b/Emby.Dlna/Server/DescriptionXmlBuilder.cs @@ -1,12 +1,11 @@ -using Emby.Dlna.Common; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Extensions; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Security; using System.Text; +using Emby.Dlna.Common; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Extensions; namespace Emby.Dlna.Server { @@ -24,12 +23,12 @@ namespace Emby.Dlna.Server { if (string.IsNullOrEmpty(serverUdn)) { - throw new ArgumentNullException("serverUdn"); + throw new ArgumentNullException(nameof(serverUdn)); } if (string.IsNullOrEmpty(serverAddress)) { - throw new ArgumentNullException("serverAddress"); + throw new ArgumentNullException(nameof(serverAddress)); } _profile = profile; @@ -39,10 +38,7 @@ namespace Emby.Dlna.Server _serverId = serverId; } - private bool EnableAbsoluteUrls - { - get { return false; } - } + private static bool EnableAbsoluteUrls => false; public string GetXml() { diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index ae094cc2f..5f78674b8 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -1,7 +1,3 @@ -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Dlna; -using Emby.Dlna.Server; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -9,9 +5,10 @@ using System.Linq; using System.Text; using System.Xml; using Emby.Dlna.Didl; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Xml; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.Service { @@ -88,7 +85,7 @@ namespace Emby.Dlna.Service StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); - using (XmlWriter writer = XmlWriter.Create(builder, settings)) + using (var writer = XmlWriter.Create(builder, settings)) { writer.WriteStartDocument(true); @@ -205,7 +202,7 @@ namespace Emby.Dlna.Service return result; } - private void ParseFirstBodyChild(XmlReader reader, IDictionary headers) + private void ParseFirstBodyChild(XmlReader reader, IDictionary headers) { reader.MoveToContent(); reader.Read(); @@ -229,7 +226,7 @@ namespace Emby.Dlna.Service { public string LocalName; public string NamespaceURI; - public IDictionary Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + public IDictionary Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); } protected abstract IEnumerable> GetResult(string methodName, IDictionary methodParams); diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs index 92b81a7ac..5359e94c4 100644 --- a/Emby.Dlna/Service/BaseService.cs +++ b/Emby.Dlna/Service/BaseService.cs @@ -1,6 +1,5 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Dlna; using Emby.Dlna.Eventing; +using MediaBrowser.Common.Net; using Microsoft.Extensions.Logging; namespace Emby.Dlna.Service @@ -14,7 +13,7 @@ namespace Emby.Dlna.Service protected BaseService(ILogger logger, IHttpClient httpClient) { Logger = logger; - HttpClient = httpClient; + HttpClient = httpClient; EventManager = new EventManager(Logger, HttpClient); } diff --git a/Emby.Dlna/Service/ControlErrorHandler.cs b/Emby.Dlna/Service/ControlErrorHandler.cs index a3cd77f0f..d5eb4a887 100644 --- a/Emby.Dlna/Service/ControlErrorHandler.cs +++ b/Emby.Dlna/Service/ControlErrorHandler.cs @@ -1,4 +1,3 @@ -using MediaBrowser.Controller.Dlna; using System; using System.IO; using System.Text; @@ -10,7 +9,7 @@ namespace Emby.Dlna.Service public class ControlErrorHandler { private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; - + public ControlResponse GetResponse(Exception ex) { var settings = new XmlWriterSettings @@ -21,7 +20,7 @@ namespace Emby.Dlna.Service StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); - using (XmlWriter writer = XmlWriter.Create(builder, settings)) + using (var writer = XmlWriter.Create(builder, settings)) { writer.WriteStartDocument(true); diff --git a/Emby.Dlna/Service/ServiceXmlBuilder.cs b/Emby.Dlna/Service/ServiceXmlBuilder.cs index c41f1b3be..bd1f0bf05 100644 --- a/Emby.Dlna/Service/ServiceXmlBuilder.cs +++ b/Emby.Dlna/Service/ServiceXmlBuilder.cs @@ -1,7 +1,6 @@ -using Emby.Dlna.Common; using System.Collections.Generic; -using System.Security; using System.Text; +using Emby.Dlna.Common; using Emby.Dlna.Server; namespace Emby.Dlna.Service @@ -28,7 +27,7 @@ namespace Emby.Dlna.Service return builder.ToString(); } - private void AppendActionList(StringBuilder builder, IEnumerable actions) + private static void AppendActionList(StringBuilder builder, IEnumerable actions) { builder.Append(""); @@ -59,7 +58,7 @@ namespace Emby.Dlna.Service builder.Append(""); } - private void AppendServiceStateTable(StringBuilder builder, IEnumerable stateVariables) + private static void AppendServiceStateTable(StringBuilder builder, IEnumerable stateVariables) { builder.Append(""); diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index d91f711d2..89a88705f 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -1,19 +1,12 @@ -using MediaBrowser.Common.Events; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Dlna; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Net; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; using Rssdp; using Rssdp.Infrastructure; @@ -59,9 +52,13 @@ namespace Emby.Dlna.Ssdp private readonly ISocketFactory _socketFactory; private ISsdpCommunicationsServer _commsServer; - public DeviceDiscovery(ILogger logger, IServerConfigurationManager config, ISocketFactory socketFactory, ITimerFactory timerFactory) + public DeviceDiscovery( + ILoggerFactory loggerFactory, + IServerConfigurationManager config, + ISocketFactory socketFactory, + ITimerFactory timerFactory) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(DeviceDiscovery)); _config = config; _socketFactory = socketFactory; _timerFactory = timerFactory; @@ -83,8 +80,8 @@ namespace Emby.Dlna.Ssdp { _deviceLocator = new SsdpDeviceLocator(_commsServer, _timerFactory); - // (Optional) Set the filter so we only see notifications for devices we care about - // (can be any search target value i.e device type, uuid value etc - any value that appears in the + // (Optional) Set the filter so we only see notifications for devices we care about + // (can be any search target value i.e device type, uuid value etc - any value that appears in the // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method). //_DeviceLocator.NotificationFilter = "upnp:rootdevice"; diff --git a/Emby.Dlna/Ssdp/Extensions.cs b/Emby.Dlna/Ssdp/Extensions.cs index 41a361515..c680c123e 100644 --- a/Emby.Dlna/Ssdp/Extensions.cs +++ b/Emby.Dlna/Ssdp/Extensions.cs @@ -1,6 +1,3 @@ -using System; -using System.Net; -using System.Threading.Tasks; using System.Xml.Linq; namespace Emby.Dlna.Ssdp diff --git a/Emby.Drawing.Skia/Emby.Drawing.Skia.csproj b/Emby.Drawing.Skia/Emby.Drawing.Skia.csproj deleted file mode 100644 index 7d6643d54..000000000 --- a/Emby.Drawing.Skia/Emby.Drawing.Skia.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - netstandard2.0 - false - - - - - - - - - - - - - - - - - - diff --git a/Emby.Drawing.Skia/Properties/AssemblyInfo.cs b/Emby.Drawing.Skia/Properties/AssemblyInfo.cs deleted file mode 100644 index c0dc7c5b4..000000000 --- a/Emby.Drawing.Skia/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Resources; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Emby.Drawing.Skia")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Drawing.Skia")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// \ No newline at end of file diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs deleted file mode 100644 index 7b819c2fd..000000000 --- a/Emby.Drawing/Common/ImageHeader.cs +++ /dev/null @@ -1,238 +0,0 @@ -using MediaBrowser.Model.Drawing; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.Common -{ - /// - /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349 - /// http://www.codeproject.com/Articles/35978/Reading-Image-Headers-to-Get-Width-and-Height - /// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic - /// to load the image using new Bitmap if reading the headers fails - /// - public static class ImageHeader - { - /// - /// The error message - /// - const string ErrorMessage = "Could not recognize image format."; - - /// - /// The image format decoders - /// - private static readonly KeyValuePair>[] ImageFormatDecoders = new Dictionary> - { - { new byte[] { 0x42, 0x4D }, DecodeBitmap }, - { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, - { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, - { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, - { new byte[] { 0xff, 0xd8 }, DecodeJfif } - - }.ToArray(); - - private static readonly int MaxMagicBytesLength = ImageFormatDecoders.Select(i => i.Key.Length).OrderByDescending(i => i).First(); - - private static string[] SupportedExtensions = new string[] { ".jpg", ".jpeg", ".png", ".gif" }; - - /// - /// Gets the dimensions of an image. - /// - /// The path of the image to get the dimensions of. - /// The logger. - /// The file system. - /// The dimensions of the specified image. - /// The image was of an unrecognised format. - public static ImageSize GetDimensions(string path, ILogger logger, IFileSystem fileSystem) - { - var extension = Path.GetExtension(path); - - if (string.IsNullOrEmpty(extension)) - { - throw new ArgumentException("ImageHeader doesn't support image file"); - } - if (!SupportedExtensions.Contains(extension)) - { - throw new ArgumentException("ImageHeader doesn't support " + extension); - } - - using (var fs = fileSystem.OpenRead(path)) - { - using (var binaryReader = new BinaryReader(fs)) - { - return GetDimensions(binaryReader); - } - } - } - - /// - /// Gets the dimensions of an image. - /// - /// The binary reader. - /// Size. - /// binaryReader - /// The image was of an unrecognized format. - private static ImageSize GetDimensions(BinaryReader binaryReader) - { - var magicBytes = new byte[MaxMagicBytesLength]; - - for (var i = 0; i < MaxMagicBytesLength; i += 1) - { - magicBytes[i] = binaryReader.ReadByte(); - - foreach (var kvPair in ImageFormatDecoders) - { - if (StartsWith(magicBytes, kvPair.Key)) - { - return kvPair.Value(binaryReader); - } - } - } - - throw new ArgumentException(ErrorMessage, "binaryReader"); - } - - /// - /// Startses the with. - /// - /// The this bytes. - /// The that bytes. - /// true if XXXX, false otherwise - private static bool StartsWith(byte[] thisBytes, byte[] thatBytes) - { - for (int i = 0; i < thatBytes.Length; i += 1) - { - if (thisBytes[i] != thatBytes[i]) - { - return false; - } - } - - return true; - } - - /// - /// Reads the little endian int16. - /// - /// The binary reader. - /// System.Int16. - private static short ReadLittleEndianInt16(BinaryReader binaryReader) - { - var bytes = new byte[sizeof(short)]; - - for (int i = 0; i < sizeof(short); i += 1) - { - bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); - } - return BitConverter.ToInt16(bytes, 0); - } - - /// - /// Reads the little endian int32. - /// - /// The binary reader. - /// System.Int32. - private static int ReadLittleEndianInt32(BinaryReader binaryReader) - { - var bytes = new byte[sizeof(int)]; - for (int i = 0; i < sizeof(int); i += 1) - { - bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); - } - return BitConverter.ToInt32(bytes, 0); - } - - /// - /// Decodes the bitmap. - /// - /// The binary reader. - /// Size. - private static ImageSize DecodeBitmap(BinaryReader binaryReader) - { - binaryReader.ReadBytes(16); - int width = binaryReader.ReadInt32(); - int height = binaryReader.ReadInt32(); - return new ImageSize - { - Width = width, - Height = height - }; - } - - /// - /// Decodes the GIF. - /// - /// The binary reader. - /// Size. - private static ImageSize DecodeGif(BinaryReader binaryReader) - { - int width = binaryReader.ReadInt16(); - int height = binaryReader.ReadInt16(); - return new ImageSize - { - Width = width, - Height = height - }; - } - - /// - /// Decodes the PNG. - /// - /// The binary reader. - /// Size. - private static ImageSize DecodePng(BinaryReader binaryReader) - { - binaryReader.ReadBytes(8); - int width = ReadLittleEndianInt32(binaryReader); - int height = ReadLittleEndianInt32(binaryReader); - return new ImageSize - { - Width = width, - Height = height - }; - } - - /// - /// Decodes the jfif. - /// - /// The binary reader. - /// Size. - /// - private static ImageSize DecodeJfif(BinaryReader binaryReader) - { - while (binaryReader.ReadByte() == 0xff) - { - byte marker = binaryReader.ReadByte(); - short chunkLength = ReadLittleEndianInt16(binaryReader); - if (marker == 0xc0) - { - binaryReader.ReadByte(); - int height = ReadLittleEndianInt16(binaryReader); - int width = ReadLittleEndianInt16(binaryReader); - return new ImageSize - { - Width = width, - Height = height - }; - } - - if (chunkLength < 0) - { - var uchunkLength = (ushort)chunkLength; - binaryReader.ReadBytes(uchunkLength - 2); - } - else - { - binaryReader.ReadBytes(chunkLength - 2); - } - } - - throw new ArgumentException(ErrorMessage); - } - } -} diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 5ffaaed27..c36d42194 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -1,17 +1,24 @@ - - - - - - - - - - + netstandard2.0 false + + + + + + + + + + + + + + + + diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 6a67be56d..c750b60e2 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -1,27 +1,24 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using Emby.Drawing.Common; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Threading; +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; +using SkiaSharp; namespace Emby.Drawing { @@ -48,106 +45,83 @@ namespace Emby.Drawing private readonly ILogger _logger; private readonly IFileSystem _fileSystem; - private readonly IJsonSerializer _jsonSerializer; private readonly IServerApplicationPaths _appPaths; private IImageEncoder _imageEncoder; private readonly Func _libraryManager; private readonly Func _mediaEncoder; - public ImageProcessor(ILogger logger, + public ImageProcessor( + ILoggerFactory loggerFactory, IServerApplicationPaths appPaths, IFileSystem fileSystem, - IJsonSerializer jsonSerializer, IImageEncoder imageEncoder, - Func libraryManager, ITimerFactory timerFactory, Func mediaEncoder) + Func libraryManager, + Func mediaEncoder) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(ImageProcessor)); _fileSystem = fileSystem; - _jsonSerializer = jsonSerializer; _imageEncoder = imageEncoder; _libraryManager = libraryManager; _mediaEncoder = mediaEncoder; _appPaths = appPaths; - ImageEnhancers = new IImageEnhancer[] { }; + ImageEnhancers = Array.Empty(); + ImageHelper.ImageProcessor = this; } public IImageEncoder ImageEncoder { - get { return _imageEncoder; } + get => _imageEncoder; set { if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } _imageEncoder = value; } } - public string[] SupportedInputFormats - { - get + public string[] SupportedInputFormats => + new string[] { - return new string[] - { - "tiff", - "tif", - "jpeg", - "jpg", - "png", - "aiff", - "cr2", - "crw", + "tiff", + "tif", + "jpeg", + "jpg", + "png", + "aiff", + "cr2", + "crw", - // Remove until supported - //"nef", - "orf", - "pef", - "arw", - "webp", - "gif", - "bmp", - "erf", - "raf", - "rw2", - "nrw", - "dng", - "ico", - "astc", - "ktx", - "pkm", - "wbmp" - }; - } - } + // Remove until supported + //"nef", + "orf", + "pef", + "arw", + "webp", + "gif", + "bmp", + "erf", + "raf", + "rw2", + "nrw", + "dng", + "ico", + "astc", + "ktx", + "pkm", + "wbmp" + }; - public bool SupportsImageCollageCreation - { - get - { - return _imageEncoder.SupportsImageCollageCreation; - } - } + public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation; - private string ResizedImageCachePath - { - get - { - return Path.Combine(_appPaths.ImageCachePath, "resized-images"); - } - } + private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images"); - private string EnhancedImageCachePath - { - get - { - return Path.Combine(_appPaths.ImageCachePath, "enhanced-images"); - } - } + private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images"); public void AddParts(IEnumerable enhancers) { @@ -169,21 +143,19 @@ namespace Emby.Drawing return _imageEncoder.SupportedOutputFormats; } - private readonly string[] TransparentImageTypes = new string[] { ".png", ".webp", ".gif" }; + private static readonly string[] TransparentImageTypes = new string[] { ".png", ".webp", ".gif" }; public bool SupportsTransparency(string path) - { - return TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty); - } + => TransparentImageTypes.Contains(Path.GetExtension(path).ToLower()); - public async Task> ProcessImage(ImageProcessingOptions options) + public async Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options) { if (options == null) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } - var originalImage = options.Image; - var item = options.Item; + ItemImageInfo originalImage = options.Image; + BaseItem item = options.Item; if (!originalImage.IsLocalFile) { @@ -194,19 +166,23 @@ namespace Emby.Drawing originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); } - var originalImagePath = originalImage.Path; - var dateModified = originalImage.DateModified; - var originalImageSize = originalImage.Width > 0 && originalImage.Height > 0 ? new ImageSize(originalImage.Width, originalImage.Height) : (ImageSize?)null; + string originalImagePath = originalImage.Path; + DateTime dateModified = originalImage.DateModified; + ImageSize? originalImageSize = null; + if (originalImage.Width > 0 && originalImage.Height > 0) + { + originalImageSize = new ImageSize(originalImage.Width, originalImage.Height); + } if (!_imageEncoder.SupportsImageEncoding) { - return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); + return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false); - originalImagePath = supportedImageInfo.Item1; - dateModified = supportedImageInfo.Item2; - var requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath) ?? string.Empty); + originalImagePath = supportedImageInfo.path; + dateModified = supportedImageInfo.dateModified; + bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath)); if (options.Enhancers.Length > 0) { @@ -220,20 +196,18 @@ namespace Emby.Drawing DateModified = dateModified, Type = originalImage.Type, Path = originalImagePath - }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false); - originalImagePath = tuple.Item1; - dateModified = tuple.Item2; - requiresTransparency = tuple.Item3; + originalImagePath = tuple.path; + dateModified = tuple.dateModified; + requiresTransparency = tuple.transparent; // TODO: Get this info originalImageSize = null; } - var photo = item as Photo; - var autoOrient = false; + bool autoOrient = false; ImageOrientation? orientation = null; - if (photo != null) + if (item is Photo photo) { if (photo.Orientation.HasValue) { @@ -254,26 +228,18 @@ namespace Emby.Drawing if (options.HasDefaultOptions(originalImagePath, originalImageSize) && (!autoOrient || !options.RequiresAutoOrientation)) { // Just spit out the original file if all the options are default - return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); + return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - //ImageSize? originalImageSize = GetSavedImageSize(originalImagePath, dateModified); - //if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient) - //{ - // // Just spit out the original file if all the options are default - // _logger.LogInformation("Returning original image {0}", originalImagePath); - // return new ValueTuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); - //} + ImageSize newSize = ImageHelper.GetNewImageSize(options, null); + int quality = options.Quality; - var newSize = ImageHelper.GetNewImageSize(options, null); - var quality = options.Quality; - - var outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); - var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); + ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); + string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); CheckDisposed(); - var lockInfo = GetLock(cacheFilePath); + LockInfo lockInfo = GetLock(cacheFilePath); await lockInfo.Lock.WaitAsync().ConfigureAwait(false); @@ -286,17 +252,15 @@ namespace Emby.Drawing options.CropWhiteSpace = false; } - var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat); + string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat); if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { - return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); + return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - - return new Tuple(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)); } - return new Tuple(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)); + return (cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)); } catch (ArgumentOutOfRangeException ex) { @@ -305,7 +269,7 @@ namespace Emby.Drawing _logger.LogError(ex, "Error encoding image"); #endif // Just spit out the original file if all the options are default - return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); + return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } catch (Exception ex) { @@ -313,7 +277,7 @@ namespace Emby.Drawing _logger.LogError(ex, "Error encoding image"); // Just spit out the original file if all the options are default - return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); + return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } finally { @@ -349,42 +313,17 @@ namespace Emby.Drawing return ImageFormat.Jpg; } - private void CopyFile(string src, string destination) - { - try - { - _fileSystem.CopyFile(src, destination, true); - } - catch - { - - } - } - private string GetMimeType(ImageFormat format, string path) { - if (format == ImageFormat.Bmp) + switch(format) { - return MimeTypes.GetMimeType("i.bmp"); + case ImageFormat.Bmp: return MimeTypes.GetMimeType("i.bmp"); + case ImageFormat.Gif: return MimeTypes.GetMimeType("i.gif"); + case ImageFormat.Jpg: return MimeTypes.GetMimeType("i.jpg"); + case ImageFormat.Png: return MimeTypes.GetMimeType("i.png"); + case ImageFormat.Webp: return MimeTypes.GetMimeType("i.webp"); + default: return MimeTypes.GetMimeType(path); } - if (format == ImageFormat.Gif) - { - return MimeTypes.GetMimeType("i.gif"); - } - if (format == ImageFormat.Jpg) - { - return MimeTypes.GetMimeType("i.jpg"); - } - if (format == ImageFormat.Png) - { - return MimeTypes.GetMimeType("i.png"); - } - if (format == ImageFormat.Webp) - { - return MimeTypes.GetMimeType("i.webp"); - } - - return MimeTypes.GetMimeType(path); } /// @@ -397,17 +336,12 @@ namespace Emby.Drawing /// private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer) { - var filename = originalPath; - - filename += "width=" + outputSize.Width; - - filename += "height=" + outputSize.Height; - - filename += "quality=" + quality; - - filename += "datemodified=" + dateModified.Ticks; - - filename += "f=" + format; + var filename = originalPath + + "width=" + outputSize.Width + + "height=" + outputSize.Height + + "quality=" + quality + + "datemodified=" + dateModified.Ticks + + "f=" + format; if (addPlayedIndicator) { @@ -445,28 +379,22 @@ namespace Emby.Drawing } public ImageSize GetImageSize(BaseItem item, ItemImageInfo info) - { - return GetImageSize(item, info, false, true); - } + => GetImageSize(item, info, true); - public ImageSize GetImageSize(BaseItem item, ItemImageInfo info, bool allowSlowMethods, bool updateItem) + public ImageSize GetImageSize(BaseItem item, ItemImageInfo info, bool updateItem) { - var width = info.Width; - var height = info.Height; + int width = info.Width; + int height = info.Height; if (height > 0 && width > 0) { - return new ImageSize - { - Width = width, - Height = height - }; + return new ImageSize(width, height); } - var path = info.Path; - _logger.LogInformation("Getting image size for item {0} {1}", item.GetType().Name, path); + string path = info.Path; + _logger.LogInformation("Getting image size for item {ItemType} {Path}", item.GetType().Name, path); - var size = GetImageSize(path, allowSlowMethods); + var size = GetImageSize(path); info.Height = Convert.ToInt32(size.Height); info.Width = Convert.ToInt32(size.Width); @@ -479,34 +407,22 @@ namespace Emby.Drawing return size; } - public ImageSize GetImageSize(string path) - { - return GetImageSize(path, true); - } - /// /// Gets the size of the image. /// - private ImageSize GetImageSize(string path, bool allowSlowMethod) + public ImageSize GetImageSize(string path) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } - try + using (var s = new SKFileStream(path)) + using (var codec = SKCodec.Create(s)) { - return ImageHeader.GetDimensions(path, _logger, _fileSystem); + var info = codec.Info; + return new ImageSize(info.Width, info.Height); } - catch - { - if (!allowSlowMethod) - { - throw; - } - } - - return _imageEncoder.GetImageSize(path); } /// @@ -515,7 +431,7 @@ namespace Emby.Drawing /// The item. /// The image. /// Guid. - /// item + /// item public string GetImageCacheTag(BaseItem item, ItemImageInfo image) { var supportedEnhancers = GetSupportedEnhancers(item, image.Type); @@ -547,12 +463,12 @@ namespace Emby.Drawing /// The image. /// The image enhancers. /// Guid. - /// item + /// item public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers) { - var originalImagePath = image.Path; - var dateModified = image.DateModified; - var imageType = image.Type; + string originalImagePath = image.Path; + DateTime dateModified = image.DateModified; + ImageType imageType = image.Type; // Optimization if (imageEnhancers.Length == 0) @@ -564,28 +480,28 @@ namespace Emby.Drawing var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList(); cacheKeys.Add(originalImagePath + dateModified.Ticks); - return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N"); + return string.Join("|", cacheKeys).GetMD5().ToString("N"); } - private async Task> GetSupportedImage(string originalImagePath, DateTime dateModified) + private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified) { - var inputFormat = (Path.GetExtension(originalImagePath) ?? string.Empty) + var inputFormat = Path.GetExtension(originalImagePath) .TrimStart('.') .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase); // These are just jpg files renamed as tbn if (string.Equals(inputFormat, "tbn", StringComparison.OrdinalIgnoreCase)) { - return new ValueTuple(originalImagePath, dateModified); + return (originalImagePath, dateModified); } if (!_imageEncoder.SupportedInputFormats.Contains(inputFormat, StringComparer.OrdinalIgnoreCase)) { try { - var filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N"); + string filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N"); - var cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png"; + string cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png"; var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension); var file = _fileSystem.GetFileInfo(outputPath); @@ -603,11 +519,11 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.LogError(ex, "Image conversion failed for {originalImagePath}", originalImagePath); + _logger.LogError(ex, "Image conversion failed for {Path}", originalImagePath); } } - return new ValueTuple(originalImagePath, dateModified); + return (originalImagePath, dateModified); } /// @@ -621,16 +537,17 @@ namespace Emby.Drawing { var enhancers = GetSupportedEnhancers(item, imageType); - var imageInfo = item.GetImageInfo(imageType, imageIndex); + ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex); - var inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path); + bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path); var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None); - return result.Item1; + return result.path; } - private async Task> GetEnhancedImage(ItemImageInfo image, + private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage( + ItemImageInfo image, bool inputImageSupportsTransparency, BaseItem item, int imageIndex, @@ -648,14 +565,14 @@ namespace Emby.Drawing // Enhance if we have enhancers var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); - var enhancedImagePath = enhancedImageInfo.Item1; + string enhancedImagePath = enhancedImageInfo.path; // If the path changed update dateModified if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { - var treatmentRequiresTransparency = enhancedImageInfo.Item2; + var treatmentRequiresTransparency = enhancedImageInfo.transparent; - return new ValueTuple(enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); + return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); } } catch (Exception ex) @@ -663,7 +580,7 @@ namespace Emby.Drawing _logger.LogError(ex, "Error enhancing image"); } - return new ValueTuple(originalImagePath, dateModified, inputImageSupportsTransparency); + return (originalImagePath, dateModified, inputImageSupportsTransparency); } /// @@ -681,7 +598,8 @@ namespace Emby.Drawing /// or /// item /// - private async Task> GetEnhancedImageInternal(string originalImagePath, + private async Task<(string path, bool transparent)> GetEnhancedImageInternal( + string originalImagePath, BaseItem item, ImageType imageType, int imageIndex, @@ -691,12 +609,12 @@ namespace Emby.Drawing { if (string.IsNullOrEmpty(originalImagePath)) { - throw new ArgumentNullException("originalImagePath"); + throw new ArgumentNullException(nameof(originalImagePath)); } if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } var treatmentRequiresTransparency = false; @@ -709,13 +627,13 @@ namespace Emby.Drawing } // All enhanced images are saved as png to allow transparency - var cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ? + string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ? ".webp" : (treatmentRequiresTransparency ? ".png" : ".jpg"); - var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension); + string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension); - var lockInfo = GetLock(enhancedImagePath); + LockInfo lockInfo = GetLock(enhancedImagePath); await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -724,14 +642,14 @@ namespace Emby.Drawing // Check again in case of contention if (_fileSystem.FileExists(enhancedImagePath)) { - return new ValueTuple(enhancedImagePath, treatmentRequiresTransparency); + return (enhancedImagePath, treatmentRequiresTransparency); } _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(enhancedImagePath)); await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false); - return new ValueTuple(enhancedImagePath, treatmentRequiresTransparency); + return (enhancedImagePath, treatmentRequiresTransparency); } finally { @@ -749,7 +667,7 @@ namespace Emby.Drawing /// Type of the image. /// Index of the image. /// Task{EnhancedImage}. - private async Task ExecuteImageEnhancers(IEnumerable imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex) + private static async Task ExecuteImageEnhancers(IEnumerable imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex) { // Run the enhancers sequentially in order of priority foreach (var enhancer in imageEnhancers) @@ -768,7 +686,7 @@ namespace Emby.Drawing /// Name of the unique. /// The file extension. /// System.String. - /// + /// /// path /// or /// uniqueName @@ -779,16 +697,16 @@ namespace Emby.Drawing { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(uniqueName)) { - throw new ArgumentNullException("uniqueName"); + throw new ArgumentNullException(nameof(uniqueName)); } if (string.IsNullOrEmpty(fileExtension)) { - throw new ArgumentNullException("fileExtension"); + throw new ArgumentNullException(nameof(fileExtension)); } var filename = uniqueName.GetMD5() + fileExtension; @@ -802,7 +720,7 @@ namespace Emby.Drawing /// The path. /// The filename. /// System.String. - /// + /// /// path /// or /// filename @@ -811,27 +729,25 @@ namespace Emby.Drawing { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(filename)) { - throw new ArgumentNullException("filename"); + throw new ArgumentNullException(nameof(filename)); } var prefix = filename.Substring(0, 1); - path = Path.Combine(path, prefix); - - return Path.Combine(path, filename); + return Path.Combine(path, prefix, filename); } public void CreateImageCollage(ImageCollageOptions options) { - _logger.LogInformation("Creating image collage and saving to {0}", options.OutputPath); + _logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath); _imageEncoder.CreateImageCollage(options); - _logger.LogInformation("Completed creation of image collage and saved to {0}", options.OutputPath); + _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath); } public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType) @@ -870,8 +786,7 @@ namespace Emby.Drawing { lock (_locks) { - LockInfo info; - if (_locks.TryGetValue(key, out info)) + if (_locks.TryGetValue(key, out LockInfo info)) { info.Count++; } diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs index 95ea42ecf..e6f205a1f 100644 --- a/Emby.Drawing/NullImageEncoder.cs +++ b/Emby.Drawing/NullImageEncoder.cs @@ -1,4 +1,4 @@ -using System; +using System; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; @@ -6,26 +6,15 @@ namespace Emby.Drawing { public class NullImageEncoder : IImageEncoder { - public string[] SupportedInputFormats - { - get + public string[] SupportedInputFormats => + new[] { - return new[] - { - "png", - "jpeg", - "jpg" - }; - } - } + "png", + "jpeg", + "jpg" + }; - public ImageFormat[] SupportedOutputFormats - { - get - { - return new[] { ImageFormat.Jpg, ImageFormat.Png }; - } - } + public ImageFormat[] SupportedOutputFormats => new[] { ImageFormat.Jpg, ImageFormat.Png }; public void CropWhiteSpace(string inputPath, string outputPath) { @@ -42,20 +31,11 @@ namespace Emby.Drawing throw new NotImplementedException(); } - public string Name - { - get { return "Null Image Encoder"; } - } + public string Name => "Null Image Encoder"; - public bool SupportsImageCollageCreation - { - get { return false; } - } + public bool SupportsImageCollageCreation => false; - public bool SupportsImageEncoding - { - get { return false; } - } + public bool SupportsImageEncoding => false; public ImageSize GetImageSize(string path) { diff --git a/Emby.Drawing.Skia/PercentPlayedDrawer.cs b/Emby.Drawing/PercentPlayedDrawer.cs similarity index 83% rename from Emby.Drawing.Skia/PercentPlayedDrawer.cs rename to Emby.Drawing/PercentPlayedDrawer.cs index e291a462b..52b4329e1 100644 --- a/Emby.Drawing.Skia/PercentPlayedDrawer.cs +++ b/Emby.Drawing/PercentPlayedDrawer.cs @@ -1,14 +1,14 @@ -using SkiaSharp; -using MediaBrowser.Model.Drawing; using System; +using MediaBrowser.Model.Drawing; +using SkiaSharp; -namespace Emby.Drawing.Skia +namespace Emby.Drawing { - public class PercentPlayedDrawer + public static class PercentPlayedDrawer { private const int IndicatorHeight = 8; - public void Process(SKCanvas canvas, ImageSize imageSize, double percent) + public static void Process(SKCanvas canvas, ImageSize imageSize, double percent) { using (var paint = new SKPaint()) { diff --git a/Emby.Drawing.Skia/PlayedIndicatorDrawer.cs b/Emby.Drawing/PlayedIndicatorDrawer.cs similarity index 60% rename from Emby.Drawing.Skia/PlayedIndicatorDrawer.cs rename to Emby.Drawing/PlayedIndicatorDrawer.cs index a4d8a2938..a82398fa5 100644 --- a/Emby.Drawing.Skia/PlayedIndicatorDrawer.cs +++ b/Emby.Drawing/PlayedIndicatorDrawer.cs @@ -1,27 +1,13 @@ -using SkiaSharp; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.IO; +using SkiaSharp; -namespace Emby.Drawing.Skia +namespace Emby.Drawing { - public class PlayedIndicatorDrawer + public static class PlayedIndicatorDrawer { private const int OffsetFromTopRightCorner = 38; - private readonly IApplicationPaths _appPaths; - private readonly IHttpClient _iHttpClient; - private readonly IFileSystem _fileSystem; - - public PlayedIndicatorDrawer(IApplicationPaths appPaths, IHttpClient iHttpClient, IFileSystem fileSystem) - { - _appPaths = appPaths; - _iHttpClient = iHttpClient; - _fileSystem = fileSystem; - } - - public void DrawPlayedIndicator(SKCanvas canvas, ImageSize imageSize) + public static void DrawPlayedIndicator(SKCanvas canvas, ImageSize imageSize) { var x = imageSize.Width - OffsetFromTopRightCorner; @@ -51,7 +37,7 @@ namespace Emby.Drawing.Skia paint.Typeface = emojiTypeface; - canvas.DrawText(text, (float)x-20, OffsetFromTopRightCorner + 12, paint); + canvas.DrawText(text, (float)x - 20, OffsetFromTopRightCorner + 12, paint); } } } diff --git a/Emby.Drawing/Properties/AssemblyInfo.cs b/Emby.Drawing/Properties/AssemblyInfo.cs index b9e9c2ff7..8dfefe0af 100644 --- a/Emby.Drawing/Properties/AssemblyInfo.cs +++ b/Emby.Drawing/Properties/AssemblyInfo.cs @@ -1,20 +1,20 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Emby.Drawing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Drawing")] -[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] @@ -24,7 +24,7 @@ using System.Runtime.InteropServices; // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision -// \ No newline at end of file +// diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing/SkiaEncoder.cs similarity index 89% rename from Emby.Drawing.Skia/SkiaEncoder.cs rename to Emby.Drawing/SkiaEncoder.cs index 0467794dc..87e0eca21 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing/SkiaEncoder.cs @@ -1,80 +1,68 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; -using SkiaSharp; using System; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; -using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Extensions; -using System.Globalization; +using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; +using SkiaSharp; -namespace Emby.Drawing.Skia +namespace Emby.Drawing { public class SkiaEncoder : IImageEncoder { private readonly ILogger _logger; private static IApplicationPaths _appPaths; - private readonly Func _httpClientFactory; private readonly IFileSystem _fileSystem; private static ILocalizationManager _localizationManager; - public SkiaEncoder(ILogger logger, IApplicationPaths appPaths, Func httpClientFactory, IFileSystem fileSystem, ILocalizationManager localizationManager) + public SkiaEncoder( + ILoggerFactory loggerFactory, + IApplicationPaths appPaths, + IFileSystem fileSystem, + ILocalizationManager localizationManager) { - _logger = logger; + _logger = loggerFactory.CreateLogger("ImageEncoder"); _appPaths = appPaths; - _httpClientFactory = httpClientFactory; _fileSystem = fileSystem; _localizationManager = localizationManager; LogVersion(); } - public string[] SupportedInputFormats - { - get + public string[] SupportedInputFormats => + new[] { - // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif. - return new[] - { - "jpeg", - "jpg", - "png", + "jpeg", + "jpg", + "png", - "dng", + "dng", - "webp", - "gif", - "bmp", - "ico", - "astc", - "ktx", - "pkm", - "wbmp", + "webp", + "gif", + "bmp", + "ico", + "astc", + "ktx", + "pkm", + "wbmp", - // TODO - // Are all of these supported? https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454 + // TODO + // Are all of these supported? https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454 - // working on windows at least - "cr2", - "nef", - "arw" - }; - } - } + // working on windows at least + "cr2", + "nef", + "arw" + }; - public ImageFormat[] SupportedOutputFormats - { - get - { - return new[] { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png }; - } - } + public ImageFormat[] SupportedOutputFormats => new[] { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png }; private void LogVersion() { @@ -197,7 +185,7 @@ namespace Emby.Drawing.Skia private static bool HasDiacritics(string text) { - return !String.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal); + return !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal); } private static bool RequiresSpecialCharacterHack(string path) @@ -509,11 +497,11 @@ namespace Emby.Drawing.Skia { if (string.IsNullOrWhiteSpace(inputPath)) { - throw new ArgumentNullException("inputPath"); + throw new ArgumentNullException(nameof(inputPath)); } if (string.IsNullOrWhiteSpace(inputPath)) { - throw new ArgumentNullException("outputPath"); + throw new ArgumentNullException(nameof(outputPath)); } var skiaOutputFormat = GetImageFormat(selectedOutputFormat); @@ -594,12 +582,12 @@ namespace Emby.Drawing.Skia // If foreground layer present then draw if (hasForegroundColor) { - if (!Double.TryParse(options.ForegroundLayer, out double opacity)) + if (!double.TryParse(options.ForegroundLayer, out double opacity)) { opacity = .4; } - canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver); + canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver); } if (hasIndicator) @@ -649,16 +637,16 @@ namespace Emby.Drawing.Skia if (options.AddPlayedIndicator) { - new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize); + PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize); } else if (options.UnplayedCount.HasValue) { - new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value); + UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value); } if (options.PercentPlayed > 0) { - new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed); + PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed); } } catch (Exception ex) @@ -667,19 +655,10 @@ namespace Emby.Drawing.Skia } } - public string Name - { - get { return "Skia"; } - } + public string Name => "Skia"; - public bool SupportsImageCollageCreation - { - get { return true; } - } + public bool SupportsImageCollageCreation => true; - public bool SupportsImageEncoding - { - get { return true; } - } + public bool SupportsImageEncoding => true; } } diff --git a/Emby.Drawing.Skia/StripCollageBuilder.cs b/Emby.Drawing/StripCollageBuilder.cs similarity index 97% rename from Emby.Drawing.Skia/StripCollageBuilder.cs rename to Emby.Drawing/StripCollageBuilder.cs index a98450e08..dd342998b 100644 --- a/Emby.Drawing.Skia/StripCollageBuilder.cs +++ b/Emby.Drawing/StripCollageBuilder.cs @@ -1,11 +1,11 @@ -using SkiaSharp; -using MediaBrowser.Common.Configuration; using System; -using System.IO; -using MediaBrowser.Model.IO; using System.Collections.Generic; +using System.IO; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.IO; +using SkiaSharp; -namespace Emby.Drawing.Skia +namespace Emby.Drawing { public class StripCollageBuilder { @@ -20,6 +20,11 @@ namespace Emby.Drawing.Skia public static SKEncodedImageFormat GetEncodedFormat(string outputPath) { + if (outputPath == null) + { + throw new ArgumentNullException(nameof(outputPath)); + } + var ext = Path.GetExtension(outputPath).ToLower(); if (ext == ".jpg" || ext == ".jpeg") @@ -159,7 +164,7 @@ namespace Emby.Drawing.Skia private SKBitmap GetNextValidImage(string[] paths, int currentIndex, out int newIndex) { - Dictionary imagesTested = new Dictionary(); + var imagesTested = new Dictionary(); SKBitmap bitmap = null; while (imagesTested.Count < paths.Length) @@ -169,7 +174,7 @@ namespace Emby.Drawing.Skia currentIndex = 0; } - bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out SKEncodedOrigin origin); + bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out var origin); imagesTested[currentIndex] = 0; diff --git a/Emby.Drawing.Skia/UnplayedCountIndicator.cs b/Emby.Drawing/UnplayedCountIndicator.cs similarity index 63% rename from Emby.Drawing.Skia/UnplayedCountIndicator.cs rename to Emby.Drawing/UnplayedCountIndicator.cs index b59bc1026..16c084a21 100644 --- a/Emby.Drawing.Skia/UnplayedCountIndicator.cs +++ b/Emby.Drawing/UnplayedCountIndicator.cs @@ -1,31 +1,14 @@ -using SkiaSharp; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Model.Drawing; using System.Globalization; -using System.Threading.Tasks; +using MediaBrowser.Model.Drawing; +using SkiaSharp; -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.Skia +namespace Emby.Drawing { - public class UnplayedCountIndicator + public static class UnplayedCountIndicator { private const int OffsetFromTopRightCorner = 38; - private readonly IApplicationPaths _appPaths; - private readonly IHttpClient _iHttpClient; - private readonly IFileSystem _fileSystem; - - public UnplayedCountIndicator(IApplicationPaths appPaths, IHttpClient iHttpClient, IFileSystem fileSystem) - { - _appPaths = appPaths; - _iHttpClient = iHttpClient; - _fileSystem = fileSystem; - } - - public void DrawUnplayedCountIndicator(SKCanvas canvas, ImageSize imageSize, int count) + public static void DrawUnplayedCountIndicator(SKCanvas canvas, ImageSize imageSize, int count) { var x = imageSize.Width - OffsetFromTopRightCorner; var text = count.ToString(CultureInfo.InvariantCulture); diff --git a/Emby.IsoMounting/IsoMounter.sln b/Emby.IsoMounting/IsoMounter.sln index 7505be4f7..55db1b1ae 100644 --- a/Emby.IsoMounting/IsoMounter.sln +++ b/Emby.IsoMounting/IsoMounter.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27004.2009 diff --git a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs b/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs index 9308b8c89..4755e4e82 100644 --- a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs +++ b/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs @@ -1,8 +1,8 @@ -using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Plugins; namespace IsoMounter.Configuration { public class PluginConfiguration : BasePluginConfiguration { } -} \ No newline at end of file +} diff --git a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj b/Emby.IsoMounting/IsoMounter/IsoMounter.csproj index ee67a1d94..dafa51cd5 100644 --- a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj +++ b/Emby.IsoMounting/IsoMounter/IsoMounter.csproj @@ -1,10 +1,14 @@ + + + + - + netstandard2.0 false diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs index faaed482a..ac486f167 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs @@ -1,19 +1,19 @@ using System; using System.IO; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; -using System.Runtime.InteropServices; +using Microsoft.Extensions.Logging; namespace IsoMounter { public class LinuxIsoManager : IIsoMounter { [DllImport("libc", SetLastError = true)] - public static extern uint getuid(); + static extern uint getuid(); #region Private Fields @@ -44,13 +44,13 @@ namespace IsoMounter _logger.LogDebug( "[{0}] System PATH is currently set to [{1}].", Name, - EnvironmentInfo.GetEnvironmentVariable("PATH") ?? "" + Environment.GetEnvironmentVariable("PATH") ?? "" ); _logger.LogDebug( "[{0}] System path separator is [{1}].", Name, - EnvironmentInfo.PathSeparator + Path.PathSeparator ); _logger.LogDebug( @@ -87,9 +87,12 @@ namespace IsoMounter UmountCommand ); - if (!String.IsNullOrEmpty(SudoCommand) && !String.IsNullOrEmpty(MountCommand) && !String.IsNullOrEmpty(UmountCommand)) { + if (!string.IsNullOrEmpty(SudoCommand) && !string.IsNullOrEmpty(MountCommand) && !string.IsNullOrEmpty(UmountCommand)) + { ExecutablesAvailable = true; - } else { + } + else + { ExecutablesAvailable = false; } @@ -99,44 +102,36 @@ namespace IsoMounter #region Interface Implementation for IIsoMounter - public bool IsInstalled { - get { - return true; - } - } + public bool IsInstalled => true; - public string Name { - get { return "LinuxMount"; } - } + public string Name => "LinuxMount"; - public bool RequiresInstallation { - get { - return false; - } - } + public bool RequiresInstallation => false; public bool CanMount(string path) { - if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux) { - _logger.LogInformation( - "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].", - Name, - path, - Path.GetExtension(path), - EnvironmentInfo.OperatingSystem, - ExecutablesAvailable.ToString() - ); - - if (ExecutablesAvailable) { - return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase); - } else { - return false; - } - } else { + if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Linux) + { return false; } + _logger.LogInformation( + "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].", + Name, + path, + Path.GetExtension(path), + EnvironmentInfo.OperatingSystem, + ExecutablesAvailable.ToString() + ); + if (ExecutablesAvailable) + { + return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase); + } + else + { + return false; + } } public Task Install(CancellationToken cancellationToken) @@ -146,11 +141,13 @@ namespace IsoMounter public Task Mount(string isoPath, CancellationToken cancellationToken) { - if (MountISO(isoPath, out LinuxMount mountedISO)) { + if (MountISO(isoPath, out LinuxMount mountedISO)) + { return Task.FromResult(mountedISO); } - else { - throw new IOException(String.Format( + else + { + throw new IOException(string.Format( "An error occurred trying to mount image [$0].", isoPath )); @@ -178,7 +175,8 @@ namespace IsoMounter protected virtual void Dispose(bool disposing) { - if (disposed) { + if (disposed) + { return; } @@ -188,7 +186,8 @@ namespace IsoMounter disposing.ToString() ); - if (disposing) { + if (disposing) + { // // Free managed objects here. @@ -211,18 +210,17 @@ namespace IsoMounter private string GetFullPathForExecutable(string name) { - foreach (string test in (EnvironmentInfo.GetEnvironmentVariable("PATH") ?? "").Split(EnvironmentInfo.PathSeparator)) { - + foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) + { string path = test.Trim(); - if (!String.IsNullOrEmpty(path) && FileSystem.FileExists(path = Path.Combine(path, name))) { + if (!string.IsNullOrEmpty(path) && FileSystem.FileExists(path = Path.Combine(path, name))) + { return FileSystem.GetFullPath(path); } - } - return String.Empty; - + return string.Empty; } private uint GetUID() @@ -247,7 +245,8 @@ namespace IsoMounter bool processFailed = false; var process = ProcessFactory.Create( - new ProcessOptions { + new ProcessOptions + { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, @@ -285,9 +284,12 @@ namespace IsoMounter _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name); } - if (!processFailed && process.ExitCode == 0) { + if (!processFailed && process.ExitCode == 0) + { return true; - } else { + } + else + { return false; } @@ -300,7 +302,8 @@ namespace IsoMounter string cmdFilename; string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString()); - if (!string.IsNullOrEmpty(isoPath)) { + if (!string.IsNullOrEmpty(isoPath)) + { _logger.LogInformation( "[{Name}] Attempting to mount [{Path}].", @@ -314,10 +317,12 @@ namespace IsoMounter mountPoint ); - } else { - + } + else + { + throw new ArgumentNullException(nameof(isoPath)); - + } try @@ -333,10 +338,13 @@ namespace IsoMounter throw new IOException("Unable to create mount point for " + isoPath); } - if (GetUID() == 0) { + if (GetUID() == 0) + { cmdFilename = MountCommand; cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint); - } else { + } + else + { cmdFilename = SudoCommand; cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint); } @@ -348,7 +356,8 @@ namespace IsoMounter cmdArguments ); - if (ExecuteCommand(cmdFilename, cmdArguments)) { + if (ExecuteCommand(cmdFilename, cmdArguments)) + { _logger.LogInformation( "[{0}] ISO mount completed successfully.", @@ -357,7 +366,9 @@ namespace IsoMounter mountedISO = new LinuxMount(this, isoPath, mountPoint); - } else { + } + else + { _logger.LogInformation( "[{0}] ISO mount completed with errors.", @@ -387,7 +398,8 @@ namespace IsoMounter string cmdArguments; string cmdFilename; - if (mount != null) { + if (mount != null) + { _logger.LogInformation( "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].", @@ -396,16 +408,21 @@ namespace IsoMounter mount.MountedPath ); - } else { - + } + else + { + throw new ArgumentNullException(nameof(mount)); - + } - if (GetUID() == 0) { + if (GetUID() == 0) + { cmdFilename = UmountCommand; cmdArguments = string.Format("\"{0}\"", mount.MountedPath); - } else { + } + else + { cmdFilename = SudoCommand; cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath); } @@ -417,14 +434,17 @@ namespace IsoMounter cmdArguments ); - if (ExecuteCommand(cmdFilename, cmdArguments)) { + if (ExecuteCommand(cmdFilename, cmdArguments)) + { _logger.LogInformation( "[{0}] ISO unmount completed successfully.", Name ); - } else { + } + else + { _logger.LogInformation( "[{0}] ISO unmount completed with errors.", @@ -444,7 +464,7 @@ namespace IsoMounter } #endregion - + #region Internal Methods internal void OnUnmount(LinuxMount mount) diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs index edd26f08d..b8636822b 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxMount.cs @@ -45,11 +45,13 @@ namespace IsoMounter protected virtual void Dispose(bool disposing) { - if (disposed) { + if (disposed) + { return; } - - if (disposing) { + + if (disposing) + { // // Free managed objects here. diff --git a/Emby.IsoMounting/IsoMounter/Plugin.cs b/Emby.IsoMounting/IsoMounter/Plugin.cs index ea5317502..f45b39d3e 100644 --- a/Emby.IsoMounting/IsoMounter/Plugin.cs +++ b/Emby.IsoMounting/IsoMounter/Plugin.cs @@ -1,8 +1,8 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Plugins; -using MediaBrowser.Model.Serialization; using System; using IsoMounter.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Serialization; namespace IsoMounter { @@ -13,30 +13,18 @@ namespace IsoMounter } private Guid _id = new Guid("4682DD4C-A675-4F1B-8E7C-79ADF137A8F8"); - public override Guid Id - { - get { return _id; } - } + public override Guid Id => _id; /// /// Gets the name of the plugin /// /// The name. - public override string Name - { - get { return "Iso Mounter"; } - } + public override string Name => "Iso Mounter"; /// /// Gets the description. /// /// The description. - public override string Description - { - get - { - return "Mount and stream ISO contents"; - } - } + public override string Description => "Mount and stream ISO contents"; } } diff --git a/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs b/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..d60eccc2e --- /dev/null +++ b/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("IsoMounter")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs index c88631a0c..7d029a9f4 100644 --- a/Emby.Naming/Audio/AlbumParser.cs +++ b/Emby.Naming/Audio/AlbumParser.cs @@ -1,10 +1,9 @@ -using Emby.Naming.Common; -using Emby.Naming.Video; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Common; namespace Emby.Naming.Audio { @@ -50,8 +49,7 @@ namespace Emby.Naming.Audio tmp = tmp.Trim().Split(' ').FirstOrDefault() ?? string.Empty; - int val; - if (int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + if (int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val)) { result.IsMultiPart = true; break; diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs index 20016915a..609eb779a 100644 --- a/Emby.Naming/Audio/AudioFileParser.cs +++ b/Emby.Naming/Audio/AudioFileParser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using Emby.Naming.Common; diff --git a/Emby.Naming/Audio/MultiPartResult.cs b/Emby.Naming/Audio/MultiPartResult.cs index fae0ae4d8..b1fa6e563 100644 --- a/Emby.Naming/Audio/MultiPartResult.cs +++ b/Emby.Naming/Audio/MultiPartResult.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Audio { public class MultiPartResult diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs index 88a98d0f1..de66a5402 100644 --- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs @@ -1,6 +1,4 @@ - using System; -using Emby.Naming.Video; namespace Emby.Naming.AudioBook { diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs index b4805edd2..590979794 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Linq; -using System.Text; using System.Text.RegularExpressions; using Emby.Naming.Common; -using Emby.Naming.TV; namespace Emby.Naming.AudioBook { @@ -21,7 +16,7 @@ namespace Emby.Naming.AudioBook public AudioBookFilePathParserResult Parse(string path, bool IsDirectory) { - AudioBookFilePathParserResult result = Parse(path); + var result = Parse(path); return !result.Success ? new AudioBookFilePathParserResult() : result; } @@ -39,8 +34,7 @@ namespace Emby.Naming.AudioBook var value = match.Groups["chapter"]; if (value.Success) { - int intValue; - if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out intValue)) + if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue)) { result.ChapterNumber = intValue; } @@ -51,8 +45,7 @@ namespace Emby.Naming.AudioBook var value = match.Groups["part"]; if (value.Success) { - int intValue; - if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out intValue)) + if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue)) { result.ChapterNumber = intValue; } diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs index 759e7b8ad..3a8e3c31f 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Emby.Naming.AudioBook { public class AudioBookFilePathParserResult diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index e039e5359..f6e1d5be4 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Emby.Naming.Video; +using System.Collections.Generic; namespace Emby.Naming.AudioBook { @@ -29,7 +28,7 @@ namespace Emby.Naming.AudioBook /// /// The alternate versions. public List AlternateVersions { get; set; } - + public AudioBookInfo() { Files = new List(); diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 8cf6a03bd..4e3ad7cac 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.IO; using System.Linq; using Emby.Naming.Common; using Emby.Naming.Video; diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index a206ee30b..f8f13bc5e 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -1,9 +1,7 @@ -using System; +using System; using System.IO; using System.Linq; using Emby.Naming.Common; -using Emby.Naming.TV; -using Emby.Naming.Video; namespace Emby.Naming.AudioBook { @@ -30,7 +28,7 @@ namespace Emby.Naming.AudioBook { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (IsDirectory) return null; @@ -46,7 +44,7 @@ namespace Emby.Naming.AudioBook var parsingResult = new AudioBookFilePathParser(_options) .Parse(path, IsDirectory); - + return new AudioBookFileInfo { Path = path, diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs index 3b9687c60..fd85bf76a 100644 --- a/Emby.Naming/Common/EpisodeExpression.cs +++ b/Emby.Naming/Common/EpisodeExpression.cs @@ -1,12 +1,13 @@ -using System.Text.RegularExpressions; using System; +using System.Text.RegularExpressions; namespace Emby.Naming.Common { public class EpisodeExpression { private string _expression; - public string Expression { get { return _expression; } set { _expression = value; _regex = null; } } + public string Expression { get => _expression; + set { _expression = value; _regex = null; } } public bool IsByDate { get; set; } public bool IsOptimistic { get; set; } @@ -16,13 +17,7 @@ namespace Emby.Naming.Common public string[] DateTimeFormats { get; set; } private Regex _regex; - public Regex Regex - { - get - { - return _regex ?? (_regex = new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled)); - } - } + public Regex Regex => _regex ?? (_regex = new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled)); public EpisodeExpression(string expression, bool byDate) { diff --git a/Emby.Naming/Common/MediaType.cs b/Emby.Naming/Common/MediaType.cs index 2a3d433cf..49cc9ee39 100644 --- a/Emby.Naming/Common/MediaType.cs +++ b/Emby.Naming/Common/MediaType.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Common { public enum MediaType diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 9e65440d0..2ef0208ba 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -1,8 +1,7 @@ -using Emby.Naming.Video; -using System.Collections.Generic; using System; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Video; namespace Emby.Naming.Common { @@ -282,7 +281,7 @@ namespace Emby.Naming.Common new EpisodeExpression(@".*(\\|\/)(?((?![Ss]([0-9]+)[][ ._-]*[Ee]([0-9]+))[^\\\/])*)?[Ss](?[0-9]+)[][ ._-]*[Ee](?[0-9]+)([^\\/]*)$") { IsNamed = true - }, + }, // new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"), new EpisodeExpression("([0-9]{4})[\\.-]([0-9]{2})[\\.-]([0-9]{2})", true) diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index f1a736ecc..e344e7811 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -4,9 +4,20 @@ netstandard2.0 false - + + + + + - + + + Jellyfin Contributors + Jellyfin.Naming + https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt + https://github.com/jellyfin/jellyfin + + diff --git a/Emby.Naming/Extensions/StringExtensions.cs b/Emby.Naming/Extensions/StringExtensions.cs index e773dbfe8..26c09aeb4 100644 --- a/Emby.Naming/Extensions/StringExtensions.cs +++ b/Emby.Naming/Extensions/StringExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text; namespace Emby.Naming.Extensions diff --git a/Emby.Naming/Properties/AssemblyInfo.cs b/Emby.Naming/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..15311570b --- /dev/null +++ b/Emby.Naming/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Emby.Naming")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] diff --git a/Emby.Naming/StringExtensions.cs b/Emby.Naming/StringExtensions.cs index 5598ddb4c..7c61922af 100644 --- a/Emby.Naming/StringExtensions.cs +++ b/Emby.Naming/StringExtensions.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System; using System.Text; namespace Emby.Naming diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs index 3ece0679e..e4709dfbb 100644 --- a/Emby.Naming/Subtitles/SubtitleInfo.cs +++ b/Emby.Naming/Subtitles/SubtitleInfo.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Subtitles { public class SubtitleInfo diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index fbf0f60cb..ac9432d57 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -1,7 +1,7 @@ -using Emby.Naming.Common; using System; using System.IO; using System.Linq; +using Emby.Naming.Common; namespace Emby.Naming.Subtitles { @@ -18,7 +18,7 @@ namespace Emby.Naming.Subtitles { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var extension = Path.GetExtension(path); @@ -52,7 +52,7 @@ namespace Emby.Naming.Subtitles { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _. diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs index 41397480e..c8aca7a6f 100644 --- a/Emby.Naming/TV/EpisodeInfo.cs +++ b/Emby.Naming/TV/EpisodeInfo.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.TV { public class EpisodeInfo diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index 7f8a6a70e..9485d697b 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -1,9 +1,9 @@ -using Emby.Naming.Common; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Common; namespace Emby.Naming.TV { @@ -74,7 +74,7 @@ namespace Emby.Naming.TV return result ?? new EpisodePathParserResult(); } - private EpisodePathParserResult Parse(string name, EpisodeExpression expression) + private static EpisodePathParserResult Parse(string name, EpisodeExpression expression) { var result = new EpisodePathParserResult(); @@ -122,8 +122,7 @@ namespace Emby.Naming.TV } else if (expression.IsNamed) { - int num; - if (int.TryParse(match.Groups["seasonnumber"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num)) + if (int.TryParse(match.Groups["seasonnumber"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num)) { result.SeasonNumber = num; } @@ -133,7 +132,7 @@ namespace Emby.Naming.TV result.EpisodeNumber = num; } - Group endingNumberGroup = match.Groups["endingepnumber"]; + var endingNumberGroup = match.Groups["endingepnumber"]; if (endingNumberGroup.Success) { // Will only set EndingEpsiodeNumber if the captured number is not followed by additional numbers @@ -154,8 +153,7 @@ namespace Emby.Naming.TV } else { - int num; - if (int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num)) + if (int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num)) { result.SeasonNumber = num; } diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs index 9890c78a4..e1a48bfbc 100644 --- a/Emby.Naming/TV/EpisodePathParserResult.cs +++ b/Emby.Naming/TV/EpisodePathParserResult.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.TV { public class EpisodePathParserResult diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 2007d1307..fccf9bdec 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -1,8 +1,8 @@ -using Emby.Naming.Common; -using Emby.Naming.Video; using System; using System.IO; using System.Linq; +using Emby.Naming.Common; +using Emby.Naming.Video; namespace Emby.Naming.TV { @@ -19,20 +19,20 @@ namespace Emby.Naming.TV { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } - var isStub = false; + bool isStub = false; string container = null; string stubType = null; if (!IsDirectory) { - var extension = Path.GetExtension(path) ?? string.Empty; + var extension = Path.GetExtension(path); // Check supported extensions if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - var stubResult = new StubResolver(_options).ResolveFile(path); + var stubResult = StubResolver.ResolveFile(path, _options); isStub = stubResult.IsStub; @@ -53,7 +53,7 @@ namespace Emby.Naming.TV var parsingResult = new EpisodePathParser(_options) .Parse(path, IsDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo); - + return new EpisodeInfo { Path = path, diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index 72277e6b9..f1dcc50b8 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -1,8 +1,8 @@ -using Emby.Naming.Common; using System; using System.Globalization; using System.IO; using System.Linq; +using Emby.Naming.Common; namespace Emby.Naming.TV { @@ -72,8 +72,7 @@ namespace Emby.Naming.TV if (supportNumericSeasonFolders) { - int val; - if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val)) { return new Tuple(val, true); } @@ -83,8 +82,7 @@ namespace Emby.Naming.TV { var testFilename = filename.Substring(1); - int val; - if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val)) { return new Tuple(val, true); } @@ -121,8 +119,7 @@ namespace Emby.Naming.TV part = part.Substring(1); - int value; - if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) + if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) { return value; } diff --git a/Emby.Naming/TV/SeasonPathParserResult.cs b/Emby.Naming/TV/SeasonPathParserResult.cs index 9a18d0a03..eab27a4a5 100644 --- a/Emby.Naming/TV/SeasonPathParserResult.cs +++ b/Emby.Naming/TV/SeasonPathParserResult.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.TV { public class SeasonPathParserResult diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 572dd1c60..74807ef53 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,9 +1,9 @@ -using System; -using Emby.Naming.Common; +using System; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Common; namespace Emby.Naming.Video { @@ -38,7 +38,7 @@ namespace Emby.Naming.Video } catch (ArgumentException) { - + } var result = _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) @@ -63,7 +63,7 @@ namespace Emby.Naming.Video result; } - private CleanDateTimeResult Clean(string name, Regex expression) + private static CleanDateTimeResult Clean(string name, Regex expression) { var result = new CleanDateTimeResult(); @@ -71,8 +71,7 @@ namespace Emby.Naming.Video if (match.Success && match.Groups.Count == 4) { - int year; - if (match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out year)) + if (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; result.Year = year; diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs index 946fd953c..6bf24e4d8 100644 --- a/Emby.Naming/Video/CleanDateTimeResult.cs +++ b/Emby.Naming/Video/CleanDateTimeResult.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Video { public class CleanDateTimeResult diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index bddf9589b..02b90310d 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Text.RegularExpressions; namespace Emby.Naming.Video @@ -30,7 +30,7 @@ namespace Emby.Naming.Video }; } - private CleanStringResult Clean(string name, Regex expression) + private static CleanStringResult Clean(string name, Regex expression) { var result = new CleanStringResult(); diff --git a/Emby.Naming/Video/CleanStringResult.cs b/Emby.Naming/Video/CleanStringResult.cs index 0282863e0..b3bc59712 100644 --- a/Emby.Naming/Video/CleanStringResult.cs +++ b/Emby.Naming/Video/CleanStringResult.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Video { public class CleanStringResult diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index bde1a4765..3459b689a 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -1,9 +1,9 @@ -using Emby.Naming.Audio; -using Emby.Naming.Common; using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Audio; +using Emby.Naming.Common; namespace Emby.Naming.Video { diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs index ca79af9da..ff6f20c47 100644 --- a/Emby.Naming/Video/ExtraResult.cs +++ b/Emby.Naming/Video/ExtraResult.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Emby.Naming.Video { public class ExtraResult diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs index ef83b3cd6..b8eb8427e 100644 --- a/Emby.Naming/Video/ExtraRule.cs +++ b/Emby.Naming/Video/ExtraRule.cs @@ -1,4 +1,4 @@ -using Emby.Naming.Common; +using Emby.Naming.Common; namespace Emby.Naming.Video { diff --git a/Emby.Naming/Video/ExtraRuleType.cs b/Emby.Naming/Video/ExtraRuleType.cs index 323c7cef6..565239ff9 100644 --- a/Emby.Naming/Video/ExtraRuleType.cs +++ b/Emby.Naming/Video/ExtraRuleType.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Video { public enum ExtraRuleType diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs index 2feea4cb3..2df1e9aed 100644 --- a/Emby.Naming/Video/FileStack.cs +++ b/Emby.Naming/Video/FileStack.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs index a2c541eeb..bb129499b 100644 --- a/Emby.Naming/Video/FlagParser.cs +++ b/Emby.Naming/Video/FlagParser.cs @@ -1,6 +1,6 @@ -using Emby.Naming.Common; using System; using System.IO; +using Emby.Naming.Common; namespace Emby.Naming.Video { @@ -22,7 +22,7 @@ namespace Emby.Naming.Video { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _. diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index 42737b483..e6f830c58 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -1,6 +1,6 @@ -using Emby.Naming.Common; using System; using System.Linq; +using Emby.Naming.Common; namespace Emby.Naming.Video { @@ -36,7 +36,7 @@ namespace Emby.Naming.Video return new Format3DResult(); } - private Format3DResult Parse(string[] videoFlags, Format3DRule rule) + private static Format3DResult Parse(string[] videoFlags, Format3DRule rule) { var result = new Format3DResult(); diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs index 147ccfc05..e12494079 100644 --- a/Emby.Naming/Video/Format3DResult.cs +++ b/Emby.Naming/Video/Format3DResult.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Naming.Video { diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs index 3c173efbc..dc260175a 100644 --- a/Emby.Naming/Video/Format3DRule.cs +++ b/Emby.Naming/Video/Format3DRule.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Video { public class Format3DRule diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index 2a7125536..4893002c1 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -1,9 +1,9 @@ -using Emby.Naming.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.Common; using MediaBrowser.Model.IO; namespace Emby.Naming.Video @@ -126,7 +126,7 @@ namespace Emby.Naming.Video } stack.Files.Add(file2.FullName); } - else + else { // Sequel offset = 0; diff --git a/Emby.Naming/Video/StackResult.cs b/Emby.Naming/Video/StackResult.cs index 920a7dea7..de35d2825 100644 --- a/Emby.Naming/Video/StackResult.cs +++ b/Emby.Naming/Video/StackResult.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Naming.Video { diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index 69f1f50fa..f86bcbdf0 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -1,25 +1,18 @@ -using Emby.Naming.Common; using System; using System.IO; using System.Linq; +using Emby.Naming.Common; namespace Emby.Naming.Video { - public class StubResolver + public static class StubResolver { - private readonly NamingOptions _options; - - public StubResolver(NamingOptions options) - { - _options = options; - } - - public StubResult ResolveFile(string path) + public static StubResult ResolveFile(string path, NamingOptions options) { var result = new StubResult(); var extension = Path.GetExtension(path) ?? string.Empty; - - if (_options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) + + if (options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { result.IsStub = true; @@ -27,12 +20,11 @@ namespace Emby.Naming.Video var token = (Path.GetExtension(path) ?? string.Empty).TrimStart('.'); - foreach (var rule in _options.StubTypes) + foreach (var rule in options.StubTypes) { if (string.Equals(rule.Token, token, StringComparison.OrdinalIgnoreCase)) { result.StubType = rule.StubType; - result.Tokens.Add(token); break; } } diff --git a/Emby.Naming/Video/StubResult.cs b/Emby.Naming/Video/StubResult.cs index c9d06c9a7..7f9509ca5 100644 --- a/Emby.Naming/Video/StubResult.cs +++ b/Emby.Naming/Video/StubResult.cs @@ -1,8 +1,6 @@ -using System.Collections.Generic; - namespace Emby.Naming.Video { - public class StubResult + public struct StubResult { /// /// Gets or sets a value indicating whether this instance is stub. @@ -14,15 +12,5 @@ namespace Emby.Naming.Video /// /// The type of the stub. public string StubType { get; set; } - /// - /// Gets or sets the tokens. - /// - /// The tokens. - public List Tokens { get; set; } - - public StubResult() - { - Tokens = new List(); - } } } diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs index 66ebfc3a2..b46050085 100644 --- a/Emby.Naming/Video/StubTypeRule.cs +++ b/Emby.Naming/Video/StubTypeRule.cs @@ -1,4 +1,3 @@ - namespace Emby.Naming.Video { public class StubTypeRule diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 96839c31e..6a29ada7e 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,4 +1,4 @@ - + namespace Emby.Naming.Video { /// @@ -55,7 +55,7 @@ namespace Emby.Naming.Video /// Gets or sets the type of the stub. /// /// The type of the stub. - public string StubType { get; set; } + public string StubType { get; set; } /// /// Gets or sets the type. /// @@ -65,10 +65,7 @@ namespace Emby.Naming.Video /// Gets the file name without extension. /// /// The file name without extension. - public string FileNameWithoutExtension - { - get { return !IsDirectory ? System.IO.Path.GetFileNameWithoutExtension(Path) : System.IO.Path.GetFileName(Path); } - } + public string FileNameWithoutExtension => !IsDirectory ? System.IO.Path.GetFileNameWithoutExtension(Path) : System.IO.Path.GetFileName(Path); public override string ToString() { diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs index f4d311b97..d96d0e757 100644 --- a/Emby.Naming/Video/VideoInfo.cs +++ b/Emby.Naming/Video/VideoInfo.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Emby.Naming.Video { @@ -32,7 +32,7 @@ namespace Emby.Naming.Video /// /// The alternate versions. public List AlternateVersions { get; set; } - + public VideoInfo() { Files = new List(); diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 47be28104..0506d0734 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -1,10 +1,10 @@ -using Emby.Naming.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using MediaBrowser.Model.IO; using System.Text.RegularExpressions; +using Emby.Naming.Common; +using MediaBrowser.Model.IO; namespace Emby.Naming.Video { @@ -55,9 +55,9 @@ namespace Emby.Naming.Video info.Year = info.Files.First().Year; - var extraBaseNames = new List + var extraBaseNames = new List { - stack.Name, + stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0]) }; @@ -236,7 +236,7 @@ namespace Emby.Naming.Video if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) { testFilename = testFilename.Substring(folderName.Length).Trim(); - return testFilename.StartsWith("-", StringComparison.OrdinalIgnoreCase)||Regex.Replace(testFilename, @"\[([^]]*)\]", "").Trim() == String.Empty; + return testFilename.StartsWith("-", StringComparison.OrdinalIgnoreCase) || Regex.Replace(testFilename, @"\[([^]]*)\]", "").Trim() == string.Empty; } return false; diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index c4951c728..a67315651 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,7 +1,7 @@ -using Emby.Naming.Common; using System; using System.IO; using System.Linq; +using Emby.Naming.Common; namespace Emby.Naming.Video { @@ -40,25 +40,25 @@ namespace Emby.Naming.Video /// The path. /// if set to true [is folder]. /// VideoFileInfo. - /// path + /// path public VideoFileInfo Resolve(string path, bool IsDirectory, bool parseName = true) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } - var isStub = false; + bool isStub = false; string container = null; string stubType = null; if (!IsDirectory) { - var extension = Path.GetExtension(path) ?? string.Empty; + var extension = Path.GetExtension(path); // Check supported extensions if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - var stubResult = new StubResolver(_options).ResolveFile(path); + var stubResult = StubResolver.ResolveFile(path, _options); isStub = stubResult.IsStub; @@ -79,9 +79,9 @@ namespace Emby.Naming.Video var extraResult = new ExtraResolver(_options).GetExtraInfo(path); - var name = !IsDirectory - ? Path.GetFileNameWithoutExtension(path) - : Path.GetFileName(path); + var name = IsDirectory + ? Path.GetFileName(path) + : Path.GetFileNameWithoutExtension(path); int? year = null; @@ -91,8 +91,7 @@ namespace Emby.Naming.Video if (string.IsNullOrEmpty(extraResult.ExtraType)) { - name = cleanDateTimeResult.Name; - name = CleanString(name).Name; + name = CleanString(cleanDateTimeResult.Name).Name; } year = cleanDateTimeResult.Year; diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs index d09552ebc..83845558a 100644 --- a/Emby.Notifications/Api/NotificationsService.cs +++ b/Emby.Notifications/Api/NotificationsService.cs @@ -1,14 +1,14 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Notifications; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Services; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Notifications; +using MediaBrowser.Model.Services; namespace Emby.Notifications.Api { diff --git a/Emby.Notifications/CoreNotificationTypes.cs b/Emby.Notifications/CoreNotificationTypes.cs index b45a75b1e..158898084 100644 --- a/Emby.Notifications/CoreNotificationTypes.cs +++ b/Emby.Notifications/CoreNotificationTypes.cs @@ -1,10 +1,10 @@ -using MediaBrowser.Controller; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Notifications; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Notifications; namespace Emby.Notifications { diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 881be692b..5c68e48c8 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -1,10 +1,14 @@ - + netstandard2.0 false + + + + diff --git a/Emby.Notifications/NotificationConfigurationFactory.cs b/Emby.Notifications/NotificationConfigurationFactory.cs index 2d464910e..d08475f7d 100644 --- a/Emby.Notifications/NotificationConfigurationFactory.cs +++ b/Emby.Notifications/NotificationConfigurationFactory.cs @@ -1,6 +1,6 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Notifications; using System.Collections.Generic; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Notifications; namespace Emby.Notifications { diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index fa8fdd9c1..3d1d4722d 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -1,18 +1,17 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Notifications; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Notifications; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Notifications; +using Microsoft.Extensions.Logging; namespace Emby.Notifications { diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs index 101f9706c..fbdc39f94 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/Notifications.cs @@ -1,27 +1,27 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Updates; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Notifications; -using MediaBrowser.Model.Tasks; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Updates; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Devices; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Model.Threading; -using MediaBrowser.Model.Globalization; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Notifications; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Notifications; +using MediaBrowser.Model.Tasks; +using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Notifications { diff --git a/Emby.Notifications/Properties/AssemblyInfo.cs b/Emby.Notifications/Properties/AssemblyInfo.cs index d35c8b289..fd7037551 100644 --- a/Emby.Notifications/Properties/AssemblyInfo.cs +++ b/Emby.Notifications/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +using System.Reflection; +using System.Resources; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -8,29 +8,14 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("Emby.Notifications")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Notifications")] -[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4d1d313b-60bb-4e11-acf9-cda6745266ef")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index 3ecab9176..e6b445202 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -1,4 +1,4 @@ - + diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs index 726fd1d79..4e483ad5b 100644 --- a/Emby.Photos/PhotoProvider.cs +++ b/Emby.Photos/PhotoProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using System.Threading; @@ -7,6 +7,7 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -14,7 +15,6 @@ using TagLib; using TagLib.IFD; using TagLib.IFD.Entries; using TagLib.IFD.Tags; -using MediaBrowser.Model.MediaInfo; namespace Emby.Photos { @@ -145,8 +145,7 @@ namespace Emby.Photos } else { - MediaBrowser.Model.Drawing.ImageOrientation orientation; - if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out orientation)) + if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out ImageOrientation orientation)) { item.Orientation = orientation; } @@ -182,7 +181,7 @@ namespace Emby.Photos try { - var size = _imageProcessor.GetImageSize(item, img, false, false); + var size = _imageProcessor.GetImageSize(item, img, false); if (size.Width > 0 && size.Height > 0) { @@ -200,9 +199,6 @@ namespace Emby.Photos return Task.FromResult(result); } - public string Name - { - get { return "Embedded Information"; } - } + public string Name => "Embedded Information"; } } diff --git a/Emby.Photos/Properties/AssemblyInfo.cs b/Emby.Photos/Properties/AssemblyInfo.cs index 49ac83345..262125d38 100644 --- a/Emby.Photos/Properties/AssemblyInfo.cs +++ b/Emby.Photos/Properties/AssemblyInfo.cs @@ -1,34 +1,21 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +using System.Reflection; +using System.Resources; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Emby.Photos")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Photos")] -[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyCompany("Jellyfin Project")] +[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")] +[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("89ab4548-770d-41fd-a891-8daff44f452c")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] \ No newline at end of file diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index 3f7b907a9..a8e8f815a 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -1,29 +1,28 @@ -using MediaBrowser.Common.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; using MediaBrowser.Controller; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Activity; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Notifications; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Updates; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Notifications; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Dto; -using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Authentication; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Activity { @@ -202,7 +201,7 @@ namespace Emby.Server.Implementations.Activity return name; } - private string GetPlaybackNotificationType(string mediaType) + private static string GetPlaybackNotificationType(string mediaType) { if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)) { @@ -220,7 +219,7 @@ namespace Emby.Server.Implementations.Activity return null; } - private string GetPlaybackStoppedNotificationType(string mediaType) + private static string GetPlaybackStoppedNotificationType(string mediaType) { if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)) { @@ -528,7 +527,7 @@ namespace Emby.Server.Implementations.Activity const int DaysInMonth = 30; // Get each non-zero value from TimeSpan component - List values = new List(); + var values = new List(); // Number of years int days = span.Days; @@ -559,7 +558,7 @@ namespace Emby.Server.Implementations.Activity values.Add(CreateValueString(span.Seconds, "second")); // Combine values into string - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); for (int i = 0; i < values.Count; i++) { if (builder.Length > 0) @@ -577,8 +576,8 @@ namespace Emby.Server.Implementations.Activity /// The name of this item (singular form) private static string CreateValueString(int value, string description) { - return String.Format("{0:#,##0} {1}", - value, value == 1 ? description : String.Format("{0}s", description)); + return string.Format("{0:#,##0} {1}", + value, value == 1 ? description : string.Format("{0}s", description)); } } } diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs index 0bb44a9d5..6febcc2f7 100644 --- a/Emby.Server.Implementations/Activity/ActivityManager.cs +++ b/Emby.Server.Implementations/Activity/ActivityManager.cs @@ -1,10 +1,10 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Activity; -using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; using System; using System.Linq; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Activity; +using MediaBrowser.Model.Events; +using MediaBrowser.Model.Querying; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Activity { @@ -16,9 +16,12 @@ namespace Emby.Server.Implementations.Activity private readonly ILogger _logger; private readonly IUserManager _userManager; - public ActivityManager(ILogger logger, IActivityRepository repo, IUserManager userManager) + public ActivityManager( + ILoggerFactory loggerFactory, + IActivityRepository repo, + IUserManager userManager) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(ActivityManager)); _repo = repo; _userManager = userManager; } diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index 91a4a5fd4..aeed8b6f1 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -6,11 +6,10 @@ using System.Linq; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using MediaBrowser.Model.Activity; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; -using SQLitePCL.pretty; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Querying; +using Microsoft.Extensions.Logging; +using SQLitePCL.pretty; namespace Emby.Server.Implementations.Activity { @@ -19,8 +18,8 @@ namespace Emby.Server.Implementations.Activity private readonly CultureInfo _usCulture = new CultureInfo("en-US"); protected IFileSystem FileSystem { get; private set; } - public ActivityRepository(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem) - : base(logger) + public ActivityRepository(ILoggerFactory loggerFactory, IServerApplicationPaths appPaths, IFileSystem fileSystem) + : base(loggerFactory.CreateLogger(nameof(ActivityRepository))) { DbFilePath = Path.Combine(appPaths.DataPath, "activitylog.db"); FileSystem = fileSystem; @@ -83,7 +82,7 @@ namespace Emby.Server.Implementations.Activity { if (entry == null) { - throw new ArgumentNullException("entry"); + throw new ArgumentNullException(nameof(entry)); } using (WriteLock.Write()) @@ -122,7 +121,7 @@ namespace Emby.Server.Implementations.Activity { if (entry == null) { - throw new ArgumentNullException("entry"); + throw new ArgumentNullException(nameof(entry)); } using (WriteLock.Write()) @@ -251,7 +250,7 @@ namespace Emby.Server.Implementations.Activity } } - private ActivityLogEntry GetEntry(IReadOnlyList reader) + private static ActivityLogEntry GetEntry(IReadOnlyList reader) { var index = 0; diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs index 76d0076a6..e4a2cd9df 100644 --- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs +++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using MediaBrowser.Common.Configuration; namespace Emby.Server.Implementations.AppBase @@ -12,11 +12,16 @@ namespace Emby.Server.Implementations.AppBase /// /// Initializes a new instance of the class. /// - protected BaseApplicationPaths(string programDataPath, string appFolderPath, string logDirectoryPath) + protected BaseApplicationPaths( + string programDataPath, + string appFolderPath, + string logDirectoryPath = null, + string configurationDirectoryPath = null) { ProgramDataPath = programDataPath; ProgramSystemPath = appFolderPath; LogDirectoryPath = logDirectoryPath; + ConfigurationDirectoryPath = configurationDirectoryPath; } public string ProgramDataPath { get; private set; } @@ -50,61 +55,31 @@ namespace Emby.Server.Implementations.AppBase } private const string _virtualDataPath = "%AppDataPath%"; - public string VirtualDataPath - { - get - { - return _virtualDataPath; - } - } + public string VirtualDataPath => _virtualDataPath; /// /// Gets the image cache path. /// /// The image cache path. - public string ImageCachePath - { - get - { - return Path.Combine(CachePath, "images"); - } - } + public string ImageCachePath => Path.Combine(CachePath, "images"); /// /// Gets the path to the plugin directory /// /// The plugins path. - public string PluginsPath - { - get - { - return Path.Combine(ProgramDataPath, "plugins"); - } - } + public string PluginsPath => Path.Combine(ProgramDataPath, "plugins"); /// /// Gets the path to the plugin configurations directory /// /// The plugin configurations path. - public string PluginConfigurationsPath - { - get - { - return Path.Combine(PluginsPath, "configurations"); - } - } + public string PluginConfigurationsPath => Path.Combine(PluginsPath, "configurations"); /// /// Gets the path to where temporary update files will be stored /// /// The plugin configurations path. - public string TempUpdatePath - { - get - { - return Path.Combine(ProgramDataPath, "updates"); - } - } + public string TempUpdatePath => Path.Combine(ProgramDataPath, "updates"); /// /// The _log directory @@ -128,12 +103,14 @@ namespace Emby.Server.Implementations.AppBase return _logDirectoryPath; } - set - { - _logDirectoryPath = value; - } + set => _logDirectoryPath = value; } + /// + /// The _config directory + /// + private string _configurationDirectoryPath; + /// /// Gets the path to the application configuration root directory /// @@ -142,21 +119,23 @@ namespace Emby.Server.Implementations.AppBase { get { - return Path.Combine(ProgramDataPath, "config"); + if (string.IsNullOrEmpty(_configurationDirectoryPath)) + { + _configurationDirectoryPath = Path.Combine(ProgramDataPath, "config"); + + Directory.CreateDirectory(_configurationDirectoryPath); + } + + return _configurationDirectoryPath; } + set => _configurationDirectoryPath = value; } /// /// Gets the path to the system configuration file /// /// The system configuration file path. - public string SystemConfigurationFilePath - { - get - { - return Path.Combine(ConfigurationDirectoryPath, "system.xml"); - } - } + public string SystemConfigurationFilePath => Path.Combine(ConfigurationDirectoryPath, "system.xml"); /// /// The _cache directory @@ -179,22 +158,13 @@ namespace Emby.Server.Implementations.AppBase return _cachePath; } - set - { - _cachePath = value; - } + set => _cachePath = value; } /// /// Gets the folder path to the temp directory within the cache folder /// /// The temp directory. - public string TempDirectory - { - get - { - return Path.Combine(CachePath, "temp"); - } - } + public string TempDirectory => Path.Combine(CachePath, "temp"); } } diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index bc5168fe8..59c7c655f 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; @@ -9,8 +9,8 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.AppBase { @@ -99,6 +99,7 @@ namespace Emby.Server.Implementations.AppBase /// The application paths. /// The logger factory. /// The XML serializer. + /// The file system protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { CommonApplicationPaths = applicationPaths; @@ -150,12 +151,12 @@ namespace Emby.Server.Implementations.AppBase /// Replaces the configuration. /// /// The new configuration. - /// newConfiguration + /// newConfiguration public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration) { if (newConfiguration == null) { - throw new ArgumentNullException("newConfiguration"); + throw new ArgumentNullException(nameof(newConfiguration)); } ValidateCachePath(newConfiguration); @@ -187,7 +188,7 @@ namespace Emby.Server.Implementations.AppBase /// Replaces the cache path. /// /// The new configuration. - /// + /// private void ValidateCachePath(BaseApplicationConfiguration newConfig) { var newPath = newConfig.CachePath; @@ -283,7 +284,7 @@ namespace Emby.Server.Implementations.AppBase validatingStore.Validate(currentConfiguration, configuration); } - NamedConfigurationUpdating?.Invoke( this, new ConfigurationUpdateEventArgs + NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs { Key = key, NewConfiguration = configuration diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index d6a41dd67..ee6da95fe 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using MediaBrowser.Model.IO; @@ -18,6 +18,7 @@ namespace Emby.Server.Implementations.AppBase /// The type. /// The path. /// The XML serializer. + /// The file system /// System.Object. public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 9b9c6146f..c8c4da0f7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,9 +1,24 @@ -using Emby.Common.Implementations.Serialization; -using Emby.Drawing; -using Emby.Photos; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Emby.Common.Implementations.Serialization; using Emby.Dlna; using Emby.Dlna.Main; using Emby.Dlna.Ssdp; +using Emby.Drawing; +using Emby.Notifications; +using Emby.Photos; using Emby.Server.Implementations.Activity; using Emby.Server.Implementations.Archiving; using Emby.Server.Implementations.Channels; @@ -22,7 +37,6 @@ using Emby.Server.Implementations.Library; using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; using Emby.Server.Implementations.Net; -using Emby.Notifications; using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.Reflection; using Emby.Server.Implementations.ScheduledTasks; @@ -40,10 +54,9 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Common.Security; using MediaBrowser.Common.Updates; using MediaBrowser.Controller; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Chapters; using MediaBrowser.Controller.Collections; @@ -76,17 +89,16 @@ using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; +using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; -using MediaBrowser.Model.News; using MediaBrowser.Model.Reflection; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; -using MediaBrowser.Model.Text; using MediaBrowser.Model.Threading; using MediaBrowser.Model.Updates; using MediaBrowser.Model.Xml; @@ -95,26 +107,12 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Subtitles; using MediaBrowser.WebDashboard.Api; using MediaBrowser.XbmcMetadata.Providers; +using Microsoft.Extensions.Logging; using ServiceStack; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Threading; -using System.Threading.Tasks; +using ServiceStack.Text.Jsv; using StringExtensions = MediaBrowser.Controller.Extensions.StringExtensions; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; -using MediaBrowser.Controller.Authentication; -using System.Diagnostics; -using ServiceStack.Text.Jsv; -using Microsoft.Extensions.Logging; +using UtfUnknown; namespace Emby.Server.Implementations { @@ -133,13 +131,7 @@ namespace Emby.Server.Implementations /// Gets or sets a value indicating whether this instance can self update. /// /// true if this instance can self update; otherwise, false. - public virtual bool CanSelfUpdate - { - get - { - return false; - } - } + public virtual bool CanSelfUpdate => false; public virtual bool CanLaunchWebBrowser { @@ -238,7 +230,6 @@ namespace Emby.Server.Implementations { get { - #if BETA return PackageVersionClass.Beta; #endif @@ -246,10 +237,7 @@ namespace Emby.Server.Implementations } } - public virtual string OperatingSystemDisplayName - { - get { return EnvironmentInfo.OperatingSystemName; } - } + public virtual string OperatingSystemDisplayName => EnvironmentInfo.OperatingSystemName; /// /// The container @@ -262,10 +250,7 @@ namespace Emby.Server.Implementations /// Gets the server configuration manager. /// /// The server configuration manager. - public IServerConfigurationManager ServerConfigurationManager - { - get { return (IServerConfigurationManager)ConfigurationManager; } - } + public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager; /// /// Gets the configuration manager. @@ -278,7 +263,7 @@ namespace Emby.Server.Implementations protected virtual IResourceFileManager CreateResourceFileManager() { - return new ResourceFileManager(HttpResultFactory, LoggerFactory.CreateLogger("ResourceManager"), FileSystemManager); + return new ResourceFileManager(HttpResultFactory, LoggerFactory, FileSystemManager); } /// @@ -324,7 +309,6 @@ namespace Emby.Server.Implementations private IEncodingManager EncodingManager { get; set; } private IChannelManager ChannelManager { get; set; } - protected ITextEncoding TextEncoding { get; private set; } /// /// Gets or sets the user data repository. @@ -353,11 +337,6 @@ namespace Emby.Server.Implementations /// /// The installation manager. protected IInstallationManager InstallationManager { get; private set; } - /// - /// Gets the security manager. - /// - /// The security manager. - protected ISecurityManager SecurityManager { get; private set; } /// /// Gets or sets the zip client. @@ -369,7 +348,6 @@ namespace Emby.Server.Implementations public StartupOptions StartupOptions { get; private set; } - internal IPowerManagement PowerManagement { get; private set; } internal IImageEncoder ImageEncoder { get; private set; } protected IProcessFactory ProcessFactory { get; private set; } @@ -391,7 +369,6 @@ namespace Emby.Server.Implementations ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, - IPowerManagement powerManagement, IEnvironmentInfo environmentInfo, IImageEncoder imageEncoder, ISystemEvents systemEvents, @@ -401,7 +378,7 @@ namespace Emby.Server.Implementations // hack alert, until common can target .net core BaseExtensions.CryptographyProvider = CryptographyProvider; - XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory.CreateLogger("XmlSerializer")); + XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory); NetworkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -417,7 +394,6 @@ namespace Emby.Server.Implementations Logger = LoggerFactory.CreateLogger("App"); StartupOptions = options; - PowerManagement = powerManagement; ImageEncoder = imageEncoder; @@ -452,18 +428,20 @@ namespace Emby.Server.Implementations _validAddressResults.Clear(); } - private Version _version; + public string ApplicationVersion => typeof(ApplicationHost).Assembly.GetName().Version.ToString(3); + /// - /// Gets the current application version + /// Gets the current application user agent /// - /// The application version. - public Version ApplicationVersion - { - get - { - return _version ?? (_version = typeof(ApplicationHost).Assembly.GetName().Version); - } - } + /// The application user agent. + public string ApplicationUserAgent => Name.Replace(' ','-') + "/" + ApplicationVersion; + + private string _productName; + /// + /// Gets the current application name + /// + /// The application name. + public string ApplicationProductName => _productName ?? (_productName = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName); private DeviceId _deviceId; public string SystemId @@ -472,7 +450,7 @@ namespace Emby.Server.Implementations { if (_deviceId == null) { - _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger("SystemId"), FileSystemManager); + _deviceId = new DeviceId(ApplicationPaths, LoggerFactory, FileSystemManager); } return _deviceId.Value; @@ -483,15 +461,9 @@ namespace Emby.Server.Implementations /// Gets the name. /// /// The name. - public string Name - { - get - { - return "Emby Server"; - } - } + public string Name => ApplicationProductName; - private Tuple GetAssembly(Type type) + private static Tuple GetAssembly(Type type) { var assembly = type.GetTypeInfo().Assembly; string path = null; @@ -504,14 +476,6 @@ namespace Emby.Server.Implementations return new StreamHelper(); } - public virtual bool SupportsAutoRunAtStartup - { - get - { - return EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows; - } - } - /// /// Creates an instance of type and resolves all constructor dependancies /// @@ -525,7 +489,7 @@ namespace Emby.Server.Implementations /// /// Creates the instance safe. /// - /// The type. + /// The type information. /// System.Object. protected object CreateInstanceSafe(Tuple typeInfo) { @@ -552,7 +516,7 @@ namespace Emby.Server.Implementations protected void RegisterSingleInstance(T obj, bool manageLifetime = true) where T : class { - Container.RegisterSingleton(obj); + Container.RegisterInstance(obj); if (manageLifetime) { @@ -617,7 +581,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error loading assembly {file}", file); + Logger.LogError(ex, "Error loading assembly {File}", file); return null; } } @@ -692,8 +656,6 @@ namespace Emby.Server.Implementations { Resolve().AddTasks(GetExports(false)); - ConfigureAutorun(); - ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated; MediaEncoder.Init(); @@ -747,26 +709,6 @@ namespace Emby.Server.Implementations } } - /// - /// Configures the autorun. - /// - private void ConfigureAutorun() - { - try - { - ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error configuring autorun"); - } - } - - private IJsonSerializer CreateJsonSerializer() - { - return new JsonSerializer(FileSystemManager, LoggerFactory.CreateLogger("JsonSerializer")); - } - public void Init() { HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber; @@ -779,7 +721,7 @@ namespace Emby.Server.Implementations HttpsPort = ServerConfiguration.DefaultHttpsPort; } - JsonSerializer = CreateJsonSerializer(); + JsonSerializer = new JsonSerializer(FileSystemManager); if (Plugins != null) { @@ -804,7 +746,7 @@ namespace Emby.Server.Implementations protected virtual IHttpClient CreateHttpClient() { - return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory.CreateLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent); + return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory, FileSystemManager, () => ApplicationUserAgent); } public static IStreamHelper StreamHelper { get; set; } @@ -837,7 +779,7 @@ namespace Emby.Server.Implementations IsoManager = new IsoManager(); RegisterSingleInstance(IsoManager); - TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory.CreateLogger("TaskManager"), FileSystemManager, SystemEvents); + TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager, SystemEvents); RegisterSingleInstance(TaskManager); RegisterSingleInstance(XmlSerializer); @@ -854,15 +796,10 @@ namespace Emby.Server.Implementations RegisterSingleInstance(CryptographyProvider); - SocketFactory = new SocketFactory(LoggerFactory.CreateLogger("SocketFactory")); + SocketFactory = new SocketFactory(); RegisterSingleInstance(SocketFactory); - RegisterSingleInstance(PowerManagement); - - SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LoggerFactory, FileSystemManager, CryptographyProvider); - RegisterSingleInstance(SecurityManager); - - InstallationManager = new InstallationManager(LoggerFactory.CreateLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); + InstallationManager = new InstallationManager(LoggerFactory, this, ApplicationPaths, HttpClient, JsonSerializer, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); RegisterSingleInstance(InstallationManager); ZipClient = new ZipClient(FileSystemManager); @@ -877,15 +814,13 @@ namespace Emby.Server.Implementations RegisterSingleInstance(ServerConfigurationManager); IAssemblyInfo assemblyInfo = new AssemblyInfo(); - RegisterSingleInstance(assemblyInfo); + RegisterSingleInstance(assemblyInfo); - LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory.CreateLogger("LocalizationManager"), assemblyInfo, new TextLocalizer()); + LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory, assemblyInfo, new TextLocalizer()); StringExtensions.LocalizationManager = LocalizationManager; RegisterSingleInstance(LocalizationManager); - TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LoggerFactory.CreateLogger("TextEncoding"), JsonSerializer); - RegisterSingleInstance(TextEncoding); - BlurayExaminer = new BdInfoExaminer(FileSystemManager, TextEncoding); + BlurayExaminer = new BdInfoExaminer(FileSystemManager); RegisterSingleInstance(BlurayExaminer); RegisterSingleInstance(new XmlReaderSettingsFactory()); @@ -897,23 +832,24 @@ namespace Emby.Server.Implementations // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it RegisterSingleInstance(UserRepository); - var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory.CreateLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager); + var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager); DisplayPreferencesRepository = displayPreferencesRepo; RegisterSingleInstance(DisplayPreferencesRepository); - var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory.CreateLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); + var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); ItemRepository = itemRepo; RegisterSingleInstance(ItemRepository); AuthenticationRepository = GetAuthenticationRepository(); RegisterSingleInstance(AuthenticationRepository); - UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); + UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); RegisterSingleInstance(UserManager); - LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager); + LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager); RegisterSingleInstance(LibraryManager); + // TODO wtaylor: investigate use of second music manager var musicManager = new MusicManager(LibraryManager); RegisterSingleInstance(new MusicManager(LibraryManager)); @@ -926,11 +862,10 @@ namespace Emby.Server.Implementations Certificate = GetCertificate(CertificateInfo); HttpServer = new HttpListenerHost(this, - LoggerFactory.CreateLogger("HttpServer"), + LoggerFactory, ServerConfigurationManager, "web/index.html", NetworkManager, - TextEncoding, JsonSerializer, XmlSerializer, GetParseFn); @@ -947,37 +882,37 @@ namespace Emby.Server.Implementations var encryptionManager = new EncryptionManager(); RegisterSingleInstance(encryptionManager); - DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager); + DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory, NetworkManager); RegisterSingleInstance(DeviceManager); - MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); + MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); RegisterSingleInstance(MediaSourceManager); - SubtitleManager = new SubtitleManager(LoggerFactory.CreateLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); + SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); RegisterSingleInstance(SubtitleManager); ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); RegisterSingleInstance(ProviderManager); - DtoService = new DtoService(LoggerFactory.CreateLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); + DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); RegisterSingleInstance(DtoService); - ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory.CreateLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); + ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); RegisterSingleInstance(ChannelManager); - SessionManager = new SessionManager(UserDataManager, LoggerFactory.CreateLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); + SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); RegisterSingleInstance(SessionManager); - var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory.CreateLogger("Dlna"), JsonSerializer, this, assemblyInfo); + var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this, assemblyInfo); RegisterSingleInstance(dlnaManager); - CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("CollectionManager"), ProviderManager); + CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager); RegisterSingleInstance(CollectionManager); - PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("PlaylistManager"), UserManager, ProviderManager); - RegisterSingleInstance(PlaylistManager); + PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager); + RegisterSingleInstance(PlaylistManager); - LiveTvManager = new LiveTvManager(this, HttpClient, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager, () => ChannelManager); + LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, () => ChannelManager); RegisterSingleInstance(LiveTvManager); UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager); @@ -986,35 +921,35 @@ namespace Emby.Server.Implementations NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager); RegisterSingleInstance(NotificationManager); - RegisterSingleInstance(new DeviceDiscovery(LoggerFactory.CreateLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory)); + RegisterSingleInstance(new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory, TimerFactory)); - ChapterManager = new ChapterManager(LibraryManager, LoggerFactory.CreateLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); + ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); RegisterMediaEncoder(assemblyInfo); - EncodingManager = new Emby.Server.Implementations.MediaEncoder.EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager); + EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager); RegisterSingleInstance(EncodingManager); var activityLogRepo = GetActivityLogRepository(); RegisterSingleInstance(activityLogRepo); - RegisterSingleInstance(new ActivityManager(LoggerFactory.CreateLogger("ActivityManager"), activityLogRepo, UserManager)); + RegisterSingleInstance(new ActivityManager(LoggerFactory, activityLogRepo, UserManager)); var authContext = new AuthorizationContext(AuthenticationRepository, UserManager); RegisterSingleInstance(authContext); RegisterSingleInstance(new SessionContext(UserManager, authContext, SessionManager)); AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager); - RegisterSingleInstance(AuthService); + RegisterSingleInstance(AuthService); - SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory.CreateLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding); + SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory); RegisterSingleInstance(SubtitleEncoder); RegisterSingleInstance(CreateResourceFileManager()); displayPreferencesRepo.Initialize(); - var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager); + var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths); SetStaticProperties(); @@ -1035,13 +970,7 @@ namespace Emby.Server.Implementations return s => JsvReader.GetParseFn(propertyType)(s); } - public virtual string PackageRuntime - { - get - { - return "netcore"; - } - } + public virtual string PackageRuntime => "netcore"; public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo) { @@ -1073,37 +1002,7 @@ namespace Emby.Server.Implementations } } - protected string GetDefaultUserAgent() - { - var name = FormatAttribute(Name); - - return name + "/" + ApplicationVersion; - } - - private string FormatAttribute(string str) - { - var arr = str.ToCharArray(); - - arr = Array.FindAll(arr, (c => (char.IsLetterOrDigit(c) - || char.IsWhiteSpace(c)))); - - var result = new string(arr); - - if (string.IsNullOrWhiteSpace(result)) - { - result = "Emby"; - } - - return result; - } - - protected virtual bool SupportsDualModeSockets - { - get - { - return true; - } - } + protected virtual bool SupportsDualModeSockets => true; private X509Certificate GetCertificate(CertificateInfo info) { @@ -1124,7 +1023,7 @@ namespace Emby.Server.Implementations // Don't use an empty string password var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password; - X509Certificate2 localCert = new X509Certificate2(certificateLocation, password); + var localCert = new X509Certificate2(certificateLocation, password); //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { @@ -1143,7 +1042,7 @@ namespace Emby.Server.Implementations private IImageProcessor GetImageProcessor() { - return new ImageProcessor(LoggerFactory.CreateLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder); + return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder); } protected virtual FFMpegInstallInfo GetFfmpegInstallInfo() @@ -1202,7 +1101,7 @@ namespace Emby.Server.Implementations var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase); var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder( - LoggerFactory.CreateLogger("MediaEncoder"), + LoggerFactory, JsonSerializer, encoderPath, probePath, @@ -1219,8 +1118,7 @@ namespace Emby.Server.Implementations HttpClient, ZipClient, ProcessFactory, - 5000, - EnvironmentInfo); + 5000); MediaEncoder = mediaEncoder; RegisterSingleInstance(MediaEncoder); @@ -1232,7 +1130,7 @@ namespace Emby.Server.Implementations /// Task{IUserRepository}. private IUserRepository GetUserRepository() { - var repo = new SqliteUserRepository(LoggerFactory.CreateLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer); + var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer); repo.Initialize(); @@ -1241,7 +1139,7 @@ namespace Emby.Server.Implementations private IAuthenticationRepository GetAuthenticationRepository() { - var repo = new AuthenticationRepository(LoggerFactory.CreateLogger("AuthenticationRepository"), ServerConfigurationManager); + var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager); repo.Initialize(); @@ -1250,7 +1148,7 @@ namespace Emby.Server.Implementations private IActivityRepository GetActivityLogRepository() { - var repo = new ActivityRepository(LoggerFactory.CreateLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager); + var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager); repo.Initialize(); @@ -1573,8 +1471,6 @@ namespace Emby.Server.Implementations /// The instance containing the event data. protected void OnConfigurationUpdated(object sender, EventArgs e) { - ConfigureAutorun(); - var requiresRestart = false; // Don't do anything if these haven't been set yet @@ -1680,25 +1576,25 @@ namespace Emby.Server.Implementations // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that // This will prevent the .dll file from getting locked, and allow us to replace it when needed - // Include composable parts in the Api assembly + // Include composable parts in the Api assembly list.Add(GetAssembly(typeof(ApiEntryPoint))); - // Include composable parts in the Dashboard assembly + // Include composable parts in the Dashboard assembly list.Add(GetAssembly(typeof(DashboardService))); - // Include composable parts in the Model assembly + // Include composable parts in the Model assembly list.Add(GetAssembly(typeof(SystemInfo))); - // Include composable parts in the Common assembly + // Include composable parts in the Common assembly list.Add(GetAssembly(typeof(IApplicationHost))); - // Include composable parts in the Controller assembly + // Include composable parts in the Controller assembly list.Add(GetAssembly(typeof(IServerApplicationHost))); - // Include composable parts in the Providers assembly + // Include composable parts in the Providers assembly list.Add(GetAssembly(typeof(ProviderUtils))); - // Include composable parts in the Photos assembly + // Include composable parts in the Photos assembly list.Add(GetAssembly(typeof(PhotoProvider))); // Emby.Server implementations @@ -1707,16 +1603,16 @@ namespace Emby.Server.Implementations // MediaEncoding list.Add(GetAssembly(typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder))); - // Dlna + // Dlna list.Add(GetAssembly(typeof(DlnaEntryPoint))); - // Local metadata + // Local metadata list.Add(GetAssembly(typeof(BoxSetXmlSaver))); // Notifications list.Add(GetAssembly(typeof(NotificationManager))); - // Xbmc + // Xbmc list.Add(GetAssembly(typeof(ArtistNfoProvider))); list.AddRange(GetAssembliesWithPartsInternal().Select(i => new Tuple(i, null))); @@ -1869,8 +1765,7 @@ namespace Emby.Server.Implementations return false; } - Version minRequiredVersion; - if (minRequiredVersions.TryGetValue(filename, out minRequiredVersion)) + if (minRequiredVersions.TryGetValue(filename, out Version minRequiredVersion)) { try { @@ -1906,7 +1801,8 @@ namespace Emby.Server.Implementations { HasPendingRestart = HasPendingRestart, IsShuttingDown = IsShuttingDown, - Version = ApplicationVersion.ToString(), + Version = ApplicationVersion, + ProductName = ApplicationProductName, WebSocketPortNumber = HttpPort, CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(), Id = SystemId, @@ -1925,7 +1821,6 @@ namespace Emby.Server.Implementations CanLaunchWebBrowser = CanLaunchWebBrowser, WanAddress = wanAddress, HasUpdateAvailable = HasUpdateAvailable, - SupportsAutoRunAtStartup = SupportsAutoRunAtStartup, TranscodingTempPath = ApplicationPaths.TranscodingTempPath, ServerName = FriendlyName, LocalAddress = localAddress, @@ -1953,7 +1848,7 @@ namespace Emby.Server.Implementations var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false); return new PublicSystemInfo { - Version = ApplicationVersion.ToString(), + Version = ApplicationVersion, Id = SystemId, OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(), WanAddress = wanAddress, @@ -1962,18 +1857,9 @@ namespace Emby.Server.Implementations }; } - public bool EnableHttps - { - get - { - return SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps; - } - } + public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps; - public bool SupportsHttps - { - get { return Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy; } - } + public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy; public async Task GetLocalApiUrl(CancellationToken cancellationToken) { @@ -2016,7 +1902,7 @@ namespace Emby.Server.Implementations return GetLocalApiUrl(response.ReadToEnd().Trim()); } } - catch(Exception ex) + catch (Exception ex) { Logger.LogError(ex, "Error getting WAN Ip address information"); } @@ -2095,8 +1981,7 @@ namespace Emby.Server.Implementations address = address.Substring(index + 1); } - IpAddressInfo result; - if (NetworkManager.TryParseIpAddress(address.Trim('/'), out result)) + if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result)) { return result; } @@ -2115,8 +2000,7 @@ namespace Emby.Server.Implementations var apiUrl = GetLocalApiUrl(address); apiUrl += "/system/ping"; - bool cachedResult; - if (_validAddressResults.TryGetValue(apiUrl, out cachedResult)) + if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult)) { return cachedResult; } @@ -2167,15 +2051,10 @@ namespace Emby.Server.Implementations } } - public string FriendlyName - { - get - { - return string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) - ? Environment.MachineName - : ServerConfigurationManager.Configuration.ServerName; - } - } + public string FriendlyName => + string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) + ? Environment.MachineName + : ServerConfigurationManager.Configuration.ServerName; public int HttpPort { get; private set; } @@ -2212,7 +2091,7 @@ namespace Emby.Server.Implementations private bool _hasUpdateAvailable; public bool HasUpdateAvailable { - get { return _hasUpdateAvailable; } + get => _hasUpdateAvailable; set { var fireEvent = value && !_hasUpdateAvailable; @@ -2253,24 +2132,7 @@ namespace Emby.Server.Implementations } /// - /// Configures the automatic run at startup. - /// - /// if set to true [autorun]. - protected void ConfigureAutoRunAtStartup(bool autorun) - { - if (SupportsAutoRunAtStartup) - { - ConfigureAutoRunInternal(autorun); - } - } - - protected virtual void ConfigureAutoRunInternal(bool autorun) - { - throw new NotImplementedException(); - } - - /// - /// This returns localhost in the case of no external dns, and the hostname if the + /// This returns localhost in the case of no external dns, and the hostname if the /// dns is prefixed with a valid Uri prefix. /// /// The external dns prefix to get the hostname of. diff --git a/Emby.Server.Implementations/Archiving/ZipClient.cs b/Emby.Server.Implementations/Archiving/ZipClient.cs index fd61f2617..84072cde6 100644 --- a/Emby.Server.Implementations/Archiving/ZipClient.cs +++ b/Emby.Server.Implementations/Archiving/ZipClient.cs @@ -1,6 +1,5 @@ -using System.IO; +using System.IO; using MediaBrowser.Model.IO; -using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Archives.Tar; using SharpCompress.Common; @@ -15,14 +14,14 @@ namespace Emby.Server.Implementations.Archiving /// public class ZipClient : IZipClient { - private readonly IFileSystem _fileSystem; + private readonly IFileSystem _fileSystem; - public ZipClient(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } + public ZipClient(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } - /// + /// /// Extracts all. /// /// The source file. @@ -30,7 +29,7 @@ namespace Emby.Server.Implementations.Archiving /// if set to true [overwrite existing files]. public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = _fileSystem.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAll(fileStream, targetPath, overwriteExistingFiles); } @@ -116,7 +115,7 @@ namespace Emby.Server.Implementations.Archiving /// if set to true [overwrite existing files]. public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = _fileSystem.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles); } @@ -156,7 +155,7 @@ namespace Emby.Server.Implementations.Archiving /// if set to true [overwrite existing files]. public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = _fileSystem.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles); } diff --git a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs index a29f55f16..b27f84848 100644 --- a/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs +++ b/Emby.Server.Implementations/Branding/BrandingConfigurationFactory.cs @@ -1,6 +1,6 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Branding; using System.Collections.Generic; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Branding; namespace Emby.Server.Implementations.Branding { diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs index 007f60a9b..718129ef0 100644 --- a/Emby.Server.Implementations/Browser/BrowserLauncher.cs +++ b/Emby.Server.Implementations/Browser/BrowserLauncher.cs @@ -1,5 +1,5 @@ -using MediaBrowser.Controller; using System; +using MediaBrowser.Controller; namespace Emby.Server.Implementations.Browser { @@ -41,7 +41,7 @@ namespace Emby.Server.Implementations.Browser } catch (NotSupportedException) { - + } catch (Exception) { diff --git a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs index 8448d3640..c10f00f9b 100644 --- a/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs +++ b/Emby.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Dto; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Dto; namespace Emby.Server.Implementations.Channels { diff --git a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs index a6643e83c..bafa68818 100644 --- a/Emby.Server.Implementations/Channels/ChannelImageProvider.cs +++ b/Emby.Server.Implementations/Channels/ChannelImageProvider.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.Channels { @@ -30,10 +30,7 @@ namespace Emby.Server.Implementations.Channels return channel.GetChannelImage(type, cancellationToken); } - public string Name - { - get { return "Channel Image Provider"; } - } + public string Name => "Channel Image Provider"; public bool Supports(BaseItem item) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index c2160d338..660547c85 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -1,37 +1,30 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Channels; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; -using MediaBrowser.Model.IO; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Channels; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Tasks; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Channels { @@ -52,12 +45,23 @@ namespace Emby.Server.Implementations.Channels private readonly ILocalizationManager _localization; - public ChannelManager(IUserManager userManager, IDtoService dtoService, ILibraryManager libraryManager, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IUserDataManager userDataManager, IJsonSerializer jsonSerializer, ILocalizationManager localization, IHttpClient httpClient, IProviderManager providerManager) + public ChannelManager( + IUserManager userManager, + IDtoService dtoService, + ILibraryManager libraryManager, + ILoggerFactory loggerFactory, + IServerConfigurationManager config, + IFileSystem fileSystem, + IUserDataManager userDataManager, + IJsonSerializer jsonSerializer, + ILocalizationManager localization, + IHttpClient httpClient, + IProviderManager providerManager) { _userManager = userManager; _dtoService = dtoService; _libraryManager = libraryManager; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(ChannelManager)); _config = config; _fileSystem = fileSystem; _userDataManager = userDataManager; @@ -67,13 +71,7 @@ namespace Emby.Server.Implementations.Channels _providerManager = providerManager; } - private TimeSpan CacheLength - { - get - { - return TimeSpan.FromHours(3); - } - } + private static TimeSpan CacheLength => TimeSpan.FromHours(3); public void AddParts(IEnumerable channels) { @@ -269,6 +267,7 @@ namespace Emby.Server.Implementations.Channels { }; + //TODO Fix The co-variant conversion (internalResult.Items) between Folder[] and BaseItem[], this can generate runtime issues. var returnItems = _dtoService.GetBaseItemDtos(internalResult.Items, dtoOptions, user); var result = new QueryResult @@ -399,9 +398,7 @@ namespace Emby.Server.Implementations.Channels private async Task> GetChannelItemMediaSourcesInternal(IRequiresMediaInfoCallback channel, string id, CancellationToken cancellationToken) { - Tuple> cachedInfo; - - if (_channelItemMediaInfo.TryGetValue(id, out cachedInfo)) + if (_channelItemMediaInfo.TryGetValue(id, out Tuple> cachedInfo)) { if ((DateTime.UtcNow - cachedInfo.Item1).TotalMinutes < 5) { @@ -419,7 +416,7 @@ namespace Emby.Server.Implementations.Channels return list; } - private MediaSourceInfo NormalizeMediaSource(BaseItem item, MediaSourceInfo info) + private static MediaSourceInfo NormalizeMediaSource(BaseItem item, MediaSourceInfo info) { info.RunTimeTicks = info.RunTimeTicks ?? item.RunTimeTicks; @@ -492,7 +489,7 @@ namespace Emby.Server.Implementations.Channels return item; } - private string GetOfficialRating(ChannelParentalRating rating) + private static string GetOfficialRating(ChannelParentalRating rating) { switch (rating) { @@ -533,7 +530,7 @@ namespace Emby.Server.Implementations.Channels { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } var channel = GetChannel(id); @@ -577,7 +574,7 @@ namespace Emby.Server.Implementations.Channels { if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } return _libraryManager.GetNewItemId("Channel " + name, typeof(Channel)); } @@ -630,7 +627,7 @@ namespace Emby.Server.Implementations.Channels if (sortByPremiereDate) { - query.OrderBy = new [] + query.OrderBy = new[] { new ValueTuple(ItemSortBy.PremiereDate, SortOrder.Descending), new ValueTuple(ItemSortBy.ProductionYear, SortOrder.Descending), @@ -639,7 +636,7 @@ namespace Emby.Server.Implementations.Channels } else { - query.OrderBy = new [] + query.OrderBy = new[] { new ValueTuple(ItemSortBy.DateCreated, SortOrder.Descending) }; @@ -891,7 +888,7 @@ namespace Emby.Server.Implementations.Channels filename + ".json"); } - private string GetIdToHash(string externalId, string channelName) + private static string GetIdToHash(string externalId, string channelName) { // Increment this as needed to force new downloads // Incorporate Name because it's being used to convert channel entity to provider @@ -902,7 +899,7 @@ namespace Emby.Server.Implementations.Channels where T : BaseItem, new() { var id = _libraryManager.GetNewItemId(GetIdToHash(idString, channelName), typeof(T)); - + T item = null; try @@ -1187,7 +1184,7 @@ namespace Emby.Server.Implementations.Channels { if (channel == null) { - throw new ArgumentNullException("channel"); + throw new ArgumentNullException(nameof(channel)); } var result = GetAllChannels() diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs index bd717bc6a..ad6c537ef 100644 --- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Channels { diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs index ab6acf3c5..844f77a1a 100644 --- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs @@ -1,12 +1,12 @@ -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Progress; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.Tasks; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Channels { @@ -25,35 +25,17 @@ namespace Emby.Server.Implementations.Channels _libraryManager = libraryManager; } - public string Name - { - get { return "Refresh Channels"; } - } + public string Name => "Refresh Channels"; - public string Description - { - get { return "Refreshes internet channel information."; } - } + public string Description => "Refreshes internet channel information."; - public string Category - { - get { return "Internet Channels"; } - } + public string Category => "Internet Channels"; - public bool IsHidden - { - get { return ((ChannelManager)_channelManager).Channels.Length == 0; } - } + public bool IsHidden => ((ChannelManager)_channelManager).Channels.Length == 0; - public bool IsEnabled - { - get { return true; } - } + public bool IsEnabled => true; - public bool IsLogged - { - get { return true; } - } + public bool IsLogged => true; public async Task Execute(CancellationToken cancellationToken, IProgress progress) { @@ -70,16 +52,13 @@ namespace Emby.Server.Implementations.Channels /// public IEnumerable GetDefaultTriggers() { - return new[] { - + return new[] { + // Every so often new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks} }; } - public string Key - { - get { return "RefreshInternetChannels"; } - } + public string Key => "RefreshInternetChannels"; } } diff --git a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs index 858dada4b..6642d1ef4 100644 --- a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs +++ b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs @@ -1,4 +1,8 @@ -using MediaBrowser.Common.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using Emby.Server.Implementations.Images; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; @@ -6,13 +10,8 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Emby.Server.Implementations.Images; -using MediaBrowser.Model.IO; using MediaBrowser.Model.Extensions; -using System; +using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Collections { diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index d1d793136..0166bbc5a 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -1,24 +1,22 @@ -using MediaBrowser.Common.Events; -using MediaBrowser.Controller.Collections; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Extensions; using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Collections { @@ -36,12 +34,19 @@ namespace Emby.Server.Implementations.Collections public event EventHandler ItemsAddedToCollection; public event EventHandler ItemsRemovedFromCollection; - public CollectionManager(ILibraryManager libraryManager, IApplicationPaths appPaths, ILocalizationManager localizationManager, IFileSystem fileSystem, ILibraryMonitor iLibraryMonitor, ILogger logger, IProviderManager providerManager) + public CollectionManager( + ILibraryManager libraryManager, + IApplicationPaths appPaths, + ILocalizationManager localizationManager, + IFileSystem fileSystem, + ILibraryMonitor iLibraryMonitor, + ILoggerFactory loggerFactory, + IProviderManager providerManager) { _libraryManager = libraryManager; _fileSystem = fileSystem; _iLibraryMonitor = iLibraryMonitor; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(CollectionManager)); _providerManager = providerManager; _localizationManager = localizationManager; _appPaths = appPaths; diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index 015421197..ab2e1c9a9 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using Emby.Server.Implementations.AppBase; @@ -8,8 +8,8 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Configuration { @@ -38,28 +38,19 @@ namespace Emby.Server.Implementations.Configuration /// Gets the type of the configuration. /// /// The type of the configuration. - protected override Type ConfigurationType - { - get { return typeof(ServerConfiguration); } - } + protected override Type ConfigurationType => typeof(ServerConfiguration); /// /// Gets the application paths. /// /// The application paths. - public IServerApplicationPaths ApplicationPaths - { - get { return (IServerApplicationPaths)CommonApplicationPaths; } - } + public IServerApplicationPaths ApplicationPaths => (IServerApplicationPaths)CommonApplicationPaths; /// /// Gets the configuration. /// /// The configuration. - public ServerConfiguration Configuration - { - get { return (ServerConfiguration)CommonConfiguration; } - } + public ServerConfiguration Configuration => (ServerConfiguration)CommonConfiguration; /// /// Called when [configuration updated]. @@ -128,7 +119,7 @@ namespace Emby.Server.Implementations.Configuration /// Replaces the configuration. /// /// The new configuration. - /// + /// public override void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration) { var newConfig = (ServerConfiguration)newConfiguration; @@ -146,7 +137,7 @@ namespace Emby.Server.Implementations.Configuration /// Validates the SSL certificate. /// /// The new configuration. - /// + /// private void ValidateSslCertificate(BaseApplicationConfiguration newConfig) { var serverConfig = (ServerConfiguration)newConfig; @@ -168,7 +159,7 @@ namespace Emby.Server.Implementations.Configuration /// Validates the metadata path. /// /// The new configuration. - /// + /// private void ValidateMetadataPath(ServerConfiguration newConfig) { var newPath = newConfig.MetadataPath; diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 6402da0c9..09fdbc856 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Security.Cryptography; using System.Text; diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 59776c373..0f432c36c 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -1,12 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using SQLitePCL.pretty; using System.Linq; +using System.Threading; +using Microsoft.Extensions.Logging; using SQLitePCL; +using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data { @@ -24,15 +23,9 @@ namespace Emby.Server.Implementations.Data WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); } - protected TransactionMode TransactionMode - { - get { return TransactionMode.Deferred; } - } + protected TransactionMode TransactionMode => TransactionMode.Deferred; - protected TransactionMode ReadTransactionMode - { - get { return TransactionMode.Deferred; } - } + protected TransactionMode ReadTransactionMode => TransactionMode.Deferred; internal static int ThreadSafeMode { get; set; } @@ -58,10 +51,7 @@ namespace Emby.Server.Implementations.Data private string _defaultWal; protected ManagedConnection _connection; - protected virtual bool EnableSingleConnection - { - get { return true; } - } + protected virtual bool EnableSingleConnection => true; protected ManagedConnection CreateConnection(bool isReadOnly = false) { @@ -238,21 +228,9 @@ namespace Emby.Server.Implementations.Data Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First()); } - protected virtual bool EnableTempStoreMemory - { - get - { - return false; - } - } + protected virtual bool EnableTempStoreMemory => false; - protected virtual int? CacheSize - { - get - { - return null; - } - } + protected virtual int? CacheSize => null; internal static void CheckOk(int rc) { @@ -276,7 +254,7 @@ namespace Emby.Server.Implementations.Data { if (_disposed) { - throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed."); + throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed."); } } diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs index 536cf21f6..dcfe14943 100644 --- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs +++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs @@ -1,16 +1,12 @@ -using MediaBrowser.Common.Progress; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Data { diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs index 91a2dfdf6..b8f1e581a 100644 --- a/Emby.Server.Implementations/Data/ManagedConnection.cs +++ b/Emby.Server.Implementations/Data/ManagedConnection.cs @@ -1,13 +1,10 @@ -using System; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data { - public class ManagedConnection : IDisposable + public class ManagedConnection : IDisposable { private SQLiteDatabaseConnection db; private readonly bool _closeOnDispose; @@ -50,7 +47,7 @@ namespace Emby.Server.Implementations.Data public T RunInTransaction(Func action, TransactionMode mode) { - return db.RunInTransaction(action, mode); + return db.RunInTransaction(action, mode); } public IEnumerable> Query(string sql) diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 00e1956cf..3d60925da 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Threading; @@ -7,8 +7,8 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data @@ -20,8 +20,8 @@ namespace Emby.Server.Implementations.Data { protected IFileSystem FileSystem { get; private set; } - public SqliteDisplayPreferencesRepository(ILogger logger, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IFileSystem fileSystem) - : base(logger) + public SqliteDisplayPreferencesRepository(ILoggerFactory loggerFactory, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IFileSystem fileSystem) + : base(loggerFactory.CreateLogger(nameof(SqliteDisplayPreferencesRepository))) { _jsonSerializer = jsonSerializer; FileSystem = fileSystem; @@ -32,13 +32,7 @@ namespace Emby.Server.Implementations.Data /// Gets the name of the repository /// /// The name. - public string Name - { - get - { - return "SQLite"; - } - } + public string Name => "SQLite"; /// /// The _json serializer @@ -89,16 +83,16 @@ namespace Emby.Server.Implementations.Data /// The client. /// The cancellation token. /// Task. - /// item + /// item public void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken) { if (displayPreferences == null) { - throw new ArgumentNullException("displayPreferences"); + throw new ArgumentNullException(nameof(displayPreferences)); } if (string.IsNullOrEmpty(displayPreferences.Id)) { - throw new ArgumentNullException("displayPreferences.Id"); + throw new ArgumentNullException(nameof(displayPreferences.Id)); } cancellationToken.ThrowIfCancellationRequested(); @@ -137,12 +131,12 @@ namespace Emby.Server.Implementations.Data /// The user id. /// The cancellation token. /// Task. - /// item + /// item public void SaveAllDisplayPreferences(IEnumerable displayPreferences, Guid userId, CancellationToken cancellationToken) { if (displayPreferences == null) { - throw new ArgumentNullException("displayPreferences"); + throw new ArgumentNullException(nameof(displayPreferences)); } cancellationToken.ThrowIfCancellationRequested(); @@ -169,12 +163,12 @@ namespace Emby.Server.Implementations.Data /// The user id. /// The client. /// Task{DisplayPreferences}. - /// item + /// item public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, Guid userId, string client) { if (string.IsNullOrEmpty(displayPreferencesId)) { - throw new ArgumentNullException("displayPreferencesId"); + throw new ArgumentNullException(nameof(displayPreferencesId)); } var guidId = displayPreferencesId.GetMD5(); @@ -208,7 +202,7 @@ namespace Emby.Server.Implementations.Data /// /// The user id. /// Task{DisplayPreferences}. - /// item + /// item public IEnumerable GetAllDisplayPreferences(Guid userId) { var list = new List(); diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index a755c65f4..a486cb1a0 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -1,10 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; -using MediaBrowser.Model.IO; +using System.IO; using MediaBrowser.Model.Serialization; using SQLitePCL.pretty; -using System.IO; namespace Emby.Server.Implementations.Data { @@ -14,7 +13,7 @@ namespace Emby.Server.Implementations.Data { if (queries == null) { - throw new ArgumentNullException("queries"); + throw new ArgumentNullException(nameof(queries)); } connection.RunInTransaction(conn => @@ -115,9 +114,7 @@ namespace Emby.Server.Implementations.Data { var dateText = result.ToString(); - DateTime dateTimeResult; - - if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dateTimeResult)) + if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var dateTimeResult)) { return dateTimeResult.ToUniversalTime(); } @@ -129,12 +126,12 @@ namespace Emby.Server.Implementations.Data /// Serializes to bytes. /// /// System.Byte[][]. - /// obj + /// obj public static byte[] SerializeToBytes(this IJsonSerializer json, object obj) { if (obj == null) { - throw new ArgumentNullException("obj"); + throw new ArgumentNullException(nameof(obj)); } using (var stream = new MemoryStream()) @@ -202,8 +199,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, double value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -215,8 +211,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, string value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { if (value == null) { @@ -235,8 +230,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, bool value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -248,8 +242,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, float value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -261,8 +254,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, int value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -274,8 +266,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, Guid value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value.ToGuidBlob()); } @@ -287,8 +278,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, DateTime value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value.ToDateTimeParamValue()); } @@ -300,8 +290,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, long value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -313,8 +302,7 @@ namespace Emby.Server.Implementations.Data public static void TryBind(this IStatement statement, string name, byte[] value) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.Bind(value); } @@ -326,8 +314,7 @@ namespace Emby.Server.Implementations.Data public static void TryBindNull(this IStatement statement, string name) { - IBindParameter bindParam; - if (statement.BindParameters.TryGetValue(name, out bindParam)) + if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { bindParam.BindNull(); } diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 0f9770e8f..492adef6a 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -6,17 +6,17 @@ using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading; -using System.Threading.Tasks; -using Emby.Server.Implementations.Devices; using Emby.Server.Implementations.Playlists; +using MediaBrowser.Controller; using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Extensions; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Playlists; @@ -24,17 +24,13 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Reflection; -using SQLitePCL.pretty; +using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Threading; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging; +using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data { @@ -49,13 +45,7 @@ namespace Emby.Server.Implementations.Data /// Gets the name of the repository /// /// The name. - public string Name - { - get - { - return "SQLite"; - } - } + public string Name => "SQLite"; /// /// Gets the json serializer. @@ -77,16 +67,24 @@ namespace Emby.Server.Implementations.Data /// /// Initializes a new instance of the class. /// - public SqliteItemRepository(IServerConfigurationManager config, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, ILogger logger, IAssemblyInfo assemblyInfo, IFileSystem fileSystem, IEnvironmentInfo environmentInfo, ITimerFactory timerFactory) - : base(logger) + public SqliteItemRepository( + IServerConfigurationManager config, + IServerApplicationHost appHost, + IJsonSerializer jsonSerializer, + ILoggerFactory loggerFactory, + IAssemblyInfo assemblyInfo, + IFileSystem fileSystem, + IEnvironmentInfo environmentInfo, + ITimerFactory timerFactory) + : base(loggerFactory.CreateLogger(nameof(SqliteItemRepository))) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (jsonSerializer == null) { - throw new ArgumentNullException("jsonSerializer"); + throw new ArgumentNullException(nameof(jsonSerializer)); } _appHost = appHost; @@ -101,21 +99,9 @@ namespace Emby.Server.Implementations.Data private const string ChaptersTableName = "Chapters2"; - protected override int? CacheSize - { - get - { - return 20000; - } - } + protected override int? CacheSize => 20000; - protected override bool EnableTempStoreMemory - { - get - { - return true; - } - } + protected override bool EnableTempStoreMemory => true; /// /// Opens the connection to the database @@ -455,7 +441,7 @@ namespace Emby.Server.Implementations.Data "ColorTransfer" }; - private string GetSaveItemCommandText() + private static string GetSaveItemCommandText() { var saveColumns = new List { @@ -553,12 +539,12 @@ namespace Emby.Server.Implementations.Data /// /// The item. /// The cancellation token. - /// item + /// item public void SaveItem(BaseItem item, CancellationToken cancellationToken) { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } SaveItems(new List { item }, cancellationToken); @@ -568,7 +554,7 @@ namespace Emby.Server.Implementations.Data { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } CheckDisposed(); @@ -596,7 +582,7 @@ namespace Emby.Server.Implementations.Data /// /// The items. /// The cancellation token. - /// + /// /// items /// or /// cancellationToken @@ -605,7 +591,7 @@ namespace Emby.Server.Implementations.Data { if (items == null) { - throw new ArgumentNullException("items"); + throw new ArgumentNullException(nameof(items)); } cancellationToken.ThrowIfCancellationRequested(); @@ -1070,7 +1056,7 @@ namespace Emby.Server.Implementations.Data saveItemStatement.MoveNext(); } - private string SerializeProviderIds(BaseItem item) + private static string SerializeProviderIds(BaseItem item) { // Ideally we shouldn't need this IsNullOrWhiteSpace check but we're seeing some cases of bad data slip through var ids = item.ProviderIds @@ -1085,7 +1071,7 @@ namespace Emby.Server.Implementations.Data return string.Join("|", ids.Select(i => i.Key + "=" + i.Value).ToArray()); } - private void DeserializeProviderIds(string value, BaseItem item) + private static void DeserializeProviderIds(string value, BaseItem item) { if (string.IsNullOrWhiteSpace(value)) { @@ -1186,25 +1172,21 @@ namespace Emby.Server.Implementations.Data image.Path = RestorePath(parts[0]); - long ticks; - if (long.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out ticks)) + if (long.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks)) { image.DateModified = new DateTime(ticks, DateTimeKind.Utc); } - ImageType type; - if (Enum.TryParse(parts[2], true, out type)) + if (Enum.TryParse(parts[2], true, out ImageType type)) { image.Type = type; } if (parts.Length >= 5) { - int width; - int height; - if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out width)) + if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var width)) { - if (int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out height)) + if (int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out var height)) { image.Width = width; image.Height = height; @@ -1220,13 +1202,13 @@ namespace Emby.Server.Implementations.Data /// /// The id. /// BaseItem. - /// id - /// + /// id + /// public BaseItem RetrieveItem(Guid id) { if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } CheckDisposed(); @@ -1611,8 +1593,7 @@ namespace Emby.Server.Implementations.Data if (!reader.IsDBNull(index)) { - ProgramAudio audio; - if (Enum.TryParse(reader.GetString(index), true, out audio)) + if (Enum.TryParse(reader.GetString(index), true, out ProgramAudio audio)) { item.Audio = audio; } @@ -1656,9 +1637,7 @@ namespace Emby.Server.Implementations.Data item.LockedFields = reader.GetString(index).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).Select( i => { - MetadataFields parsedValue; - - if (Enum.TryParse(i, true, out parsedValue)) + if (Enum.TryParse(i, true, out MetadataFields parsedValue)) { return parsedValue; } @@ -1696,9 +1675,7 @@ namespace Emby.Server.Implementations.Data trailer.TrailerTypes = reader.GetString(index).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).Select( i => { - TrailerType parsedValue; - - if (Enum.TryParse(i, true, out parsedValue)) + if (Enum.TryParse(i, true, out TrailerType parsedValue)) { return parsedValue; } @@ -1879,8 +1856,7 @@ namespace Emby.Server.Implementations.Data if (!reader.IsDBNull(index)) { - ExtraType extraType; - if (Enum.TryParse(reader.GetString(index), true, out extraType)) + if (Enum.TryParse(reader.GetString(index), true, out ExtraType extraType)) { item.ExtraType = extraType; } @@ -1948,7 +1924,7 @@ namespace Emby.Server.Implementations.Data return item; } - private Guid[] SplitToGuids(string value) + private static Guid[] SplitToGuids(string value) { var ids = value.Split('|'); @@ -1965,9 +1941,9 @@ namespace Emby.Server.Implementations.Data /// /// Gets chapters for an item /// - /// The id. + /// The item. /// IEnumerable{ChapterInfo}. - /// id + /// id public List GetChapters(BaseItem item) { CheckDisposed(); @@ -1996,10 +1972,10 @@ namespace Emby.Server.Implementations.Data /// /// Gets a single chapter for an item /// - /// The id. + /// The item. /// The index. /// ChapterInfo. - /// id + /// id public ChapterInfo GetChapter(BaseItem item, int index) { CheckDisposed(); @@ -2067,12 +2043,12 @@ namespace Emby.Server.Implementations.Data if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } if (chapters == null) { - throw new ArgumentNullException("chapters"); + throw new ArgumentNullException(nameof(chapters)); } using (WriteLock.Write()) @@ -2144,7 +2120,7 @@ namespace Emby.Server.Implementations.Data } } - private bool EnableJoinUserData(InternalItemsQuery query) + private static bool EnableJoinUserData(InternalItemsQuery query) { if (query.User == null) { @@ -2681,7 +2657,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -2739,7 +2715,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -2928,7 +2904,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -3212,7 +3188,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -3286,7 +3262,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -3362,7 +3338,7 @@ namespace Emby.Server.Implementations.Data { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -4038,7 +4014,7 @@ namespace Emby.Server.Implementations.Data if (query.PersonIds.Length > 0) { - // TODO: Should this query with CleanName ? + // TODO: Should this query with CleanName ? var clauses = new List(); var index = 0; @@ -5171,8 +5147,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type private IEnumerable MapIncludeItemTypes(string value) { - string[] result; - if (_types.TryGetValue(value, out result)) + if (_types.TryGetValue(value, out string[] result)) { return result; } @@ -5184,7 +5159,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } CheckDisposed(); @@ -5233,7 +5208,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -5273,7 +5248,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } CheckDisposed(); @@ -5387,19 +5362,19 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (itemId.Equals(Guid.Empty)) { - throw new ArgumentNullException("itemId"); + throw new ArgumentNullException(nameof(itemId)); } if (ancestorIds == null) { - throw new ArgumentNullException("ancestorIds"); + throw new ArgumentNullException(nameof(ancestorIds)); } CheckDisposed(); var itemIdBlob = itemId.ToGuidBlob(); - // First delete + // First delete deleteAncestorsStatement.Reset(); deleteAncestorsStatement.TryBind("@ItemId", itemIdBlob); deleteAncestorsStatement.MoveNext(); @@ -5556,7 +5531,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } if (!query.Limit.HasValue) @@ -5915,19 +5890,19 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (itemId.Equals(Guid.Empty)) { - throw new ArgumentNullException("itemId"); + throw new ArgumentNullException(nameof(itemId)); } if (values == null) { - throw new ArgumentNullException("keys"); + throw new ArgumentNullException(nameof(values)); } CheckDisposed(); var guidBlob = itemId.ToGuidBlob(); - // First delete + // First delete db.Execute("delete from ItemValues where ItemId=@Id", guidBlob); InsertItemValues(guidBlob, values, db); @@ -5991,12 +5966,12 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (itemId.Equals(Guid.Empty)) { - throw new ArgumentNullException("itemId"); + throw new ArgumentNullException(nameof(itemId)); } if (people == null) { - throw new ArgumentNullException("people"); + throw new ArgumentNullException(nameof(people)); } CheckDisposed(); @@ -6102,7 +6077,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (query == null) { - throw new ArgumentNullException("query"); + throw new ArgumentNullException(nameof(query)); } var cmdText = "select " + string.Join(",", _mediaStreamSaveColumns) + " from mediastreams where"; @@ -6158,12 +6133,12 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } if (streams == null) { - throw new ArgumentNullException("streams"); + throw new ArgumentNullException(nameof(streams)); } cancellationToken.ThrowIfCancellationRequested(); diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 6d4ddcedd..7a9b72244 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -1,26 +1,25 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; using SQLitePCL.pretty; -using MediaBrowser.Controller.Library; namespace Emby.Server.Implementations.Data { public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository { - private readonly IFileSystem _fileSystem; - - public SqliteUserDataRepository(ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem) - : base(logger) + public SqliteUserDataRepository( + ILoggerFactory loggerFactory, + IApplicationPaths appPaths) + : base(loggerFactory.CreateLogger(nameof(SqliteUserDataRepository))) { - _fileSystem = fileSystem; DbFilePath = Path.Combine(appPaths.DataPath, "library.db"); } @@ -28,13 +27,7 @@ namespace Emby.Server.Implementations.Data /// Gets the name of the repository /// /// The name. - public string Name - { - get - { - return "SQLite"; - } - } + public string Name => "SQLite"; /// /// Opens the connection to the database @@ -116,7 +109,7 @@ namespace Emby.Server.Implementations.Data private List GetAllUserIdsWithUserData(IDatabaseConnection db) { - List list = new List(); + var list = new List(); using (var statement = PrepareStatement(db, "select DISTINCT UserId from UserData where UserId not null")) { @@ -136,13 +129,7 @@ namespace Emby.Server.Implementations.Data return list; } - protected override bool EnableTempStoreMemory - { - get - { - return true; - } - } + protected override bool EnableTempStoreMemory => true; /// /// Saves the user data. @@ -151,15 +138,15 @@ namespace Emby.Server.Implementations.Data { if (userData == null) { - throw new ArgumentNullException("userData"); + throw new ArgumentNullException(nameof(userData)); } if (internalUserId <= 0) { - throw new ArgumentNullException("internalUserId"); + throw new ArgumentNullException(nameof(internalUserId)); } if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } PersistUserData(internalUserId, key, userData, cancellationToken); @@ -169,11 +156,11 @@ namespace Emby.Server.Implementations.Data { if (userData == null) { - throw new ArgumentNullException("userData"); + throw new ArgumentNullException(nameof(userData)); } if (internalUserId <= 0) { - throw new ArgumentNullException("internalUserId"); + throw new ArgumentNullException(nameof(internalUserId)); } PersistAllUserData(internalUserId, userData, cancellationToken); @@ -182,7 +169,7 @@ namespace Emby.Server.Implementations.Data /// /// Persists the user data. /// - /// The user id. + /// The user id. /// The key. /// The user data. /// The cancellation token. @@ -203,7 +190,7 @@ namespace Emby.Server.Implementations.Data } } - private void SaveUserData(IDatabaseConnection db, long internalUserId, string key, UserItemData userData) + private static void SaveUserData(IDatabaseConnection db, long internalUserId, string key, UserItemData userData) { using (var statement = db.PrepareStatement("replace into UserDatas (key, userId, rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex) values (@key, @userId, @rating,@played,@playCount,@isFavorite,@playbackPositionTicks,@lastPlayedDate,@AudioStreamIndex,@SubtitleStreamIndex)")) { @@ -280,10 +267,10 @@ namespace Emby.Server.Implementations.Data /// /// Gets the user data. /// - /// The user id. + /// The user id. /// The key. /// Task{UserItemData}. - /// + /// /// userId /// or /// key @@ -292,11 +279,11 @@ namespace Emby.Server.Implementations.Data { if (internalUserId <= 0) { - throw new ArgumentNullException("internalUserId"); + throw new ArgumentNullException(nameof(internalUserId)); } if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } using (WriteLock.Read()) @@ -323,7 +310,7 @@ namespace Emby.Server.Implementations.Data { if (keys == null) { - throw new ArgumentNullException("keys"); + throw new ArgumentNullException(nameof(keys)); } if (keys.Count == 0) @@ -337,13 +324,13 @@ namespace Emby.Server.Implementations.Data /// /// Return all user-data associated with the given user /// - /// + /// /// public List GetAllUserData(long internalUserId) { if (internalUserId <= 0) { - throw new ArgumentNullException("internalUserId"); + throw new ArgumentNullException(nameof(internalUserId)); } var list = new List(); diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index d490a481e..db359d7dd 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.IO; -using System.Threading; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; namespace Emby.Server.Implementations.Data @@ -19,8 +17,11 @@ namespace Emby.Server.Implementations.Data { private readonly IJsonSerializer _jsonSerializer; - public SqliteUserRepository(ILogger logger, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer) - : base(logger) + public SqliteUserRepository( + ILoggerFactory loggerFactory, + IServerApplicationPaths appPaths, + IJsonSerializer jsonSerializer) + : base(loggerFactory.CreateLogger(nameof(SqliteUserRepository))) { _jsonSerializer = jsonSerializer; @@ -31,13 +32,7 @@ namespace Emby.Server.Implementations.Data /// Gets the name of the repository /// /// The name. - public string Name - { - get - { - return "SQLite"; - } - } + public string Name => "SQLite"; /// /// Opens the connection to the database @@ -85,7 +80,7 @@ namespace Emby.Server.Implementations.Data { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } var serialized = _jsonSerializer.SerializeToBytes(user); @@ -122,7 +117,7 @@ namespace Emby.Server.Implementations.Data { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } var serialized = _jsonSerializer.SerializeToBytes(user); @@ -207,14 +202,13 @@ namespace Emby.Server.Implementations.Data /// Deletes the user. /// /// The user. - /// The cancellation token. /// Task. - /// user + /// user public void DeleteUser(User user) { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } using (WriteLock.Write()) diff --git a/Emby.Server.Implementations/Data/TypeMapper.cs b/Emby.Server.Implementations/Data/TypeMapper.cs index f4b37749e..37c952e88 100644 --- a/Emby.Server.Implementations/Data/TypeMapper.cs +++ b/Emby.Server.Implementations/Data/TypeMapper.cs @@ -1,7 +1,7 @@ -using System; +using System; using System.Collections.Concurrent; -using MediaBrowser.Model.Reflection; using System.Linq; +using MediaBrowser.Model.Reflection; namespace Emby.Server.Implementations.Data { @@ -27,12 +27,12 @@ namespace Emby.Server.Implementations.Data /// /// Name of the type. /// Type. - /// + /// public Type GetType(string typeName) { if (string.IsNullOrEmpty(typeName)) { - throw new ArgumentNullException("typeName"); + throw new ArgumentNullException(nameof(typeName)); } return _typeMap.GetOrAdd(typeName, LookupType); diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index 90cef5d06..00761809a 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text; using MediaBrowser.Common.Configuration; @@ -10,15 +10,12 @@ namespace Emby.Server.Implementations.Devices public class DeviceId { private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; - private readonly IFileSystem _fileSystem; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; private readonly object _syncLock = new object(); - private string CachePath - { - get { return Path.Combine(_appPaths.DataPath, "device.txt"); } - } + private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt"); private string GetCachedId() { @@ -26,10 +23,9 @@ namespace Emby.Server.Implementations.Devices { lock (_syncLock) { - var value = File.ReadAllText(CachePath, Encoding.UTF8); + var value = File.ReadAllText(CachePath, Encoding.UTF8); - Guid guid; - if (Guid.TryParse(value, out guid)) + if (Guid.TryParse(value, out var guid)) { return value; } @@ -57,7 +53,7 @@ namespace Emby.Server.Implementations.Devices { var path = CachePath; - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); lock (_syncLock) { @@ -70,7 +66,7 @@ namespace Emby.Server.Implementations.Devices } } - private string GetNewId() + private static string GetNewId() { return Guid.NewGuid().ToString("N"); } @@ -90,20 +86,21 @@ namespace Emby.Server.Implementations.Devices private string _id; - public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem) + public DeviceId( + IApplicationPaths appPaths, + ILoggerFactory loggerFactory, + IFileSystem fileSystem) { - if (fileSystem == null) { - throw new ArgumentNullException ("fileSystem"); - } + if (fileSystem == null) + { + throw new ArgumentNullException(nameof(fileSystem)); + } _appPaths = appPaths; - _logger = logger; - _fileSystem = fileSystem; + _logger = loggerFactory.CreateLogger("SystemId"); + _fileSystem = fileSystem; } - public string Value - { - get { return _id ?? (_id = GetDeviceId()); } - } + public string Value => _id ?? (_id = GetDeviceId()); } } diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index f5314df6e..60d57519e 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -1,30 +1,29 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Devices; -using MediaBrowser.Model.Events; -using MediaBrowser.Model.Extensions; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Session; -using MediaBrowser.Model.Users; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Globalization; -using MediaBrowser.Controller.Security; -using MediaBrowser.Model.Serialization; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Devices; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Security; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Devices; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Events; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Net; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Session; +using MediaBrowser.Model.Users; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Devices { @@ -48,14 +47,24 @@ namespace Emby.Server.Implementations.Devices private readonly object _cameraUploadSyncLock = new object(); private readonly object _capabilitiesSyncLock = new object(); - public DeviceManager(IAuthenticationRepository authRepo, IJsonSerializer json, ILibraryManager libraryManager, ILocalizationManager localizationManager, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network) + public DeviceManager( + IAuthenticationRepository authRepo, + IJsonSerializer json, + ILibraryManager libraryManager, + ILocalizationManager localizationManager, + IUserManager userManager, + IFileSystem fileSystem, + ILibraryMonitor libraryMonitor, + IServerConfigurationManager config, + ILoggerFactory loggerFactory, + INetworkManager network) { _json = json; _userManager = userManager; _fileSystem = fileSystem; _libraryMonitor = libraryMonitor; _config = config; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(DeviceManager)); _network = network; _libraryManager = libraryManager; _localizationManager = localizationManager; @@ -99,8 +108,7 @@ namespace Emby.Server.Implementations.Devices { lock (_capabilitiesSyncLock) { - ClientCapabilities result; - if (_capabilitiesCache.TryGetValue(id, out result)) + if (_capabilitiesCache.TryGetValue(id, out var result)) { return result; } @@ -144,7 +152,7 @@ namespace Emby.Server.Implementations.Devices HasUser = true }).Items; - + // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger. if (query.SupportsSync.HasValue) { @@ -360,10 +368,7 @@ namespace Emby.Server.Implementations.Devices return path; } - private string DefaultCameraUploadsPath - { - get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); } - } + private string DefaultCameraUploadsPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); public bool CanAccessDevice(User user, string deviceId) { @@ -373,7 +378,7 @@ namespace Emby.Server.Implementations.Devices } if (string.IsNullOrEmpty(deviceId)) { - throw new ArgumentNullException("deviceId"); + throw new ArgumentNullException(nameof(deviceId)); } if (!CanAccessDevice(user.Policy, deviceId)) @@ -389,7 +394,7 @@ namespace Emby.Server.Implementations.Devices return true; } - private bool CanAccessDevice(UserPolicy policy, string id) + private static bool CanAccessDevice(UserPolicy policy, string id) { if (policy.EnableAllDevices) { diff --git a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs index a709607bd..d8a798c46 100644 --- a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs +++ b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs @@ -1,9 +1,9 @@ -using System; +using System; using System.Diagnostics; using System.IO; +using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Diagnostics; -using System.Threading; namespace Emby.Server.Implementations.Diagnostics { @@ -81,30 +81,15 @@ namespace Emby.Server.Implementations.Diagnostics } } - public ProcessOptions StartInfo - { - get { return _options; } - } + public ProcessOptions StartInfo => _options; - public StreamWriter StandardInput - { - get { return _process.StandardInput; } - } + public StreamWriter StandardInput => _process.StandardInput; - public StreamReader StandardError - { - get { return _process.StandardError; } - } + public StreamReader StandardError => _process.StandardError; - public StreamReader StandardOutput - { - get { return _process.StandardOutput; } - } + public StreamReader StandardOutput => _process.StandardOutput; - public int ExitCode - { - get { return _process.ExitCode; } - } + public int ExitCode => _process.ExitCode; public void Start() { diff --git a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs index a2c511cb9..14aadaaae 100644 --- a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs +++ b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Diagnostics; +using MediaBrowser.Model.Diagnostics; namespace Emby.Server.Implementations.Diagnostics { diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 7871d3fb3..13febc214 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1,4 +1,9 @@ -using MediaBrowser.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using MediaBrowser.Common; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -11,21 +16,15 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; -using MediaBrowser.Controller.Sync; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using MediaBrowser.Model.IO; using MediaBrowser.Model.Extensions; -using MediaBrowser.Controller.Playlists; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Querying; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Dto { @@ -47,9 +46,22 @@ namespace Emby.Server.Implementations.Dto private readonly Func _mediaSourceManager; private readonly Func _livetvManager; - public DtoService(ILogger logger, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func channelManagerFactory, IApplicationHost appHost, Func deviceManager, Func mediaSourceManager, Func livetvManager) + public DtoService( + ILoggerFactory loggerFactory, + ILibraryManager libraryManager, + IUserDataManager userDataRepository, + IItemRepository itemRepo, + IImageProcessor imageProcessor, + IServerConfigurationManager config, + IFileSystem fileSystem, + IProviderManager providerManager, + Func channelManagerFactory, + IApplicationHost appHost, + Func deviceManager, + Func mediaSourceManager, + Func livetvManager) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(DtoService)); _libraryManager = libraryManager; _userDataRepository = userDataRepository; _itemRepo = itemRepo; @@ -72,7 +84,7 @@ namespace Emby.Server.Implementations.Dto /// The user. /// The owner. /// Task{DtoBaseItem}. - /// item + /// item public BaseItemDto GetBaseItemDto(BaseItem item, ItemFields[] fields, User user = null, BaseItem owner = null) { var options = new DtoOptions @@ -189,7 +201,7 @@ namespace Emby.Server.Implementations.Dto return dto; } - private IList GetTaggedItems(IItemByName byName, User user, DtoOptions options) + private static IList GetTaggedItems(IItemByName byName, User user, DtoOptions options) { return byName.GetTaggedItems(new InternalItemsQuery(user) { @@ -295,7 +307,7 @@ namespace Emby.Server.Implementations.Dto return dto; } - private void NormalizeMediaSourceContainers(BaseItemDto dto) + private static void NormalizeMediaSourceContainers(BaseItemDto dto) { foreach (var mediaSource in dto.MediaSources) { @@ -347,7 +359,7 @@ namespace Emby.Server.Implementations.Dto return dto; } - private void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList taggedItems, User user = null) + private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList taggedItems, User user = null) { if (item is MusicArtist) { @@ -447,7 +459,7 @@ namespace Emby.Server.Implementations.Dto } } - private int GetChildCount(Folder folder, User user) + private static int GetChildCount(Folder folder, User user) { // Right now this is too slow to calculate for top level folders on a per-user basis // Just return something so that apps that are expecting a value won't think the folders are empty @@ -464,17 +476,17 @@ namespace Emby.Server.Implementations.Dto /// /// The item. /// System.String. - /// item + /// item public string GetDtoId(BaseItem item) { return item.Id.ToString("N"); } - private void SetBookProperties(BaseItemDto dto, Book item) + private static void SetBookProperties(BaseItemDto dto, Book item) { dto.SeriesName = item.SeriesName; } - private void SetPhotoProperties(BaseItemDto dto, Photo item) + private static void SetPhotoProperties(BaseItemDto dto, Photo item) { dto.CameraMake = item.CameraMake; dto.CameraModel = item.CameraModel; @@ -520,13 +532,13 @@ namespace Emby.Server.Implementations.Dto dto.Album = item.Album; } - private void SetGameProperties(BaseItemDto dto, Game item) + private static void SetGameProperties(BaseItemDto dto, Game item) { dto.GameSystem = item.GameSystem; dto.MultiPartGameFiles = item.MultiPartGameFiles; } - private void SetGameSystemProperties(BaseItemDto dto, GameSystem item) + private static void SetGameSystemProperties(BaseItemDto dto, GameSystem item) { dto.GameSystem = item.GameSystemName; } @@ -638,9 +650,7 @@ namespace Emby.Server.Implementations.Dto Type = person.Type }; - Person entity; - - if (dictionary.TryGetValue(person.Name, out entity)) + if (dictionary.TryGetValue(person.Name, out Person entity)) { baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary); baseItemPerson.Id = entity.Id.ToString("N"); diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 241505019..3aa617b02 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -1,4 +1,4 @@ - + @@ -27,6 +27,7 @@ + @@ -42,10 +43,7 @@ - - - diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs index a0947c87d..0fc4c3858 100644 --- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs @@ -1,16 +1,16 @@ -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Tasks; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 6cd867921..8755ee3a7 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; +using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller; @@ -9,10 +10,9 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; using Mono.Nat; -using System.Threading; namespace Emby.Server.Implementations.EntryPoints { @@ -108,11 +108,9 @@ namespace Emby.Server.Implementations.EntryPoints var info = e.Argument; - string usn; - if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty; + if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty; - string nt; - if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty; + if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty; // Filter device type if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && @@ -141,8 +139,7 @@ namespace Emby.Server.Implementations.EntryPoints _logger.LogDebug("Found NAT device: " + identifier); - IPAddress address; - if (IPAddress.TryParse(info.Location.Host, out address)) + if (IPAddress.TryParse(info.Location.Host, out var address)) { // The Handle method doesn't need the port var endpoint = new IPEndPoint(address, info.Location.Port); @@ -153,8 +150,7 @@ namespace Emby.Server.Implementations.EntryPoints { var localAddressString = await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false); - Uri uri; - if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri)) + if (Uri.TryCreate(localAddressString, UriKind.Absolute, out var uri)) { localAddressString = uri.Host; @@ -227,7 +223,7 @@ namespace Emby.Server.Implementations.EntryPoints { if (_disposed) { - throw new ObjectDisposedException("PortMapper"); + throw new ObjectDisposedException(GetType().Name); } // On some systems the device discovered event seems to fire repeatedly diff --git a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs deleted file mode 100644 index a6dadcef0..000000000 --- a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs +++ /dev/null @@ -1,65 +0,0 @@ -using MediaBrowser.Controller; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using Microsoft.Extensions.Logging; -using System; -using System.Linq; -using MediaBrowser.Model.System; -using MediaBrowser.Model.Threading; - -namespace Emby.Server.Implementations.EntryPoints -{ - public class KeepServerAwake : IServerEntryPoint - { - private readonly ISessionManager _sessionManager; - private readonly ILogger _logger; - private ITimer _timer; - private readonly IServerApplicationHost _appHost; - private readonly ITimerFactory _timerFactory; - private readonly IPowerManagement _powerManagement; - - public KeepServerAwake(ISessionManager sessionManager, ILogger logger, IServerApplicationHost appHost, ITimerFactory timerFactory, IPowerManagement powerManagement) - { - _sessionManager = sessionManager; - _logger = logger; - _appHost = appHost; - _timerFactory = timerFactory; - _powerManagement = powerManagement; - } - - public void Run() - { - _timer = _timerFactory.Create(OnTimerCallback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); - } - - private void OnTimerCallback(object state) - { - var now = DateTime.UtcNow; - - try - { - if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15)) - { - _powerManagement.PreventSystemStandby(); - } - else - { - _powerManagement.AllowSystemStandby(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error resetting system standby timer"); - } - } - - public void Dispose() - { - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } - } - } -} diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index bb8ef52f1..7a8b09cf7 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -1,21 +1,20 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -90,8 +89,7 @@ namespace Emby.Server.Implementations.EntryPoints var progress = e.Argument.Item2; - DateTime lastMessageSendTime; - if (_lastProgressMessageTimes.TryGetValue(item.Id, out lastMessageSendTime)) + if (_lastProgressMessageTimes.TryGetValue(item.Id, out var lastMessageSendTime)) { if (progress > 0 && progress < 100 && (DateTime.UtcNow - lastMessageSendTime).TotalMilliseconds < 1000) { @@ -142,7 +140,7 @@ namespace Emby.Server.Implementations.EntryPoints _providerManager_RefreshProgress(sender, new GenericEventArgs>(new Tuple(e.Argument, 100))); } - private bool EnableRefreshMessage(BaseItem item) + private static bool EnableRefreshMessage(BaseItem item) { var folder = item as Folder; @@ -387,7 +385,7 @@ namespace Emby.Server.Implementations.EntryPoints }; } - private bool FilterItem(BaseItem item) + private static bool FilterItem(BaseItem item) { if (!item.IsFolder && !item.HasPathProtocol) { @@ -471,7 +469,7 @@ namespace Emby.Server.Implementations.EntryPoints LibraryUpdateTimer.Dispose(); LibraryUpdateTimer = null; } - + _libraryManager.ItemAdded -= libraryManager_ItemAdded; _libraryManager.ItemUpdated -= libraryManager_ItemUpdated; _libraryManager.ItemRemoved -= libraryManager_ItemRemoved; diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index 0b377dc68..e37ea96a1 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Threading; using MediaBrowser.Controller.Library; @@ -58,11 +58,11 @@ namespace Emby.Server.Implementations.EntryPoints try { - await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None); + await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None); } catch (ObjectDisposedException) { - + // TODO Log exception or Investigate and properly fix. } catch (Exception ex) { diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index 660ca3a94..b7565adec 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -1,12 +1,12 @@ -using System; -using MediaBrowser.Controller.Library; -using System.Threading; -using MediaBrowser.Model.Tasks; +using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints @@ -30,10 +30,7 @@ namespace Emby.Server.Implementations.EntryPoints public string Description => "Refresh user infos"; - public string Category - { - get { return "Library"; } - } + public string Category => "Library"; public bool IsHidden => true; diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs index 72dcabab3..92ea3a8f4 100644 --- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs @@ -1,17 +1,14 @@ -using MediaBrowser.Common.Plugins; +using System; +using System.Collections.Generic; +using System.Threading; +using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Controller.Sync; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Sync; -using System; -using System.Collections.Generic; -using System.Threading; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.EntryPoints diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs index ffd98bf78..05c8b07ab 100644 --- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs +++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs @@ -1,8 +1,8 @@ -using Emby.Server.Implementations.Browser; +using Emby.Server.Implementations.Browser; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using Microsoft.Extensions.Logging; -using MediaBrowser.Controller.Configuration; namespace Emby.Server.Implementations.EntryPoints { diff --git a/Emby.Server.Implementations/EntryPoints/SystemEvents.cs b/Emby.Server.Implementations/EntryPoints/SystemEvents.cs index e27de8967..72c8acd9f 100644 --- a/Emby.Server.Implementations/EntryPoints/SystemEvents.cs +++ b/Emby.Server.Implementations/EntryPoints/SystemEvents.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using MediaBrowser.Model.System; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Common; +using System; using MediaBrowser.Controller; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Model.System; namespace Emby.Server.Implementations.EntryPoints { diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 730ced055..2c8246d13 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,10 +1,10 @@ -using System; +using System; +using Emby.Server.Implementations.Udp; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; -using Emby.Server.Implementations.Udp; using MediaBrowser.Model.Net; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 58309ea1c..9e71ffceb 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -1,17 +1,17 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Session; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Session; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -62,9 +62,7 @@ namespace Emby.Server.Implementations.EntryPoints UpdateTimer.Change(UpdateDuration, Timeout.Infinite); } - List keys; - - if (!_changedItems.TryGetValue(e.UserId, out keys)) + if (!_changedItems.TryGetValue(e.UserId, out List keys)) { keys = new List(); _changedItems[e.UserId] = keys; diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 03e10e7ea..c8104150d 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -1,11 +1,9 @@ -using System; -using System.IO; -using MediaBrowser.Model.System; +using System; using System.Runtime.InteropServices; +using MediaBrowser.Model.System; namespace Emby.Server.Implementations.EnvironmentInfo { - // TODO: Rework @bond public class EnvironmentInfo : IEnvironmentInfo { public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem) @@ -31,37 +29,8 @@ namespace Emby.Server.Implementations.EnvironmentInfo } } - public string OperatingSystemVersion - { - get - { - return Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString(); - } - } + public string OperatingSystemVersion => Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString(); - public char PathSeparator - { - get - { - return Path.PathSeparator; - } - } - - public Architecture SystemArchitecture { get { return RuntimeInformation.OSArchitecture; } } - - public string GetEnvironmentVariable(string name) - { - return Environment.GetEnvironmentVariable(name); - } - - public string StackTrace - { - get { return Environment.StackTrace; } - } - - public void SetProcessEnvironmentVariable(string name, string value) - { - Environment.SetEnvironmentVariable(name, value); - } + public Architecture SystemArchitecture => RuntimeInformation.OSArchitecture; } } diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs b/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs index e725d22f5..60cd7b3d7 100644 --- a/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs +++ b/Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs @@ -1,4 +1,4 @@ -namespace Emby.Server.Implementations.FFMpeg +namespace Emby.Server.Implementations.FFMpeg { /// /// Class FFMpegInfo @@ -21,4 +21,4 @@ /// The version. public string Version { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs b/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs index a1080a839..fa9cb5e01 100644 --- a/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs +++ b/Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs @@ -1,4 +1,3 @@ - namespace Emby.Server.Implementations.FFMpeg { public class FFMpegInstallInfo @@ -15,4 +14,4 @@ namespace Emby.Server.Implementations.FFMpeg FFProbeFilename = "ffprobe"; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs index 5f043e127..9a4aec958 100644 --- a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs +++ b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.FFMpeg { @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.FFMpeg { var encoderFilename = Path.GetFileName(info.EncoderPath); var probeFilename = Path.GetFileName(info.ProbePath); - + foreach (var directory in _fileSystem.GetDirectoryPaths(rootEncoderPath) .ToList()) { diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs index 21cec9d2b..f747b01b9 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientInfo.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Http; namespace Emby.Server.Implementations.HttpClientManager diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index d3ba1b683..ea620cb2e 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; @@ -13,8 +13,8 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpClientManager { @@ -44,18 +44,22 @@ namespace Emby.Server.Implementations.HttpClientManager /// /// Initializes a new instance of the class. /// - public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, Func defaultUserAgentFn) + public HttpClientManager( + IApplicationPaths appPaths, + ILoggerFactory loggerFactory, + IFileSystem fileSystem, + Func defaultUserAgentFn) { if (appPaths == null) { - throw new ArgumentNullException("appPaths"); + throw new ArgumentNullException(nameof(appPaths)); } - if (logger == null) + if (loggerFactory == null) { - throw new ArgumentNullException("logger"); + throw new ArgumentNullException(nameof(loggerFactory)); } - _logger = logger; + _logger = loggerFactory.CreateLogger("HttpClient"); _fileSystem = fileSystem; _appPaths = appPaths; _defaultUserAgentFn = defaultUserAgentFn; @@ -82,19 +86,17 @@ namespace Emby.Server.Implementations.HttpClientManager /// The host. /// if set to true [enable HTTP compression]. /// HttpClient. - /// host + /// host private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression) { if (string.IsNullOrEmpty(host)) { - throw new ArgumentNullException("host"); + throw new ArgumentNullException(nameof(host)); } - HttpClientInfo client; - var key = host + enableHttpCompression; - if (!_httpClients.TryGetValue(key, out client)) + if (!_httpClients.TryGetValue(key, out var client)) { client = new HttpClientInfo(); @@ -104,7 +106,7 @@ namespace Emby.Server.Implementations.HttpClientManager return client; } - private WebRequest CreateWebRequest(string url) + private static WebRequest CreateWebRequest(string url) { try { @@ -125,7 +127,7 @@ namespace Emby.Server.Implementations.HttpClientManager { string url = options.Url; - Uri uriAddress = new Uri(url); + var uriAddress = new Uri(url); string userInfo = uriAddress.UserInfo; if (!string.IsNullOrWhiteSpace(userInfo)) { @@ -133,7 +135,7 @@ namespace Emby.Server.Implementations.HttpClientManager url = url.Replace(userInfo + "@", string.Empty); } - WebRequest request = CreateWebRequest(url); + var request = CreateWebRequest(url); if (request is HttpWebRequest httpWebRequest) { @@ -185,10 +187,10 @@ namespace Emby.Server.Implementations.HttpClientManager return request; } - private CredentialCache GetCredential(string url, string username, string password) + private static CredentialCache GetCredential(string url, string username, string password) { //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; - CredentialCache credentialCache = new CredentialCache(); + var credentialCache = new CredentialCache(); credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password)); return credentialCache; } @@ -220,7 +222,7 @@ namespace Emby.Server.Implementations.HttpClientManager } } - private void SetUserAgent(HttpWebRequest request, string userAgent) + private static void SetUserAgent(HttpWebRequest request, string userAgent) { request.UserAgent = userAgent; } @@ -266,7 +268,7 @@ namespace Emby.Server.Implementations.HttpClientManager var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash); - var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false); + var response = GetCachedResponse(responseCachePath, options.CacheLength, url); if (response != null) { return response; @@ -282,30 +284,24 @@ namespace Emby.Server.Implementations.HttpClientManager return response; } - private async Task GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url) + private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url) { try { if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow) { - using (var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true)) + var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true); + + return new HttpResponseInfo { - var memoryStream = new MemoryStream(); - - await stream.CopyToAsync(memoryStream).ConfigureAwait(false); - memoryStream.Position = 0; - - return new HttpResponseInfo - { - ResponseUrl = url, - Content = memoryStream, - StatusCode = HttpStatusCode.OK, - ContentLength = memoryStream.Length - }; - } + ResponseUrl = url, + Content = stream, + StatusCode = HttpStatusCode.OK, + ContentLength = stream.Length + }; } } - catch (FileNotFoundException) + catch (FileNotFoundException) // REVIEW: @bond Is this really faster? { } @@ -321,19 +317,11 @@ namespace Emby.Server.Implementations.HttpClientManager { _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(responseCachePath)); - using (var responseStream = response.Content) + using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true)) { - var memoryStream = new MemoryStream(); - await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false); - memoryStream.Position = 0; + await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); - using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true)) - { - await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false); - - memoryStream.Position = 0; - response.Content = memoryStream; - } + response.Content.Position = 0; } } @@ -389,7 +377,7 @@ namespace Emby.Server.Implementations.HttpClientManager { options.ResourcePool?.Release(); - throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true }; + throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true }; } if (options.LogRequest) @@ -491,7 +479,7 @@ namespace Emby.Server.Implementations.HttpClientManager return responseInfo; } - private void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo) + private static void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo) { foreach (var key in headers.AllKeys) { @@ -541,7 +529,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.Progress == null) { - throw new ArgumentNullException("progress"); + throw new ArgumentException("Options did not have a Progress value.", nameof(options)); } options.CancellationToken.ThrowIfCancellationRequested(); @@ -616,7 +604,7 @@ namespace Emby.Server.Implementations.HttpClientManager } } - private long? GetContentLength(HttpWebResponse response) + private static long? GetContentLength(HttpWebResponse response) { var length = response.ContentLength; @@ -704,7 +692,7 @@ namespace Emby.Server.Implementations.HttpClientManager { if (string.IsNullOrEmpty(options.Url)) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } } @@ -713,7 +701,7 @@ namespace Emby.Server.Implementations.HttpClientManager /// /// The URL. /// System.String. - private string GetHostFromUrl(string url) + private static string GetHostFromUrl(string url) { var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase); @@ -803,11 +791,11 @@ namespace Emby.Server.Implementations.HttpClientManager }; } - private Task GetResponseAsync(WebRequest request, TimeSpan timeout) + private static Task GetResponseAsync(WebRequest request, TimeSpan timeout) { var taskCompletion = new TaskCompletionSource(); - Task asyncTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); + var asyncTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true); var callback = new TaskCallback { taskCompletion = taskCompletion }; @@ -823,7 +811,7 @@ namespace Emby.Server.Implementations.HttpClientManager { if (timedOut && state != null) { - WebRequest request = (WebRequest)state; + var request = (WebRequest)state; request.Abort(); } } diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs index 1a875e533..c32c91670 100644 --- a/Emby.Server.Implementations/HttpServer/FileWriter.cs +++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs @@ -1,13 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; -using System.Linq; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -38,10 +38,7 @@ namespace Emby.Server.Implementations.HttpServer /// Gets the options. /// /// The options. - public IDictionary Headers - { - get { return _options; } - } + public IDictionary Headers => _options; public string Path { get; set; } @@ -49,7 +46,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(contentType)) { - throw new ArgumentNullException("contentType"); + throw new ArgumentNullException(nameof(contentType)); } Path = path; @@ -148,7 +145,7 @@ namespace Emby.Server.Implementations.HttpServer } } - private string[] SkipLogExtensions = new string[] + private string[] SkipLogExtensions = new string[] { ".js", ".html", @@ -203,8 +200,8 @@ namespace Emby.Server.Implementations.HttpServer public HttpStatusCode StatusCode { - get { return (HttpStatusCode)Status; } - set { Status = (int)value; } + get => (HttpStatusCode)Status; + set => Status = (int)value; } public string StatusDescription { get; set; } diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 69ca0f85b..834ffb130 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,27 +1,25 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; +using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Services; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; -using MediaBrowser.Common.Security; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; -using MediaBrowser.Model.Text; -using System.Net.Sockets; -using Emby.Server.Implementations.Net; -using MediaBrowser.Model.Events; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -38,11 +36,7 @@ namespace Emby.Server.Implementations.HttpServer private readonly IServerConfigurationManager _config; private readonly INetworkManager _networkManager; - private readonly IServerApplicationHost _appHost; - - private readonly ITextEncoding _textEncoding; - private readonly IJsonSerializer _jsonSerializer; private readonly IXmlSerializer _xmlSerializer; private readonly Func> _funcParseFn; @@ -55,47 +49,32 @@ namespace Emby.Server.Implementations.HttpServer private IWebSocketListener[] _webSocketListeners = Array.Empty(); private readonly List _webSocketConnections = new List(); - public HttpListenerHost(IServerApplicationHost applicationHost, - ILogger logger, + public HttpListenerHost( + IServerApplicationHost applicationHost, + ILoggerFactory loggerFactory, IServerConfigurationManager config, - string defaultRedirectPath, INetworkManager networkManager, ITextEncoding textEncoding, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, Func> funcParseFn) + string defaultRedirectPath, + INetworkManager networkManager, + IJsonSerializer jsonSerializer, + IXmlSerializer xmlSerializer, + Func> funcParseFn) { - Instance = this; - _appHost = applicationHost; + _logger = loggerFactory.CreateLogger("HttpServer"); + _config = config; DefaultRedirectPath = defaultRedirectPath; _networkManager = networkManager; - _textEncoding = textEncoding; _jsonSerializer = jsonSerializer; _xmlSerializer = xmlSerializer; - _config = config; - - _logger = logger; _funcParseFn = funcParseFn; - ResponseFilters = new Action[] { }; + Instance = this; + ResponseFilters = Array.Empty>(); } public string GlobalResponse { get; set; } - readonly Dictionary _mapExceptionToStatusCode = new Dictionary - { - {typeof (ResourceNotFoundException), 404}, - {typeof (RemoteServiceUnavailableException), 502}, - {typeof (FileNotFoundException), 404}, - //{typeof (DirectoryNotFoundException), 404}, - {typeof (SecurityException), 401}, - {typeof (PaymentRequiredException), 402}, - {typeof (ArgumentException), 400} - }; - - protected ILogger Logger - { - get - { - return _logger; - } - } + protected ILogger Logger => _logger; public object CreateInstance(Type type) { @@ -103,7 +82,7 @@ namespace Emby.Server.Implementations.HttpServer } /// - /// Applies the request filters. Returns whether or not the request has been handled + /// Applies the request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// /// @@ -111,9 +90,9 @@ namespace Emby.Server.Implementations.HttpServer { //Exec all RequestFilter attributes with Priority < 0 var attributes = GetRequestFilterAttributes(requestDto.GetType()); - var i = 0; - var count = attributes.Count; + int count = attributes.Count; + int i = 0; for (; i < count && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; @@ -130,8 +109,7 @@ namespace Emby.Server.Implementations.HttpServer public Type GetServiceTypeByRequest(Type requestType) { - Type serviceType; - ServiceOperationsMap.TryGetValue(requestType, out serviceType); + ServiceOperationsMap.TryGetValue(requestType, out var serviceType); return serviceType; } @@ -162,7 +140,7 @@ namespace Emby.Server.Implementations.HttpServer return; } - var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger, _textEncoding) + var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { OnReceive = ProcessWebSocketMessageReceived, Url = e.Url, @@ -176,10 +154,7 @@ namespace Emby.Server.Implementations.HttpServer _webSocketConnections.Add(connection); } - if (WebSocketConnected != null) - { - WebSocketConnected?.Invoke(this, new GenericEventArgs(connection)); - } + WebSocketConnected?.Invoke(this, new GenericEventArgs(connection)); } private void Connection_Closed(object sender, EventArgs e) @@ -190,10 +165,9 @@ namespace Emby.Server.Implementations.HttpServer } } - private Exception GetActualException(Exception ex) + private static Exception GetActualException(Exception ex) { - var agg = ex as AggregateException; - if (agg != null) + if (ex is AggregateException agg) { var inner = agg.InnerException; if (inner != null) @@ -215,27 +189,16 @@ namespace Emby.Server.Implementations.HttpServer private int GetStatusCode(Exception ex) { - if (ex is ArgumentException) + switch (ex) { - return 400; + case ArgumentException _: return 400; + case SecurityException _: return 401; + case DirectoryNotFoundException _: + case FileNotFoundException _: + case ResourceNotFoundException _: return 404; + case RemoteServiceUnavailableException _: return 502; + default: return 500; } - - var exceptionType = ex.GetType(); - - int statusCode; - if (!_mapExceptionToStatusCode.TryGetValue(exceptionType, out statusCode)) - { - if (ex is DirectoryNotFoundException) - { - statusCode = 404; - } - else - { - statusCode = 500; - } - } - - return statusCode; } private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage) @@ -321,32 +284,25 @@ namespace Emby.Server.Implementations.HttpServer } } - private readonly Dictionary _skipLogExtensions = new Dictionary(StringComparer.OrdinalIgnoreCase) + private static readonly string[] _skipLogExtensions = { - {".js", 0}, - {".css", 0}, - {".woff", 0}, - {".woff2", 0}, - {".ttf", 0}, - {".html", 0} + ".js", + ".css", + ".woff", + ".woff2", + ".ttf", + ".html" }; private bool EnableLogging(string url, string localPath) { var extension = GetExtension(url); - if (string.IsNullOrEmpty(extension) || !_skipLogExtensions.ContainsKey(extension)) - { - if (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1) - { - return true; - } - } - - return false; + return ((string.IsNullOrEmpty(extension) || !_skipLogExtensions.Contains(extension)) + && (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)); } - private string GetExtension(string url) + private static string GetExtension(string url) { var parts = url.Split(new[] { '?' }, 2); @@ -379,18 +335,18 @@ namespace Emby.Server.Implementations.HttpServer string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0]; return newQueryString.Count > 0 - ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) + ? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) : pagePathWithoutQueryString; } - private string GetUrlToLog(string url) + private static string GetUrlToLog(string url) { url = RemoveQueryStringByKey(url, "api_key"); return url; } - private string NormalizeConfiguredLocalAddress(string address) + private static string NormalizeConfiguredLocalAddress(string address) { var index = address.Trim('/').IndexOf('/'); @@ -566,9 +522,7 @@ namespace Emby.Server.Implementations.HttpServer return; } - if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || - string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || - localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) + if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; @@ -711,8 +665,7 @@ namespace Emby.Server.Implementations.HttpServer return null; } - string contentType; - var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType); + var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out string contentType); if (restPath != null) { @@ -723,11 +676,11 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.LogError("Could not find handler for {pathInfo}", pathInfo); + _logger.LogError("Could not find handler for {PathInfo}", pathInfo); return null; } - private Task Write(IResponse response, string text) + private static Task Write(IResponse response, string text) { var bOutput = Encoding.UTF8.GetBytes(text); response.SetContentLength(bOutput.Length); @@ -737,14 +690,13 @@ namespace Emby.Server.Implementations.HttpServer private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url) { - int currentPort; - Uri uri; - if (Uri.TryCreate(url, UriKind.Absolute, out uri)) + if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { - currentPort = uri.Port; - var builder = new UriBuilder(uri); - builder.Port = _config.Configuration.PublicHttpsPort; - builder.Scheme = "https"; + var builder = new UriBuilder(uri) + { + Port = _config.Configuration.PublicHttpsPort, + Scheme = "https" + }; url = builder.Uri.ToString(); RedirectToUrl(httpRes, url); @@ -844,16 +796,12 @@ namespace Emby.Server.Implementations.HttpServer public Task DeserializeJson(Type type, Stream stream) { - //using (var reader = new StreamReader(stream)) - //{ - // var json = reader.ReadToEnd(); - // logger.LogInformation(json); - // return _jsonSerializer.DeserializeFromString(json, type); - //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); } - private string NormalizeEmbyRoutePath(string path) + //TODO Add Jellyfin Route Path Normalizer + + private static string NormalizeEmbyRoutePath(string path) { if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { @@ -863,7 +811,7 @@ namespace Emby.Server.Implementations.HttpServer return "emby/" + path; } - private string NormalizeMediaBrowserRoutePath(string path) + private static string NormalizeMediaBrowserRoutePath(string path) { if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { @@ -873,7 +821,7 @@ namespace Emby.Server.Implementations.HttpServer return "mediabrowser/" + path; } - private string DoubleNormalizeEmbyRoutePath(string path) + private static string DoubleNormalizeEmbyRoutePath(string path) { if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index 73b2afe64..8b60d61d4 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -1,7 +1,3 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; using System.Globalization; @@ -13,8 +9,12 @@ using System.Text; using System.Threading.Tasks; using System.Xml; using Emby.Server.Implementations.Services; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; using IRequest = MediaBrowser.Model.Services.IRequest; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; @@ -96,8 +96,7 @@ namespace Emby.Server.Implementations.HttpServer responseHeaders = new Dictionary(); } - string expires; - if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires)) + if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires)) { responseHeaders["Expires"] = "-1"; } @@ -115,7 +114,8 @@ namespace Emby.Server.Implementations.HttpServer string compressionType = null; bool isHeadRequest = false; - if (requestContext != null) { + if (requestContext != null) + { compressionType = GetCompressionType(requestContext, content, contentType); isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase); } @@ -142,8 +142,7 @@ namespace Emby.Server.Implementations.HttpServer responseHeaders = new Dictionary(); } - string expires; - if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires)) + if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires)) { responseHeaders["Expires"] = "-1"; } @@ -187,8 +186,7 @@ namespace Emby.Server.Implementations.HttpServer responseHeaders = new Dictionary(); } - string expires; - if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires)) + if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires)) { responseHeaders["Expires"] = "-1"; } @@ -207,7 +205,7 @@ namespace Emby.Server.Implementations.HttpServer { if (result == null) { - throw new ArgumentNullException("result"); + throw new ArgumentNullException(nameof(result)); } if (responseHeaders == null) @@ -245,7 +243,7 @@ namespace Emby.Server.Implementations.HttpServer return GetCompressionType(request); } - private string GetCompressionType(IRequest request) + private static string GetCompressionType(IRequest request) { var acceptEncoding = request.Headers["Accept-Encoding"]; @@ -265,7 +263,7 @@ namespace Emby.Server.Implementations.HttpServer } /// - /// Returns the optimized result for the IRequestContext. + /// Returns the optimized result for the IRequestContext. /// Does not use or store results in any cache. /// /// @@ -365,7 +363,7 @@ namespace Emby.Server.Implementations.HttpServer return _brotliCompressor.Compress(bytes); } - private byte[] Deflate(byte[] bytes) + private static byte[] Deflate(byte[] bytes) { // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream @@ -379,7 +377,7 @@ namespace Emby.Server.Implementations.HttpServer } } - private byte[] GZip(byte[] buffer) + private static byte[] GZip(byte[] buffer) { using (var ms = new MemoryStream()) using (var zipStream = new GZipStream(ms, CompressionMode.Compress)) @@ -398,7 +396,7 @@ namespace Emby.Server.Implementations.HttpServer : contentType.Split(';')[0].ToLower().Trim(); } - private string SerializeToXmlString(object from) + private static string SerializeToXmlString(object from) { using (var ms = new MemoryStream()) { @@ -412,8 +410,10 @@ namespace Emby.Server.Implementations.HttpServer serializer.WriteObject(xw, from); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); - var reader = new StreamReader(ms); - return reader.ReadToEnd(); + using (var reader = new StreamReader(ms)) + { + return reader.ReadToEnd(); + } } } } @@ -425,7 +425,7 @@ namespace Emby.Server.Implementations.HttpServer { responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString); - var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; + bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; if (!noCache) { @@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } return GetStaticFileResult(requestContext, new StaticFileResultOptions @@ -463,15 +463,14 @@ namespace Emby.Server.Implementations.HttpServer }); } - public Task GetStaticFileResult(IRequest requestContext, - StaticFileResultOptions options) + public Task GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options) { var path = options.Path; var fileShare = options.FileShare; if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite) @@ -661,7 +660,7 @@ namespace Emby.Server.Implementations.HttpServer /// /// Adds the expires header. /// - private void AddExpiresHeader(IDictionary responseHeaders, string cacheKey, TimeSpan? cacheDuration) + private static void AddExpiresHeader(IDictionary responseHeaders, string cacheKey, TimeSpan? cacheDuration) { if (cacheDuration.HasValue) { @@ -678,7 +677,7 @@ namespace Emby.Server.Implementations.HttpServer /// /// The responseHeaders. /// The last date modified. - private void AddAgeHeader(IDictionary responseHeaders, DateTime? lastDateModified) + private static void AddAgeHeader(IDictionary responseHeaders, DateTime? lastDateModified) { if (lastDateModified.HasValue) { @@ -699,36 +698,26 @@ namespace Emby.Server.Implementations.HttpServer var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since"); - if (!string.IsNullOrEmpty(ifModifiedSinceHeader)) + if (!string.IsNullOrEmpty(ifModifiedSinceHeader) + && DateTime.TryParse(ifModifiedSinceHeader, out DateTime ifModifiedSince) + && IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) { - DateTime ifModifiedSince; - - if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince)) - { - if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) - { - return true; - } - } + return true; } var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match"); - var hasCacheKey = !cacheKey.Equals(Guid.Empty); + bool hasCacheKey = !cacheKey.Equals(Guid.Empty); // Validate If-None-Match - if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader))) + if ((hasCacheKey && !string.IsNullOrEmpty(ifNoneMatchHeader))) { - Guid ifNoneMatch; - ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"'); - if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch)) + if (Guid.TryParse(ifNoneMatchHeader, out var ifNoneMatch) + && cacheKey.Equals(ifNoneMatch)) { - if (hasCacheKey && cacheKey.Equals(ifNoneMatch)) - { - return true; - } + return true; } } @@ -771,7 +760,7 @@ namespace Emby.Server.Implementations.HttpServer /// /// The date. /// DateTime. - private DateTime NormalizeDateForComparison(DateTime date) + private static DateTime NormalizeDateForComparison(DateTime date) { return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind); } @@ -781,7 +770,7 @@ namespace Emby.Server.Implementations.HttpServer /// /// The has options. /// The response headers. - private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable> responseHeaders) + private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable> responseHeaders) { foreach (var item in responseHeaders) { diff --git a/Emby.Server.Implementations/HttpServer/IHttpListener.cs b/Emby.Server.Implementations/HttpServer/IHttpListener.cs index e21607ebd..835091361 100644 --- a/Emby.Server.Implementations/HttpServer/IHttpListener.cs +++ b/Emby.Server.Implementations/HttpServer/IHttpListener.cs @@ -1,10 +1,10 @@ -using MediaBrowser.Controller.Net; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Services; using Emby.Server.Implementations.Net; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.HttpServer { @@ -33,7 +33,7 @@ namespace Emby.Server.Implementations.HttpServer /// /// The web socket connecting. Action WebSocketConnecting { get; set; } - + /// /// Starts this instance. /// diff --git a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs index 5b7bbe79c..d22d9db26 100644 --- a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs +++ b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs @@ -1,7 +1,7 @@ -using Microsoft.Extensions.Logging; using System; using System.Globalization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index dc20ee1a2..891a76ec2 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -7,6 +6,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -40,16 +40,11 @@ namespace Emby.Server.Implementations.HttpServer /// private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - public List Cookies { get; private set; } - /// /// Additional HTTP Headers /// /// The headers. - public IDictionary Headers - { - get { return _options; } - } + public IDictionary Headers => _options; /// /// Initializes a new instance of the class. @@ -62,7 +57,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(contentType)) { - throw new ArgumentNullException("contentType"); + throw new ArgumentNullException(nameof(contentType)); } RangeHeader = rangeHeader; @@ -75,7 +70,6 @@ namespace Emby.Server.Implementations.HttpServer Headers["Accept-Ranges"] = "bytes"; StatusCode = HttpStatusCode.PartialContent; - Cookies = new List(); SetRangeValues(contentLength); } @@ -186,7 +180,7 @@ namespace Emby.Server.Implementations.HttpServer } } - private async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength) + private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength) { var array = new byte[BufferSize]; int bytesRead; @@ -220,10 +214,8 @@ namespace Emby.Server.Implementations.HttpServer public HttpStatusCode StatusCode { - get { return (HttpStatusCode)Status; } - set { Status = (int)value; } + get => (HttpStatusCode)Status; + set => Status = (int)value; } - - public string StatusDescription { get; set; } } } diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index f38aa5ea0..da2bf983a 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -1,8 +1,8 @@ -using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.Text; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -25,14 +25,11 @@ namespace Emby.Server.Implementations.HttpServer public void FilterResponse(IRequest req, IResponse res, object dto) { // Try to prevent compatibility view - //res.AddHeader("X-UA-Compatible", "IE=Edge"); res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization"); res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); res.AddHeader("Access-Control-Allow-Origin", "*"); - var exception = dto as Exception; - - if (exception != null) + if (dto is Exception exception) { _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); @@ -45,43 +42,26 @@ namespace Emby.Server.Implementations.HttpServer } } - var hasHeaders = dto as IHasHeaders; - - if (hasHeaders != null) + if (dto is IHasHeaders hasHeaders) { if (!hasHeaders.Headers.ContainsKey("Server")) { hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50"; - //hasHeaders.Headers["Server"] = "Mono-HTTPAPI/1.1"; } // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy - string contentLength; - - if (hasHeaders.Headers.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength)) + if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength) + && !string.IsNullOrEmpty(contentLength)) { var length = long.Parse(contentLength, UsCulture); if (length > 0) { res.SetContentLength(length); - - //var listenerResponse = res.OriginalResponse as HttpListenerResponse; - - //if (listenerResponse != null) - //{ - // // Disable chunked encoding. Technically this is only needed when using Content-Range, but - // // anytime we know the content length there's no need for it - // listenerResponse.SendChunked = false; - // return; - //} - res.SendChunked = false; } } } - - //res.KeepAlive = false; } /// diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index e153d6f71..499a334fc 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,15 +1,13 @@ -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Connect; -using MediaBrowser.Controller.Devices; +using System; +using System.Linq; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; -using System; -using System.Linq; using MediaBrowser.Model.Services; -using MediaBrowser.Common.Net; namespace Emby.Server.Implementations.HttpServer.Security { @@ -173,7 +171,7 @@ namespace Emby.Server.Implementations.HttpServer.Security return false; } - private void ValidateRoles(string[] roles, User user) + private static void ValidateRoles(string[] roles, User user) { if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase)) { @@ -207,10 +205,9 @@ namespace Emby.Server.Implementations.HttpServer.Security } } - private AuthenticationInfo GetTokenInfo(IRequest request) + private static AuthenticationInfo GetTokenInfo(IRequest request) { - object info; - request.Items.TryGetValue("OriginalAuthenticationInfo", out info); + request.Items.TryGetValue("OriginalAuthenticationInfo", out var info); return info as AuthenticationInfo; } diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index c3e2d3170..cab41e65b 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -1,12 +1,10 @@ -using MediaBrowser.Controller.Connect; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Security; using System; using System.Collections.Generic; -using MediaBrowser.Model.Services; using System.Linq; -using System.Threading; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Security; +using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.HttpServer.Security { @@ -28,8 +26,7 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext) { - object cached; - if (requestContext.Items.TryGetValue("AuthorizationInfo", out cached)) + if (requestContext.Items.TryGetValue("AuthorizationInfo", out var cached)) { return (AuthorizationInfo)cached; } @@ -115,7 +112,7 @@ namespace Emby.Server.Implementations.HttpServer.Security { info.Device = tokenInfo.DeviceName; } - + else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase)) { if (allowTokenInfoUpdate) @@ -227,7 +224,7 @@ namespace Emby.Server.Implementations.HttpServer.Security return result; } - private string NormalizeValue(string value) + private static string NormalizeValue(string value) { if (string.IsNullOrEmpty(value)) { diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index a919ce008..81e11d312 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -1,11 +1,10 @@ -using MediaBrowser.Controller.Entities; +using System; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; -using System.Threading.Tasks; using MediaBrowser.Model.Services; -using System; namespace Emby.Server.Implementations.HttpServer.Security { @@ -32,8 +31,7 @@ namespace Emby.Server.Implementations.HttpServer.Security private AuthenticationInfo GetTokenInfo(IRequest request) { - object info; - request.Items.TryGetValue("OriginalAuthenticationInfo", out info); + request.Items.TryGetValue("OriginalAuthenticationInfo", out var info); return info as AuthenticationInfo; } diff --git a/Emby.Server.Implementations/HttpServer/StreamWriter.cs b/Emby.Server.Implementations/HttpServer/StreamWriter.cs index 0a44a5fe5..3269d44cf 100644 --- a/Emby.Server.Implementations/HttpServer/StreamWriter.cs +++ b/Emby.Server.Implementations/HttpServer/StreamWriter.cs @@ -1,12 +1,11 @@ -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -35,10 +34,7 @@ namespace Emby.Server.Implementations.HttpServer /// Gets the options. /// /// The options. - public IDictionary Headers - { - get { return _options; } - } + public IDictionary Headers => _options; public Action OnComplete { get; set; } public Action OnError { get; set; } @@ -53,7 +49,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(contentType)) { - throw new ArgumentNullException("contentType"); + throw new ArgumentNullException(nameof(contentType)); } SourceStream = source; @@ -77,7 +73,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(contentType)) { - throw new ArgumentNullException("contentType"); + throw new ArgumentNullException(nameof(contentType)); } SourceBytes = source; diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index 914fa9dbc..e9d0bac74 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -1,15 +1,15 @@ -using System.Text; -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; -using System; +using System; +using System.Net.WebSockets; +using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Services; -using MediaBrowser.Model.Text; -using System.Net.WebSockets; using Emby.Server.Implementations.Net; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Net; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; +using UtfUnknown; namespace Emby.Server.Implementations.HttpServer { @@ -68,7 +68,6 @@ namespace Emby.Server.Implementations.HttpServer /// /// The query string. public QueryParamCollection QueryString { get; set; } - private readonly ITextEncoding _textEncoding; /// /// Initializes a new instance of the class. @@ -77,24 +76,24 @@ namespace Emby.Server.Implementations.HttpServer /// The remote end point. /// The json serializer. /// The logger. - /// socket - public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, ITextEncoding textEncoding) + /// socket + public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger) { if (socket == null) { - throw new ArgumentNullException("socket"); + throw new ArgumentNullException(nameof(socket)); } if (string.IsNullOrEmpty(remoteEndPoint)) { - throw new ArgumentNullException("remoteEndPoint"); + throw new ArgumentNullException(nameof(remoteEndPoint)); } if (jsonSerializer == null) { - throw new ArgumentNullException("jsonSerializer"); + throw new ArgumentNullException(nameof(jsonSerializer)); } if (logger == null) { - throw new ArgumentNullException("logger"); + throw new ArgumentNullException(nameof(logger)); } Id = Guid.NewGuid(); @@ -110,7 +109,6 @@ namespace Emby.Server.Implementations.HttpServer RemoteEndPoint = remoteEndPoint; _logger = logger; - _textEncoding = textEncoding; socket.Closed += socket_Closed; } @@ -132,8 +130,7 @@ namespace Emby.Server.Implementations.HttpServer { return; } - - var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false); + var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName; if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase)) { @@ -141,14 +138,15 @@ namespace Emby.Server.Implementations.HttpServer } else { - OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length)); + OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } } /// /// Called when [receive]. /// - /// The bytes. + /// The memory block. + /// The length of the memory block. private void OnReceiveInternal(Memory memory, int length) { LastActivityDate = DateTime.UtcNow; @@ -160,7 +158,7 @@ namespace Emby.Server.Implementations.HttpServer var bytes = memory.Slice(0, length).ToArray(); - var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false); + var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName; if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase)) { @@ -168,7 +166,7 @@ namespace Emby.Server.Implementations.HttpServer } else { - OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length)); + OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } } @@ -214,12 +212,12 @@ namespace Emby.Server.Implementations.HttpServer /// The message. /// The cancellation token. /// Task. - /// message + /// message public Task SendAsync(WebSocketMessage message, CancellationToken cancellationToken) { if (message == null) { - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); } var json = _jsonSerializer.SerializeToString(message); @@ -237,7 +235,7 @@ namespace Emby.Server.Implementations.HttpServer { if (buffer == null) { - throw new ArgumentNullException("buffer"); + throw new ArgumentNullException(nameof(buffer)); } cancellationToken.ThrowIfCancellationRequested(); @@ -249,7 +247,7 @@ namespace Emby.Server.Implementations.HttpServer { if (string.IsNullOrEmpty(text)) { - throw new ArgumentNullException("text"); + throw new ArgumentNullException(nameof(text)); } cancellationToken.ThrowIfCancellationRequested(); @@ -261,10 +259,7 @@ namespace Emby.Server.Implementations.HttpServer /// Gets the state. /// /// The state. - public WebSocketState State - { - get { return _socket.State; } - } + public WebSocketState State => _socket.State; /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. diff --git a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs index 6b08c26c9..48b34a3a0 100644 --- a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs +++ b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Emby.Server.Implementations.IO { public class ExtendedFileSystemInfo diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 34c711324..6bee178ea 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -1,16 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; -using MediaBrowser.Model.IO; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Extensions; -using Microsoft.Extensions.Logging; +using MediaBrowser.Model.IO; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.IO { @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (!_affectedPaths.Contains(path, StringComparer.Ordinal)) @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } lock (_timerLock) @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations.IO continue; } - Logger.LogInformation("{name} ({path}}) will be refreshed.", item.Name, item.Path); + Logger.LogInformation("{name} ({path}) will be refreshed.", item.Name, item.Path); try { @@ -164,7 +164,7 @@ namespace Emby.Server.Implementations.IO } catch (IOException ex) { - // For now swallow and log. + // For now swallow and log. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable) // Should we remove it from it's parent? Logger.LogError(ex, "Error refreshing {name}", item.Name); diff --git a/Emby.Server.Implementations/IO/IsoManager.cs b/Emby.Server.Implementations/IO/IsoManager.cs index 903d5f301..f0a15097c 100644 --- a/Emby.Server.Implementations/IO/IsoManager.cs +++ b/Emby.Server.Implementations/IO/IsoManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -23,13 +23,13 @@ namespace Emby.Server.Implementations.IO /// The iso path. /// The cancellation token. /// IsoMount. - /// isoPath - /// + /// isoPath + /// public Task Mount(string isoPath, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(isoPath)) { - throw new ArgumentNullException("isoPath"); + throw new ArgumentNullException(nameof(isoPath)); } var mounter = _mounters.FirstOrDefault(i => i.CanMount(isoPath)); diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index ca5810fd6..6a3204011 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; @@ -9,10 +9,10 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.IO { @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } TemporarilyIgnore(path); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } // This is an arbitraty amount of time, but delay it because file system writes often trigger events long after the file was actually written to. @@ -103,8 +103,7 @@ namespace Emby.Server.Implementations.IO // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata await Task.Delay(45000).ConfigureAwait(false); - string val; - _tempIgnoredPaths.TryRemove(path, out val); + _tempIgnoredPaths.TryRemove(path, out var val); if (refreshPath) { @@ -145,7 +144,7 @@ namespace Emby.Server.Implementations.IO { if (taskManager == null) { - throw new ArgumentNullException("taskManager"); + throw new ArgumentNullException(nameof(taskManager)); } LibraryManager = libraryManager; @@ -263,12 +262,12 @@ namespace Emby.Server.Implementations.IO /// The LST. /// The path. /// true if [contains parent folder] [the specified LST]; otherwise, false. - /// path + /// path private static bool ContainsParentFolder(IEnumerable lst, string path) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } path = path.TrimEnd(Path.DirectorySeparatorChar); @@ -365,9 +364,7 @@ namespace Emby.Server.Implementations.IO /// The path. private void StopWatchingPath(string path) { - FileSystemWatcher watcher; - - if (_fileSystemWatchers.TryGetValue(path, out watcher)) + if (_fileSystemWatchers.TryGetValue(path, out var watcher)) { DisposeWatcher(watcher, true); } @@ -424,9 +421,7 @@ namespace Emby.Server.Implementations.IO /// The watcher. private void RemoveWatcherFromList(FileSystemWatcher watcher) { - FileSystemWatcher removed; - - _fileSystemWatchers.TryRemove(watcher.Path, out removed); + _fileSystemWatchers.TryRemove(watcher.Path, out var removed); } /// @@ -469,7 +464,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var filename = Path.GetFileName(path); diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 0f85e0642..3e7774abf 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -1,12 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.IO { @@ -29,9 +29,14 @@ namespace Emby.Server.Implementations.IO private string _defaultDirectory; - public ManagedFileSystem(ILogger logger, IEnvironmentInfo environmentInfo, string defaultDirectory, string tempPath, bool enableSeparateFileAndDirectoryQueries) + public ManagedFileSystem( + ILoggerFactory loggerFactory, + IEnvironmentInfo environmentInfo, + string defaultDirectory, + string tempPath, + bool enableSeparateFileAndDirectoryQueries) { - Logger = logger; + Logger = loggerFactory.CreateLogger("FileSystem"); _supportsAsyncFileStreams = true; _tempPath = tempPath; _environmentInfo = environmentInfo; @@ -85,17 +90,11 @@ namespace Emby.Server.Implementations.IO { // Be consistent across platforms because the windows server will fail to query network shares that don't follow windows conventions // https://referencesource.microsoft.com/#mscorlib/system/io/path.cs - _invalidFileNameChars = new char[] { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, ':', '*', '?', '\\', '/' }; + _invalidFileNameChars = new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; } } - public char DirectorySeparatorChar - { - get - { - return Path.DirectorySeparatorChar; - } - } + public char DirectorySeparatorChar => Path.DirectorySeparatorChar; public string GetFullPath(string path) { @@ -107,12 +106,12 @@ namespace Emby.Server.Implementations.IO /// /// The filename. /// true if the specified filename is shortcut; otherwise, false. - /// filename + /// filename public virtual bool IsShortcut(string filename) { if (string.IsNullOrEmpty(filename)) { - throw new ArgumentNullException("filename"); + throw new ArgumentNullException(nameof(filename)); } var extension = Path.GetExtension(filename); @@ -124,12 +123,12 @@ namespace Emby.Server.Implementations.IO /// /// The filename. /// System.String. - /// filename + /// filename public virtual string ResolveShortcut(string filename) { if (string.IsNullOrEmpty(filename)) { - throw new ArgumentNullException("filename"); + throw new ArgumentNullException(nameof(filename)); } var extension = Path.GetExtension(filename); @@ -145,7 +144,7 @@ namespace Emby.Server.Implementations.IO public string MakeAbsolutePath(string folderPath, string filePath) { - if (String.IsNullOrWhiteSpace(filePath)) return filePath; + if (string.IsNullOrWhiteSpace(filePath)) return filePath; if (filePath.Contains(@"://")) return filePath; //stream if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/') return filePath; //absolute local path @@ -159,7 +158,7 @@ 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 @@ -191,7 +190,7 @@ namespace Emby.Server.Implementations.IO /// /// The shortcut path. /// The target. - /// + /// /// shortcutPath /// or /// target @@ -200,12 +199,12 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(shortcutPath)) { - throw new ArgumentNullException("shortcutPath"); + throw new ArgumentNullException(nameof(shortcutPath)); } if (string.IsNullOrEmpty(target)) { - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); } var extension = Path.GetExtension(shortcutPath); @@ -321,7 +320,7 @@ namespace Emby.Server.Implementations.IO return result; } - private ExtendedFileSystemInfo GetExtendedFileSystemInfo(string path) + private static ExtendedFileSystemInfo GetExtendedFileSystemInfo(string path) { var result = new ExtendedFileSystemInfo(); @@ -350,7 +349,7 @@ namespace Emby.Server.Implementations.IO /// /// The filename. /// System.String. - /// filename + /// filename public string GetValidFilename(string filename) { var builder = new StringBuilder(filename); @@ -451,18 +450,15 @@ namespace Emby.Server.Implementations.IO } public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) - { - var defaultBufferSize = 4096; - return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions)); - } + => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions)); - private FileOptions GetFileOptions(FileOpenOptions mode) + private static FileOptions GetFileOptions(FileOpenOptions mode) { var val = (int)mode; return (FileOptions)val; } - private FileMode GetFileMode(FileOpenMode mode) + private static FileMode GetFileMode(FileOpenMode mode) { switch (mode) { @@ -483,7 +479,7 @@ namespace Emby.Server.Implementations.IO } } - private FileAccess GetFileAccess(FileAccessMode mode) + private static FileAccess GetFileAccess(FileAccessMode mode) { switch (mode) { @@ -498,7 +494,7 @@ namespace Emby.Server.Implementations.IO } } - private FileShare GetFileShare(FileShareMode mode) + private static FileShare GetFileShare(FileShareMode mode) { switch (mode) { @@ -532,7 +528,7 @@ namespace Emby.Server.Implementations.IO } else { - FileAttributes attributes = File.GetAttributes(path); + var attributes = File.GetAttributes(path); attributes = RemoveAttribute(attributes, FileAttributes.Hidden); File.SetAttributes(path, attributes); } @@ -556,7 +552,7 @@ namespace Emby.Server.Implementations.IO } else { - FileAttributes attributes = File.GetAttributes(path); + var attributes = File.GetAttributes(path); attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly); File.SetAttributes(path, attributes); } @@ -619,12 +615,12 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(file1)) { - throw new ArgumentNullException("file1"); + throw new ArgumentNullException(nameof(file1)); } if (string.IsNullOrEmpty(file2)) { - throw new ArgumentNullException("file2"); + throw new ArgumentNullException(nameof(file2)); } var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N")); @@ -640,7 +636,7 @@ namespace Emby.Server.Implementations.IO CopyFile(temp1, file2, true); } - private char GetDirectorySeparatorChar(string path) + private static char GetDirectorySeparatorChar(string path) { return Path.DirectorySeparatorChar; } @@ -649,12 +645,12 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(parentPath)) { - throw new ArgumentNullException("parentPath"); + throw new ArgumentNullException(nameof(parentPath)); } if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var separatorChar = GetDirectorySeparatorChar(parentPath); @@ -666,7 +662,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var parent = GetDirectoryName(path); @@ -688,7 +684,7 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase)) @@ -765,18 +761,13 @@ namespace Emby.Server.Implementations.IO // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata { - Name = GetName(d), + Name = d.Name, FullName = d.RootDirectory.FullName, IsDirectory = true }).ToList(); } - private string GetName(DriveInfo drive) - { - return drive.Name; - } - public IEnumerable GetDirectories(string path, bool recursive = false) { var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; @@ -852,17 +843,6 @@ namespace Emby.Server.Implementations.IO return File.OpenRead(path); } - private void CopyFileUsingStreams(string source, string target, bool overwrite) - { - using (var sourceStream = OpenRead(source)) - { - using (var targetStream = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) - { - sourceStream.CopyTo(targetStream); - } - } - } - public void CopyFile(string source, string target, bool overwrite) { File.Copy(source, target, overwrite); @@ -972,7 +952,7 @@ namespace Emby.Server.Implementations.IO } } - private void RunProcess(string path, string args, string workingDirectory) + private static void RunProcess(string path, string args, string workingDirectory) { using (var process = Process.Start(new ProcessStartInfo { diff --git a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs index aef53751e..a306f94b3 100644 --- a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs +++ b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs @@ -1,7 +1,5 @@ -using System; +using System; using System.IO; - -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.IO @@ -15,16 +13,13 @@ namespace Emby.Server.Implementations.IO _fileSystem = fileSystem; } - public string Extension - { - get { return ".mblink"; } - } + public string Extension => ".mblink"; public string Resolve(string shortcutPath) { if (string.IsNullOrEmpty(shortcutPath)) { - throw new ArgumentNullException("filenshortcutPathame"); + throw new ArgumentException("Shortcut path is empty or null.", nameof(shortcutPath)); } if (string.Equals(Path.GetExtension(shortcutPath), ".mblink", StringComparison.OrdinalIgnoreCase)) @@ -41,12 +36,12 @@ namespace Emby.Server.Implementations.IO { if (string.IsNullOrEmpty(shortcutPath)) { - throw new ArgumentNullException("shortcutPath"); + throw new ArgumentNullException(nameof(shortcutPath)); } if (string.IsNullOrEmpty(targetPath)) { - throw new ArgumentNullException("targetPath"); + throw new ArgumentNullException(nameof(targetPath)); } _fileSystem.WriteAllText(shortcutPath, targetPath); diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs index e91817611..09cf4d4a3 100644 --- a/Emby.Server.Implementations/IO/StreamHelper.cs +++ b/Emby.Server.Implementations/IO/StreamHelper.cs @@ -1,6 +1,6 @@ -using System.IO; -using System.Threading; using System; +using System.IO; +using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; diff --git a/Emby.Server.Implementations/IO/ThrottledStream.cs b/Emby.Server.Implementations/IO/ThrottledStream.cs index 81760b639..81e8abc98 100644 --- a/Emby.Server.Implementations/IO/ThrottledStream.cs +++ b/Emby.Server.Implementations/IO/ThrottledStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -42,13 +42,7 @@ namespace Emby.Server.Implementations.IO /// Gets the current milliseconds. /// /// The current milliseconds. - protected long CurrentMilliseconds - { - get - { - return Environment.TickCount; - } - } + protected long CurrentMilliseconds => Environment.TickCount; /// /// Gets or sets the maximum bytes per second that can be transferred through the base stream. @@ -56,10 +50,7 @@ namespace Emby.Server.Implementations.IO /// The maximum bytes per second. public long MaximumBytesPerSecond { - get - { - return _maximumBytesPerSecond; - } + get => _maximumBytesPerSecond; set { if (MaximumBytesPerSecond != value) @@ -74,39 +65,21 @@ namespace Emby.Server.Implementations.IO /// Gets a value indicating whether the current stream supports reading. /// /// true if the stream supports reading; otherwise, false. - public override bool CanRead - { - get - { - return _baseStream.CanRead; - } - } + public override bool CanRead => _baseStream.CanRead; /// /// Gets a value indicating whether the current stream supports seeking. /// /// /// true if the stream supports seeking; otherwise, false. - public override bool CanSeek - { - get - { - return _baseStream.CanSeek; - } - } + public override bool CanSeek => _baseStream.CanSeek; /// /// Gets a value indicating whether the current stream supports writing. /// /// /// true if the stream supports writing; otherwise, false. - public override bool CanWrite - { - get - { - return _baseStream.CanWrite; - } - } + public override bool CanWrite => _baseStream.CanWrite; /// /// Gets the length in bytes of the stream. @@ -115,13 +88,7 @@ namespace Emby.Server.Implementations.IO /// A long value representing the length of the stream in bytes. /// The base stream does not support seeking. /// Methods were called after the stream was closed. - public override long Length - { - get - { - return _baseStream.Length; - } - } + public override long Length => _baseStream.Length; /// /// Gets or sets the position within the current stream. @@ -133,14 +100,8 @@ namespace Emby.Server.Implementations.IO /// Methods were called after the stream was closed. public override long Position { - get - { - return _baseStream.Position; - } - set - { - _baseStream.Position = value; - } + get => _baseStream.Position; + set => _baseStream.Position = value; } #endregion @@ -158,12 +119,12 @@ namespace Emby.Server.Implementations.IO { if (baseStream == null) { - throw new ArgumentNullException("baseStream"); + throw new ArgumentNullException(nameof(baseStream)); } if (maximumBytesPerSecond < 0) { - throw new ArgumentOutOfRangeException("maximumBytesPerSecond", + throw new ArgumentOutOfRangeException(nameof(maximumBytesPerSecond), maximumBytesPerSecond, "The maximum number of bytes per second can't be negative."); } @@ -303,7 +264,7 @@ namespace Emby.Server.Implementations.IO { if (!ThrottleCheck(bufferSizeInBytes)) { - return ; + return; } _byteCount += bufferSizeInBytes; @@ -391,4 +352,4 @@ namespace Emby.Server.Implementations.IO } #endregion } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs index be17893d8..b99b98157 100644 --- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs @@ -1,22 +1,18 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Playlists; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; - -using MediaBrowser.Model.IO; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.Configuration; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Playlists; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; namespace Emby.Server.Implementations.Images @@ -193,10 +189,7 @@ namespace Emby.Server.Implementations.Images return outputPath; } - public string Name - { - get { return "Dynamic Image Provider"; } - } + public string Name => "Dynamic Image Provider"; protected virtual string CreateImage(BaseItem item, List itemsWithImages, @@ -232,10 +225,7 @@ namespace Emby.Server.Implementations.Images throw new ArgumentException("Unexpected image type"); } - protected virtual int MaxImageAgeDays - { - get { return 7; } - } + protected virtual int MaxImageAgeDays => 7; public bool HasChanged(BaseItem item, IDirectoryService directoryServicee) { @@ -293,14 +283,7 @@ namespace Emby.Server.Implementations.Images return true; } - public int Order - { - get - { - // Run before the default image provider which will download placeholders - return 0; - } - } + public int Order => 0; protected string CreateSingleImage(List itemsWithImages, string outputPathWithoutExtension, ImageType imageType) { diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index 7fb979d66..c0a126b84 100644 --- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -1,13 +1,10 @@ -using MediaBrowser.Model.Extensions; +using System; +using System.Collections.Generic; +using System.Linq; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using MediaBrowser.Controller.IO; +using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; diff --git a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs index 7c79a7c69..4013ac0c8 100644 --- a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs +++ b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System; using System.Text; using System.Threading.Tasks; using MediaBrowser.Controller.Authentication; @@ -67,7 +66,7 @@ namespace Emby.Server.Implementations.Library if (string.IsNullOrWhiteSpace(newPasswordHash)) { - throw new ArgumentNullException("newPasswordHash"); + throw new ArgumentNullException(nameof(newPasswordHash)); } user.Password = newPasswordHash; diff --git a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs index 186ec63da..45a33a296 100644 --- a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs +++ b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs @@ -1,8 +1,8 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Dto; using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Dto; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 451f16bef..ad070ed79 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1,23 +1,3 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Progress; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Controller.Resolvers; -using MediaBrowser.Controller.Sorting; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; -using Emby.Naming.Audio; -using Emby.Naming.Common; -using Emby.Naming.TV; -using Emby.Naming.Video; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -27,26 +7,42 @@ using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; +using Emby.Naming.Audio; +using Emby.Naming.Common; +using Emby.Naming.TV; +using Emby.Naming.Video; using Emby.Server.Implementations.Library.Resolvers; using Emby.Server.Implementations.Library.Validators; +using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.ScheduledTasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Channels; -using MediaBrowser.Model.Channels; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Progress; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.IO; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Resolvers; +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; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Tasks; +using MediaBrowser.Providers.MediaInfo; +using Microsoft.Extensions.Logging; using SortOrder = MediaBrowser.Model.Entities.SortOrder; using VideoResolver = Emby.Naming.Video.VideoResolver; -using MediaBrowser.Common.Configuration; - -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Tasks; -using Emby.Server.Implementations.Playlists; -using MediaBrowser.Providers.MediaInfo; -using MediaBrowser.Controller; namespace Emby.Server.Implementations.Library { @@ -147,13 +143,7 @@ namespace Emby.Server.Implementations.Library /// Gets the library items cache. /// /// The library items cache. - private ConcurrentDictionary LibraryItemsCache - { - get - { - return _libraryItemsCache; - } - } + private ConcurrentDictionary LibraryItemsCache => _libraryItemsCache; private readonly IFileSystem _fileSystem; @@ -165,9 +155,19 @@ namespace Emby.Server.Implementations.Library /// The user manager. /// The configuration manager. /// The user data repository. - public LibraryManager(IServerApplicationHost appHost, ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func libraryMonitorFactory, IFileSystem fileSystem, Func providerManagerFactory, Func userviewManager) + public LibraryManager( + IServerApplicationHost appHost, + ILoggerFactory loggerFactory, + ITaskManager taskManager, + IUserManager userManager, + IServerConfigurationManager configurationManager, + IUserDataManager userDataRepository, + Func libraryMonitorFactory, + IFileSystem fileSystem, + Func providerManagerFactory, + Func userviewManager) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(LibraryManager)); _taskManager = taskManager; _userManager = userManager; ConfigurationManager = configurationManager; @@ -188,7 +188,6 @@ namespace Emby.Server.Implementations.Library /// Adds the parts. /// /// The rules. - /// The plugin folders. /// The resolvers. /// The intro providers. /// The item comparers. @@ -277,7 +276,7 @@ namespace Emby.Server.Implementations.Library { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } if (item is IItemByName) { @@ -317,7 +316,7 @@ namespace Emby.Server.Implementations.Library { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } var parent = item.GetOwner() ?? item.GetParent(); @@ -329,7 +328,7 @@ namespace Emby.Server.Implementations.Library { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } if (item.SourceType == SourceType.Channel) @@ -398,7 +397,7 @@ namespace Emby.Server.Implementations.Library { try { - _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName); + _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName); if (fileSystemInfo.IsDirectory) { _fileSystem.DeleteDirectory(fileSystemInfo.FullName, true); @@ -443,13 +442,12 @@ namespace Emby.Server.Implementations.Library ItemRepository.DeleteItem(child.Id, CancellationToken.None); } - BaseItem removed; - _libraryItemsCache.TryRemove(item.Id, out removed); + _libraryItemsCache.TryRemove(item.Id, out BaseItem removed); ReportItemRemoved(item, parent); } - private IEnumerable GetMetadataPaths(BaseItem item, IEnumerable children) + private static IEnumerable GetMetadataPaths(BaseItem item, IEnumerable children) { var list = new List { @@ -502,11 +500,11 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath)) @@ -542,7 +540,7 @@ namespace Emby.Server.Implementations.Library { if (fileInfo == null) { - throw new ArgumentNullException("fileInfo"); + throw new ArgumentNullException(nameof(fileInfo)); } var fullPath = fileInfo.FullName; @@ -722,14 +720,14 @@ namespace Emby.Server.Implementations.Library /// Creates the root media folder /// /// AggregateFolder. - /// Cannot create the root folder until plugins have loaded + /// Cannot create the root folder until plugins have loaded public AggregateFolder CreateRootFolder() { var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath; _fileSystem.CreateDirectory(rootFolderPath); - var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy(); + var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy(); // In case program data folder was moved if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal)) @@ -798,7 +796,7 @@ namespace Emby.Server.Implementations.Library if (tmpItem == null) { - tmpItem = ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath))).DeepCopy(); + tmpItem = ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath))).DeepCopy(); } // In case program data folder was moved @@ -818,12 +816,12 @@ namespace Emby.Server.Implementations.Library public BaseItem FindByPath(string path, bool? isFolder) { - // If this returns multiple items it could be tricky figuring out which one is correct. + // If this returns multiple items it could be tricky figuring out which one is correct. // In most cases, the newest one will be and the others obsolete but not yet cleaned up if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } //_logger.LogInformation("FindByPath {0}", path); @@ -916,12 +914,12 @@ namespace Emby.Server.Implementations.Library /// /// The value. /// Task{Year}. - /// + /// public Year GetYear(int value) { if (value <= 0) { - throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid."); + throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid."); } var name = value.ToString(CultureInfo.InvariantCulture); @@ -1244,17 +1242,15 @@ namespace Emby.Server.Implementations.Library /// /// The id. /// BaseItem. - /// id + /// id public BaseItem GetItemById(Guid id) { if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } - BaseItem item; - - if (LibraryItemsCache.TryGetValue(id, out item)) + if (LibraryItemsCache.TryGetValue(id, out BaseItem item)) { return item; } @@ -1699,7 +1695,7 @@ namespace Emby.Server.Implementations.Library { try { - // Try to resolve the path into a video + // Try to resolve the path into a video video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video; if (video == null) @@ -1828,7 +1824,7 @@ namespace Emby.Server.Implementations.Library /// Creates the item. /// /// The item. - /// The cancellation token. + /// The parent item. /// Task. public void CreateItem(BaseItem item, BaseItem parent) { @@ -2023,7 +2019,7 @@ namespace Emby.Server.Implementations.Library return GetCollectionFoldersInternal(item, allUserRootChildren); } - private List GetCollectionFoldersInternal(BaseItem item, List allUserRootChildren) + private static List GetCollectionFoldersInternal(BaseItem item, List allUserRootChildren) { return allUserRootChildren .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase)) @@ -2086,7 +2082,7 @@ namespace Emby.Server.Implementations.Library public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath) { - ICollectionFolder collectionFolder = item as ICollectionFolder; + var collectionFolder = item as ICollectionFolder; if (collectionFolder != null) { return collectionFolder.CollectionType; @@ -2247,7 +2243,7 @@ namespace Emby.Server.Implementations.Library { if (parent == null) { - throw new ArgumentNullException("parent"); + throw new ArgumentNullException(nameof(parent)); } var name = parent.Name; @@ -2313,7 +2309,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N"); @@ -2382,7 +2378,7 @@ namespace Emby.Server.Implementations.Library string videoPath, string[] files) { - new SubtitleResolver(BaseItem.LocalizationManager, _fileSystem).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files); + new SubtitleResolver(BaseItem.LocalizationManager, _fileSystem).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files); } public bool IsVideoFile(string path, LibraryOptions libraryOptions) @@ -2428,11 +2424,11 @@ namespace Emby.Server.Implementations.Library var episodeInfo = episode.IsFileProtocol ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) : - new Emby.Naming.TV.EpisodeInfo(); + new Naming.TV.EpisodeInfo(); if (episodeInfo == null) { - episodeInfo = new Emby.Naming.TV.EpisodeInfo(); + episodeInfo = new Naming.TV.EpisodeInfo(); } var changed = false; @@ -2596,7 +2592,7 @@ namespace Emby.Server.Implementations.Library video.ParentId = Guid.Empty; video.OwnerId = owner.Id; video.ExtraType = ExtraType.Trailer; - video.TrailerTypes = new [] { TrailerType.LocalTrailer }; + video.TrailerTypes = new[] { TrailerType.LocalTrailer }; return video; @@ -2708,15 +2704,15 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrWhiteSpace(from)) { - throw new ArgumentNullException("from"); + throw new ArgumentNullException(nameof(from)); } if (string.IsNullOrWhiteSpace(to)) { - throw new ArgumentNullException("to"); + throw new ArgumentNullException(nameof(to)); } from = from.Trim(); @@ -2864,7 +2860,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } name = _fileSystem.GetValidFilename(name); @@ -2937,7 +2933,7 @@ namespace Emby.Server.Implementations.Library }); } - private bool ValidateNetworkPath(string path) + private static bool ValidateNetworkPath(string path) { //if (Environment.OSVersion.Platform == PlatformID.Win32NT) //{ @@ -2962,14 +2958,14 @@ namespace Emby.Server.Implementations.Library { if (pathInfo == null) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(pathInfo)); } var path = pathInfo.Path; if (string.IsNullOrWhiteSpace(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (!_fileSystem.DirectoryExists(path)) @@ -3017,7 +3013,7 @@ namespace Emby.Server.Implementations.Library { if (pathInfo == null) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(pathInfo)); } if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath)) @@ -3075,7 +3071,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; @@ -3116,7 +3112,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var removeList = new List(); @@ -3148,7 +3144,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(mediaPath)) { - throw new ArgumentNullException("mediaPath"); + throw new ArgumentNullException(nameof(mediaPath)); } var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index d0b3152ba..c3082a78a 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -1,19 +1,19 @@ -using System; +using System; +using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; -using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Configuration; -using System.IO; -using MediaBrowser.Common.Extensions; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index ddda4b2c3..0adc5553b 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -1,28 +1,27 @@ -using MediaBrowser.Common.Extensions; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Threading; -using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Globalization; -using System.IO; -using System.Globalization; -using MediaBrowser.Common.Configuration; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { @@ -42,12 +41,23 @@ namespace Emby.Server.Implementations.Library private ILocalizationManager _localizationManager; private IApplicationPaths _appPaths; - public MediaSourceManager(IItemRepository itemRepo, IApplicationPaths applicationPaths, ILocalizationManager localizationManager, IUserManager userManager, ILibraryManager libraryManager, ILogger logger, IJsonSerializer jsonSerializer, IFileSystem fileSystem, IUserDataManager userDataManager, ITimerFactory timerFactory, Func mediaEncoder) + public MediaSourceManager( + IItemRepository itemRepo, + IApplicationPaths applicationPaths, + ILocalizationManager localizationManager, + IUserManager userManager, + ILibraryManager libraryManager, + ILoggerFactory loggerFactory, + IJsonSerializer jsonSerializer, + IFileSystem fileSystem, + IUserDataManager userDataManager, + ITimerFactory timerFactory, + Func mediaEncoder) { _itemRepo = itemRepo; _userManager = userManager; _libraryManager = libraryManager; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(MediaSourceManager)); _jsonSerializer = jsonSerializer; _fileSystem = fileSystem; _userDataManager = userDataManager; @@ -74,7 +84,7 @@ namespace Emby.Server.Implementations.Library return list; } - private bool StreamSupportsExternalStream(MediaStream stream) + private static bool StreamSupportsExternalStream(MediaStream stream) { if (stream.IsExternal) { @@ -128,7 +138,7 @@ namespace Emby.Server.Implementations.Library if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video)) { - await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { EnableRemoteContentProbe = true, MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh @@ -261,7 +271,7 @@ namespace Emby.Server.Implementations.Library } } - private void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource) + private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource) { var prefix = provider.GetType().FullName.GetMD5().ToString("N") + LiveStreamIdDelimeter; @@ -292,7 +302,7 @@ namespace Emby.Server.Implementations.Library { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } var hasMediaSources = (IHasMediaSources)item; @@ -401,7 +411,7 @@ namespace Emby.Server.Implementations.Library } } - private IEnumerable SortMediaSources(IEnumerable sources) + private static IEnumerable SortMediaSources(IEnumerable sources) { return sources.OrderBy(i => { @@ -501,7 +511,7 @@ namespace Emby.Server.Implementations.Library }, liveStream as IDirectStreamProvider); } - private void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio) + private static void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio) { mediaSource.DefaultSubtitleStreamIndex = null; @@ -629,6 +639,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { + _logger.LogDebug(ex, "_jsonSerializer.DeserializeFromFile threw an exception."); } } @@ -759,7 +770,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } var info = await GetLiveStreamInfo(id, cancellationToken).ConfigureAwait(false); @@ -770,15 +781,14 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { - ILiveStream info; - if (_openStreams.TryGetValue(id, out info)) + if (_openStreams.TryGetValue(id, out ILiveStream info)) { return info; } @@ -803,16 +813,14 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false); try { - ILiveStream liveStream; - - if (_openStreams.TryGetValue(id, out liveStream)) + if (_openStreams.TryGetValue(id, out ILiveStream liveStream)) { liveStream.ConsumerCount--; diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs index 5d4c5a452..0a6c8845d 100644 --- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs +++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs @@ -1,8 +1,8 @@ -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Entities; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.Library { @@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Library private static int FindIndex(string[] list, string value) { - for (var i=0; i< list.Length; i++) + for (var i = 0; i < list.Length; i++) { if (string.Equals(list[i], value, StringComparison.OrdinalIgnoreCase)) { diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs index 1319ee6f4..10602fea7 100644 --- a/Emby.Server.Implementations/Library/MusicManager.cs +++ b/Emby.Server.Implementations/Library/MusicManager.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Playlists; using System; using System.Collections.Generic; using System.Linq; using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -89,7 +89,7 @@ namespace Emby.Server.Implementations.Library Limit = 200, - OrderBy = new [] { new ValueTuple(ItemSortBy.Random, SortOrder.Ascending) }, + OrderBy = new[] { new ValueTuple(ItemSortBy.Random, SortOrder.Ascending) }, DtoOptions = dtoOptions diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 28ed2f53c..d3a81f622 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; namespace Emby.Server.Implementations.Library @@ -11,17 +11,17 @@ namespace Emby.Server.Implementations.Library /// The STR. /// The attrib. /// System.String. - /// attrib + /// attrib public static string GetAttributeValue(this string str, string attrib) { if (string.IsNullOrEmpty(str)) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } if (string.IsNullOrEmpty(attrib)) { - throw new ArgumentNullException("attrib"); + throw new ArgumentNullException(nameof(attrib)); } string srch = "[" + attrib + "="; diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs index 14b28966a..96d1bff92 100644 --- a/Emby.Server.Implementations/Library/ResolverHelper.cs +++ b/Emby.Server.Implementations/Library/ResolverHelper.cs @@ -1,10 +1,9 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; using System; using System.IO; using System.Linq; -using System.Text.RegularExpressions; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library @@ -22,7 +21,7 @@ namespace Emby.Server.Implementations.Library /// The file system. /// The library manager. /// The directory service. - /// Item must have a path + /// Item must have a path public static void SetInitialItemValues(BaseItem item, Folder parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService) { // This version of the below method has no ItemResolveArgs, so we have to require the path already being set @@ -104,7 +103,7 @@ namespace Emby.Server.Implementations.Library /// System.String. private static string GetDisplayName(string path, bool isDirectory) { - return isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path); + return isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path); } /// @@ -117,15 +116,15 @@ namespace Emby.Server.Implementations.Library { if (fileSystem == null) { - throw new ArgumentNullException("fileSystem"); + throw new ArgumentNullException(nameof(fileSystem)); } if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } if (args == null) { - throw new ArgumentNullException("args"); + throw new ArgumentNullException(nameof(args)); } // See if a different path came out of the resolver than what went in diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 8872bd641..baa665fce 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -1,16 +1,14 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Resolvers; -using MediaBrowser.Model.Entities; using System; -using MediaBrowser.Controller.Entities; +using System.Collections.Generic; using System.IO; using System.Linq; -using MediaBrowser.Controller.Providers; -using System.Collections.Generic; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Extensions; -using Emby.Naming.Video; using Emby.Naming.AudioBook; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Resolvers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library.Resolvers.Audio { @@ -30,10 +28,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get { return ResolverPriority.Fourth; } - } + public override ResolverPriority Priority => ResolverPriority.Fourth; public MultiItemResolverResult ResolveMultiple(Folder parent, List files, @@ -231,7 +226,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } var firstMedia = resolvedItem.Files.First(); - + var libraryItem = new T { Path = firstMedia.Path, @@ -264,12 +259,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio result.Extras.Any(i => ContainsFile(i, file)); } - private bool ContainsFile(AudioBookFileInfo result, FileSystemMetadata file) + private static bool ContainsFile(AudioBookFileInfo result, FileSystemMetadata file) { return string.Equals(result.Path, file.FullName, StringComparison.OrdinalIgnoreCase); } - private bool IsIgnored(string filename) + private static bool IsIgnored(string filename) { return false; } diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index dbfcf41e8..3ce1da81a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -1,18 +1,14 @@ -using MediaBrowser.Controller.Entities.Audio; +using System; +using System.Collections.Generic; +using Emby.Naming.Audio; +using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using Emby.Naming.Audio; -using System; -using System.Collections.Generic; -using System.IO; - -using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.Audio { @@ -36,14 +32,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get - { - // Behind special folder resolver - return ResolverPriority.Second; - } - } + public override ResolverPriority Priority => ResolverPriority.Second; /// /// Resolves the specified args. diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 71ccd7da8..74e9b8304 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -1,15 +1,12 @@ -using MediaBrowser.Controller.Entities.Audio; +using System; +using System.Linq; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using System; -using System.IO; -using System.Linq; - using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.Audio { @@ -35,14 +32,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get - { - // Behind special folder resolver - return ResolverPriority.Second; - } - } + public override ResolverPriority Priority => ResolverPriority.Second; /// /// Resolves the specified args. diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 143af4076..d992f8d03 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -1,13 +1,12 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Entities; -using Emby.Naming.Video; using System; using System.IO; using System.Linq; +using Emby.Naming.Video; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers { @@ -48,9 +47,9 @@ namespace Emby.Server.Implementations.Library.Resolvers where TVideoType : Video, new() { var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); - + // If the path is a file check for a matching extensions - var parser = new Emby.Naming.Video.VideoResolver(namingOptions); + var parser = new VideoResolver(namingOptions); if (args.IsDirectory) { @@ -120,7 +119,7 @@ namespace Emby.Server.Implementations.Library.Resolvers if (video != null) { - video.Name = parseName ? + video.Name = parseName ? videoInfo.Name : Path.GetFileName(args.Path); @@ -150,7 +149,7 @@ namespace Emby.Server.Implementations.Library.Resolvers }; SetVideoType(video, videoInfo); - + video.Name = parseName ? videoInfo.Name : Path.GetFileNameWithoutExtension(args.Path); @@ -281,7 +280,7 @@ namespace Emby.Server.Implementations.Library.Resolvers { return string.Equals(name, "video_ts.ifo", StringComparison.OrdinalIgnoreCase); } - + /// /// Determines whether [is blu ray directory] [the specified directory name]. /// diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs index 7aa4c299f..f22554ee5 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using MediaBrowser.Controller.Entities; @@ -8,14 +8,14 @@ using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.Library.Resolvers.Books { /// - /// + /// /// public class BookResolver : MediaBrowser.Controller.Resolvers.ItemResolver { private readonly string[] _validExtensions = { ".pdf", ".epub", ".mobi", ".cbr", ".cbz", ".azw3" }; /// - /// + /// /// /// /// @@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books } /// - /// + /// /// /// /// diff --git a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs index 5e73baa5c..e48b6c967 100644 --- a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; @@ -13,10 +13,7 @@ namespace Emby.Server.Implementations.Library.Resolvers /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get { return ResolverPriority.Last; } - } + public override ResolverPriority Priority => ResolverPriority.Last; /// /// Resolves the specified args. diff --git a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs index b4a37be5f..a6db40714 100644 --- a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; @@ -25,13 +25,7 @@ namespace Emby.Server.Implementations.Library.Resolvers /// Gets the priority. /// /// The priority. - public virtual ResolverPriority Priority - { - get - { - return ResolverPriority.First; - } - } + public virtual ResolverPriority Priority => ResolverPriority.First; /// /// Sets initial values on the newly resolved item diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs index b9aca1417..922bd4bbb 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs @@ -1,9 +1,9 @@ -using MediaBrowser.Controller.Entities; +using System; +using System.IO; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using System; -using System.IO; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.Library.Resolvers.Movies @@ -61,7 +61,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// Sets the provider id from path. /// /// The item. - private void SetProviderIdFromPath(BaseItem item) + private static void SetProviderIdFromPath(BaseItem item) { //we need to only look at the name of this actual item (not parents) var justName = Path.GetFileName(item.Path); diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 68b6c57ae..e48213dbb 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -1,4 +1,10 @@ -using MediaBrowser.Controller.Entities; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Emby.Naming.Video; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -6,15 +12,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using Emby.Naming.Video; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.Movies { @@ -27,17 +25,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get - { - // Give plugins a chance to catch iso's first - // Also since we have to loop through child files looking for videos, - // see if we can avoid some of that by letting other resolvers claim folders first - // Also run after series resolver - return ResolverPriority.Third; - } - } + public override ResolverPriority Priority => ResolverPriority.Third; public MultiItemResolverResult ResolveMultiple(Folder parent, List files, @@ -176,7 +164,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return result; } - private bool IsIgnored(string filename) + private static bool IsIgnored(string filename) { // Ignore samples var sampleFilename = " " + filename.Replace(".", " ", StringComparison.OrdinalIgnoreCase) @@ -204,7 +192,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies result.Extras.Any(i => ContainsFile(i, file)); } - private bool ContainsFile(VideoFileInfo result, FileSystemMetadata file) + private static bool ContainsFile(VideoFileInfo result, FileSystemMetadata file) { return string.Equals(result.Path, file.FullName, StringComparison.OrdinalIgnoreCase); } @@ -330,7 +318,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// Sets the provider id from path. /// /// The item. - private void SetProviderIdsFromPath(Video item) + private static void SetProviderIdsFromPath(Video item) { if (item is Movie || item is MusicVideo) { diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 311abf14e..82779f8d3 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -1,11 +1,9 @@ -using MediaBrowser.Controller.Drawing; +using System; +using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using System; -using System.IO; -using System.Linq; namespace Emby.Server.Implementations.Library.Resolvers { @@ -79,13 +77,6 @@ namespace Emby.Server.Implementations.Library.Resolvers return false; } - public override ResolverPriority Priority - { - get - { - // Behind special folder resolver - return ResolverPriority.Second; - } - } + public override ResolverPriority Priority => ResolverPriority.Second; } } diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index e3cce5f4b..78c1c6629 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Entities; using System; using System.IO; using System.Linq; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library.Resolvers diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs index e66c9f087..c295894d3 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs @@ -1,10 +1,10 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Playlists; using System; using System.IO; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Entities; using System.Linq; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Playlists; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.Library.Resolvers { diff --git a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs index 6a1f8ec6f..fa8c89e88 100644 --- a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs @@ -1,12 +1,10 @@ -using MediaBrowser.Controller; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Resolvers; using System; using System.IO; using System.Linq; - -using MediaBrowser.Controller.IO; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library.Resolvers @@ -26,10 +24,7 @@ namespace Emby.Server.Implementations.Library.Resolvers /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get { return ResolverPriority.First; } - } + public override ResolverPriority Priority => ResolverPriority.First; /// /// Resolves the specified args. diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index 7d1c4d65a..fed0904d1 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -1,7 +1,7 @@ -using System; +using System; +using System.Linq; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using System.Linq; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; @@ -27,7 +27,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV } var season = parent as Season; - // Just in case the user decided to nest episodes. + // Just in case the user decided to nest episodes. // Not officially supported but in some cases we can handle it. if (season == null) { @@ -36,8 +36,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV // If the parent is a Season or Series, then this is an Episode if the VideoResolver returns something // Also handle flat tv folders - if (season != null || - string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || + if (season != null || + string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || args.HasParent()) { var episode = ResolveVideo(args, false); diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 0fe42fa73..ce1386e91 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -1,10 +1,9 @@ -using System.Globalization; +using System.Globalization; +using Emby.Naming.TV; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Globalization; -using Emby.Naming.Common; -using Emby.Naming.TV; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.TV @@ -28,6 +27,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// Initializes a new instance of the class. /// /// The config. + /// The library manager. + /// The localization + /// The logger public SeasonResolver(IServerConfigurationManager config, ILibraryManager libraryManager, ILocalizationManager localization, ILogger logger) { _config = config; @@ -61,7 +63,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV if (!season.IndexNumber.HasValue || !seasonParserResult.IsSeasonFolder) { - var resolver = new Emby.Naming.TV.EpisodeResolver(namingOptions); + var resolver = new Naming.TV.EpisodeResolver(namingOptions); var folderName = System.IO.Path.GetFileName(path); var testPath = "\\\\test\\" + folderName; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 32e8b6120..8ef227689 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -1,20 +1,15 @@ -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Controller.Resolvers; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using Emby.Naming.Common; -using Emby.Naming.TV; using System; using System.Collections.Generic; using System.IO; -using System.Linq; - -using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.IO; +using Emby.Naming.TV; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.TV { @@ -38,13 +33,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// Gets the priority. /// /// The priority. - public override ResolverPriority Priority - { - get - { - return ResolverPriority.Second; - } - } + public override ResolverPriority Priority => ResolverPriority.Second; /// /// Resolves the specified args. @@ -118,7 +107,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - public static bool IsSeriesFolder(string path, + public static bool IsSeriesFolder( + string path, IEnumerable fileSystemChildren, IDirectoryService directoryService, IFileSystem fileSystem, @@ -146,7 +136,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) { - //logger.LogDebug("{0} is a series because of season folder {1}.", path, child.FullName); + logger.LogDebug("{Path} is a series because of season folder {Dir}.", path, child.FullName); return true; } } @@ -162,7 +152,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV var namingOptions = ((LibraryManager)libraryManager).GetNamingOptions(); - var episodeResolver = new Emby.Naming.TV.EpisodeResolver(namingOptions); + var episodeResolver = new Naming.TV.EpisodeResolver(namingOptions); bool? isNamed = null; bool? isOptimistic = null; @@ -172,7 +162,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV isOptimistic = false; } - var episodeInfo = episodeResolver.Resolve(fullName, false, isNamed, isOptimistic, null, false); + var episodeInfo = episodeResolver.Resolve(fullName, false, isNamed, isOptimistic, fillExtendedInfo: false); if (episodeInfo != null && episodeInfo.EpisodeNumber.HasValue) { return true; @@ -181,7 +171,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV } } - //logger.LogDebug("{0} is not a series folder.", path); + logger.LogDebug("{Path} is not a series folder.", path); return false; } @@ -190,12 +180,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// /// The path. /// true if [is place holder] [the specified path]; otherwise, false. - /// path + /// path private static bool IsVideoPlaceHolder(string path) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var extension = Path.GetExtension(path); @@ -236,7 +226,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// /// The item. /// The path. - private void SetProviderIdFromPath(Series item, string path) + private static void SetProviderIdFromPath(Series item, string path) { var justName = Path.GetFileName(path); diff --git a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs index 030ff88f7..60752a85d 100644 --- a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs @@ -1,12 +1,11 @@ -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library.Resolvers { public class GenericVideoResolver : BaseVideoResolver - where T : Video, new () + where T : Video, new() { public GenericVideoResolver(ILibraryManager libraryManager, IFileSystem fileSystem) : base(libraryManager, fileSystem) { diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 1212ba549..71638b197 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -1,17 +1,15 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Search; using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Extensions; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Search; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { @@ -64,7 +62,7 @@ namespace Emby.Server.Implementations.Library }; } - private void AddIfMissing(List list, string value) + private static void AddIfMissing(List list, string value) { if (!list.Contains(value, StringComparer.OrdinalIgnoreCase)) { @@ -78,14 +76,14 @@ namespace Emby.Server.Implementations.Library /// The query. /// The user. /// IEnumerable{SearchHintResult}. - /// searchTerm + /// searchTerm private List GetSearchHints(SearchQuery query, User user) { var searchTerm = query.SearchTerm; if (string.IsNullOrEmpty(searchTerm)) { - throw new ArgumentNullException("searchTerm"); + throw new ArgumentNullException(nameof(searchTerm)); } searchTerm = searchTerm.Trim().RemoveDiacritics(); diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 27ba32c0c..dfa1edaff 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -1,16 +1,16 @@ -using MediaBrowser.Controller.Configuration; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using MediaBrowser.Controller.Dto; -using System.Globalization; namespace Emby.Server.Implementations.Library { @@ -53,11 +53,11 @@ namespace Emby.Server.Implementations.Library { if (userData == null) { - throw new ArgumentNullException("userData"); + throw new ArgumentNullException(nameof(userData)); } if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } cancellationToken.ThrowIfCancellationRequested(); @@ -150,7 +150,7 @@ namespace Emby.Server.Implementations.Library /// Gets the internal key. /// /// System.String. - private string GetCacheKey(long internalUserId, Guid itemId) + private static string GetCacheKey(long internalUserId, Guid itemId) { return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N"); } @@ -193,12 +193,12 @@ namespace Emby.Server.Implementations.Library /// /// The data. /// DtoUserItemData. - /// + /// private UserItemDataDto GetUserItemDataDto(UserItemData data) { if (data == null) { - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); } return new UserItemDataDto @@ -226,7 +226,7 @@ namespace Emby.Server.Implementations.Library // If a position has been reported, and if we know the duration if (positionTicks > 0 && hasRuntime) { - var pctIn = Decimal.Divide(positionTicks, runtimeTicks) * 100; + var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100; // Don't track in very beginning if (pctIn < _config.Configuration.MinResumePct) diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index 679116fc0..d5bc3d332 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -1,22 +1,3 @@ -using MediaBrowser.Common.Events; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Connect; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.Users; using System; using System.Collections.Generic; using System.Globalization; @@ -25,13 +6,32 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Cryptography; -using MediaBrowser.Model.IO; +using MediaBrowser.Common.Events; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller; using MediaBrowser.Controller.Authentication; -using MediaBrowser.Controller.Security; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Plugins; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Security; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Connect; +using MediaBrowser.Model.Cryptography; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Events; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Users; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { @@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.Library /// Gets the users. /// /// The users. - public IEnumerable Users { get { return _users; } } + public IEnumerable Users => _users; private User[] _users; @@ -80,9 +80,20 @@ namespace Emby.Server.Implementations.Library private IAuthenticationProvider[] _authenticationProviders; private DefaultAuthenticationProvider _defaultAuthenticationProvider; - public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func imageProcessorFactory, Func dtoServiceFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ICryptoProvider cryptographyProvider) + public UserManager( + ILoggerFactory loggerFactory, + IServerConfigurationManager configurationManager, + IUserRepository userRepository, + IXmlSerializer xmlSerializer, + INetworkManager networkManager, + Func imageProcessorFactory, + Func dtoServiceFactory, + IServerApplicationHost appHost, + IJsonSerializer jsonSerializer, + IFileSystem fileSystem, + ICryptoProvider cryptographyProvider) { - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(UserManager)); UserRepository = userRepository; _xmlSerializer = xmlSerializer; _networkManager = networkManager; @@ -158,12 +169,12 @@ namespace Emby.Server.Implementations.Library /// /// The id. /// User. - /// + /// public User GetUserById(Guid id) { if (id.Equals(Guid.Empty)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } return Users.FirstOrDefault(u => u.Id == id); @@ -183,7 +194,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase)); @@ -222,7 +233,7 @@ namespace Emby.Server.Implementations.Library return true; } - private bool IsValidUsernameCharacter(char i) + private static bool IsValidUsernameCharacter(char i) { return !char.Equals(i, '<') && !char.Equals(i, '>'); } @@ -251,7 +262,7 @@ namespace Emby.Server.Implementations.Library { if (string.IsNullOrWhiteSpace(username)) { - throw new ArgumentNullException("username"); + throw new ArgumentNullException(nameof(username)); } var user = Users @@ -344,7 +355,7 @@ namespace Emby.Server.Implementations.Library return success ? user : null; } - private string GetAuthenticationProviderId(IAuthenticationProvider provider) + private static string GetAuthenticationProviderId(IAuthenticationProvider provider) { return provider.GetType().FullName; } @@ -526,7 +537,7 @@ namespace Emby.Server.Implementations.Library { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result; @@ -619,18 +630,18 @@ namespace Emby.Server.Implementations.Library /// The user. /// The new name. /// Task. - /// user - /// + /// user + /// public async Task RenameUser(User user, string newName) { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrEmpty(newName)) { - throw new ArgumentNullException("newName"); + throw new ArgumentNullException(nameof(newName)); } if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase))) @@ -652,13 +663,13 @@ namespace Emby.Server.Implementations.Library /// Updates the user. /// /// The user. - /// user - /// + /// user + /// public void UpdateUser(User user) { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id))) @@ -683,13 +694,13 @@ namespace Emby.Server.Implementations.Library /// /// The name. /// User. - /// name - /// + /// name + /// public async Task CreateUser(string name) { if (string.IsNullOrWhiteSpace(name)) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } if (!IsValidUsername(name)) @@ -731,13 +742,13 @@ namespace Emby.Server.Implementations.Library /// /// The user. /// Task. - /// user - /// + /// user + /// public async Task DeleteUser(User user) { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } var allUsers = Users.ToList(); @@ -804,7 +815,7 @@ namespace Emby.Server.Implementations.Library { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest) @@ -823,7 +834,7 @@ namespace Emby.Server.Implementations.Library { if (user == null) { - throw new ArgumentNullException("user"); + throw new ArgumentNullException(nameof(user)); } if (newPassword != null) @@ -833,7 +844,7 @@ namespace Emby.Server.Implementations.Library if (string.IsNullOrWhiteSpace(newPasswordHash)) { - throw new ArgumentNullException("newPasswordHash"); + throw new ArgumentNullException(nameof(newPasswordHash)); } user.EasyPassword = newPasswordHash; @@ -848,7 +859,7 @@ namespace Emby.Server.Implementations.Library /// /// The name. /// User. - private User InstantiateNewUser(string name) + private static User InstantiateNewUser(string name) { return new User { @@ -861,10 +872,7 @@ namespace Emby.Server.Implementations.Library }; } - private string PasswordResetFile - { - get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); } - } + private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); private string _lastPin; private PasswordPinCreationResult _lastPasswordPinCreationResult; @@ -888,7 +896,7 @@ namespace Emby.Server.Implementations.Library text.AppendLine("Use your web browser to visit:"); text.AppendLine(string.Empty); - text.AppendLine(localAddress + "/web/forgotpasswordpin.html"); + text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html"); text.AppendLine(string.Empty); text.AppendLine("Enter the following pin code:"); text.AppendLine(string.Empty); @@ -1047,7 +1055,7 @@ namespace Emby.Server.Implementations.Library } } - private UserPolicy GetDefaultPolicy(User user) + private static UserPolicy GetDefaultPolicy(User user) { return new UserPolicy { @@ -1109,12 +1117,12 @@ namespace Emby.Server.Implementations.Library } } - private string GetPolicyFilePath(User user) + private static string GetPolicyFilePath(User user) { return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml"); } - private string GetConfigurationFilePath(User user) + private static string GetConfigurationFilePath(User user) { return Path.Combine(user.ConfigurationDirectoryPath, "config.xml"); } diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index aae5751de..9fa859bde 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -1,21 +1,19 @@ -using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Channels; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Library; -using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; using System.Linq; using System.Threading; -using System.Threading.Tasks; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Channels; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Library; +using MediaBrowser.Model.Querying; namespace Emby.Server.Implementations.Library { @@ -242,7 +240,7 @@ namespace Emby.Server.Implementations.Library { return _channelManager.GetLatestChannelItemsInternal(new InternalItemsQuery(user) { - ChannelIds = new [] { parentId }, + ChannelIds = new[] { parentId }, IsPlayed = request.IsPlayed, StartIndex = request.StartIndex, Limit = request.Limit, @@ -282,7 +280,7 @@ namespace Emby.Server.Implementations.Library if (includeItemTypes.Length == 0) { - // Handle situations with the grouping setting, e.g. movies showing up in tv, etc. + // Handle situations with the grouping setting, e.g. movies showing up in tv, etc. // Thanks to mixed content libraries included in the UserView var hasCollectionType = parents.OfType().ToArray(); if (hasCollectionType.Length > 0) diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs index eee66c8ac..27261d449 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs @@ -1,9 +1,9 @@ -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs index 1686dc23c..294348660 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs @@ -1,16 +1,12 @@ -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Extensions; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { @@ -94,7 +90,7 @@ namespace Emby.Server.Implementations.Library.Validators { continue; } - + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs index ea1f2e552..2b067951d 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs @@ -1,9 +1,9 @@ -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs index 070777475..f5ffa1e45 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs @@ -1,11 +1,9 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs index 4f4133340..056807300 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs @@ -1,7 +1,7 @@ -using MediaBrowser.Controller.Library; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using Microsoft.Extensions.Logging; diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs index 775cde299..f8459c61f 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs @@ -1,12 +1,9 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs index edc6f3ad6..d7ab92d30 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs @@ -1,9 +1,9 @@ -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs index b5ed1c0e6..710e5d043 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs @@ -1,12 +1,9 @@ -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index 50c7cfbc6..0ea543ba0 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -1,12 +1,12 @@ -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs index 45747dda1..4aa5c7e72 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs @@ -1,9 +1,9 @@ -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs index 1a5ebac54..da4645a11 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs @@ -1,11 +1,10 @@ -using MediaBrowser.Controller.Library; -using Microsoft.Extensions.Logging; using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 327b0181a..7d7ef21e3 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -1,13 +1,10 @@ -using System; -using System.IO; +using System; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.IO; - using MediaBrowser.Common.Net; -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 59f9fe86f..64e5affd7 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; @@ -8,36 +8,36 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; +using Emby.Server.Implementations.Library; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; +using MediaBrowser.Common.Progress; +using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.IO; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Progress; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Diagnostics; -using MediaBrowser.Model.System; -using MediaBrowser.Model.Threading; using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Providers; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Reflection; -using MediaBrowser.Model.Providers; -using MediaBrowser.Model.MediaInfo; -using Emby.Server.Implementations.Library; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.System; +using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -75,7 +75,23 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly IStreamHelper _streamHelper; - public EmbyTV(IServerApplicationHost appHost, IStreamHelper streamHelper, IMediaSourceManager mediaSourceManager, IAssemblyInfo assemblyInfo, ILogger logger, IJsonSerializer jsonSerializer, IPowerManagement powerManagement, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IMediaEncoder mediaEncoder, ITimerFactory timerFactory, IProcessFactory processFactory, ISystemEvents systemEvents) + public EmbyTV(IServerApplicationHost appHost, + IStreamHelper streamHelper, + IMediaSourceManager mediaSourceManager, + IAssemblyInfo assemblyInfo, + ILogger logger, + IJsonSerializer jsonSerializer, + IHttpClient httpClient, + IServerConfigurationManager config, + ILiveTvManager liveTvManager, + IFileSystem fileSystem, + ILibraryManager libraryManager, + ILibraryMonitor libraryMonitor, + IProviderManager providerManager, + IMediaEncoder mediaEncoder, + ITimerFactory timerFactory, + IProcessFactory processFactory, + ISystemEvents systemEvents) { Current = this; @@ -97,7 +113,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _streamHelper = streamHelper; _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers")); - _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory, powerManagement); + _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory); _timerProvider.TimerFired += _timerProvider_TimerFired; _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated; @@ -238,27 +254,15 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (requiresRefresh) { - await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); + await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); } } - public string Name - { - get { return "Emby"; } - } + public string Name => "Emby"; - public string DataPath - { - get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); } - } + public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); - private string DefaultRecordingPath - { - get - { - return Path.Combine(DataPath, "recordings"); - } - } + private string DefaultRecordingPath => Path.Combine(DataPath, "recordings"); private string RecordingPath { @@ -272,10 +276,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - public string HomePageUrl - { - get { return "https://github.com/jellyfin/jellyfin"; } - } + public string HomePageUrl => "https://github.com/jellyfin/jellyfin"; public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress progress) { @@ -394,8 +395,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private async Task GetEpgChannels(IListingsProvider provider, ListingsProviderInfo info, bool enableCache, CancellationToken cancellationToken) { - EpgChannelData result; - if (!enableCache || !_epgChannels.TryGetValue(info.Id, out result)) + if (!enableCache || !_epgChannels.TryGetValue(info.Id, out var result)) { var channels = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false); @@ -451,18 +451,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public ChannelInfo GetChannelByNumber(string number) { - ChannelInfo result = null; - - ChannelsByNumber.TryGetValue(number, out result); + ChannelsByNumber.TryGetValue(number, out var result); return result; } public ChannelInfo GetChannelByName(string name) { - ChannelInfo result = null; - - ChannelsByName.TryGetValue(name, out result); + ChannelsByName.TryGetValue(name, out var result); return result; } @@ -475,7 +471,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels); } - private string GetMappedChannel(string channelId, NameValuePair[] mappings) + private static string GetMappedChannel(string channelId, NameValuePair[] mappings) { foreach (NameValuePair mapping in mappings) { @@ -651,9 +647,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV TimerCancelled(this, new GenericEventArgs(timerId)); } } - ActiveRecordingInfo activeRecordingInfo; - if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo)) + if (_activeRecordings.TryGetValue(timerId, out var activeRecordingInfo)) { activeRecordingInfo.Timer = timer; activeRecordingInfo.CancellationTokenSource.Cancel(); @@ -820,8 +815,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } // Only update if not currently active - ActiveRecordingInfo activeRecordingInfo; - if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo)) + if (!_activeRecordings.TryGetValue(updatedTimer.Id, out var activeRecordingInfo)) { existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds; existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds; @@ -834,7 +828,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return Task.CompletedTask; } - private void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer) + private static void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer) { // Update the program info but retain the status existingTimer.ChannelId = updatedTimer.ChannelId; @@ -863,9 +857,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public string GetActiveRecordingPath(string id) { - ActiveRecordingInfo info; - - if (_activeRecordings.TryGetValue(id, out info)) + if (_activeRecordings.TryGetValue(id, out var info)) { return info.Path; } @@ -964,7 +956,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (string.IsNullOrWhiteSpace(tunerHostId)) { - throw new ArgumentNullException("tunerHostId"); + throw new ArgumentNullException(nameof(tunerHostId)); } return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase); @@ -1039,7 +1031,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _logger.LogInformation("Streaming Channel " + channelId); - var result = string.IsNullOrEmpty(streamId) ? + var result = string.IsNullOrEmpty(streamId) ? null : currentLiveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase)); @@ -1098,7 +1090,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (string.IsNullOrWhiteSpace(channelId)) { - throw new ArgumentNullException("channelId"); + throw new ArgumentNullException(nameof(channelId)); } foreach (var hostInstance in _liveTvManager.TunerHosts) @@ -1182,14 +1174,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return; } - var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false); - if (!registration.IsValid) - { - _logger.LogWarning("Emby Premiere required to use Emby DVR."); - OnTimerOutOfDate(timer); - return; - } - var activeRecordingInfo = new ActiveRecordingInfo { CancellationTokenSource = new CancellationTokenSource(), @@ -1326,7 +1310,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (timer == null) { - throw new ArgumentNullException("timer"); + throw new ArgumentNullException(nameof(timer)); } LiveTvProgram programInfo = null; @@ -1439,8 +1423,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV TriggerRefresh(recordPath); _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false); - ActiveRecordingInfo removed; - _activeRecordings.TryRemove(timer.Id, out removed); + _activeRecordings.TryRemove(timer.Id, out var removed); if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) { @@ -1779,7 +1762,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - private string GetPostProcessArguments(string path, string arguments) + private static string GetPostProcessArguments(string path, string arguments) { return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase); } @@ -2001,11 +1984,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV CloseOutput = false }; - using (XmlWriter writer = XmlWriter.Create(stream, settings)) + using (var writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(true); writer.WriteStartElement("tvshow"); - string id; if (timer.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out id)) { @@ -2068,7 +2050,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var isSeriesEpisode = timer.IsProgramSeries; - using (XmlWriter writer = XmlWriter.Create(stream, settings)) + using (var writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(true); @@ -2378,46 +2360,61 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var allTimers = GetTimersForSeries(seriesTimer) .ToList(); - var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false); var enabledTimersForSeries = new List(); - - if (registration.IsValid) + foreach (var timer in allTimers) { - foreach (var timer in allTimers) + var existingTimer = _timerProvider.GetTimer(timer.Id); + + if (existingTimer == null) { - var existingTimer = _timerProvider.GetTimer(timer.Id); + existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId) + ? null + : _timerProvider.GetTimerByProgramId(timer.ProgramId); + } - if (existingTimer == null) + if (existingTimer == null) + { + if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer)) { - existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId) - ? null - : _timerProvider.GetTimerByProgramId(timer.ProgramId); - } - - if (existingTimer == null) - { - if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer)) - { - timer.Status = RecordingStatus.Cancelled; - } - else - { - enabledTimersForSeries.Add(timer); - } - _timerProvider.Add(timer); - - if (TimerCreated != null) - { - TimerCreated(this, new GenericEventArgs(timer)); - } + timer.Status = RecordingStatus.Cancelled; } else + { + 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 _)) + { + UpdateExistingTimerWithNewMetadata(existingTimer, timer); + + // Needed by ShouldCancelTimerForSeriesTimer + timer.IsManual = existingTimer.IsManual; + + if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer)) + { + existingTimer.Status = RecordingStatus.Cancelled; + } + else if (!existingTimer.IsManual) + { + existingTimer.Status = RecordingStatus.New; + } + + if (existingTimer.Status != RecordingStatus.Cancelled) + { + enabledTimersForSeries.Add(existingTimer); + } + + if (updateTimerSettings) { // 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 - ActiveRecordingInfo activeRecordingInfo; - if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo)) + if (!_activeRecordings.TryGetValue(timer.Id, out var activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo)) { UpdateExistingTimerWithNewMetadata(existingTimer, timer); @@ -2452,6 +2449,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _timerProvider.Update(existingTimer); } } + + existingTimer.SeriesTimerId = seriesTimer.Id; + _timerProvider.Update(existingTimer); } } @@ -2485,7 +2485,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (seriesTimer == null) { - throw new ArgumentNullException("seriesTimer"); + throw new ArgumentNullException(nameof(seriesTimer)); } var query = new InternalItemsQuery @@ -2520,9 +2520,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (string.IsNullOrWhiteSpace(channelId) && !parent.ChannelId.Equals(Guid.Empty)) { - LiveTvChannel channel; - - if (!tempChannelCache.TryGetValue(parent.ChannelId, out channel)) + if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel)) { channel = _libraryManager.GetItemList(new InternalItemsQuery { @@ -2581,9 +2579,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (!programInfo.ChannelId.Equals(Guid.Empty)) { - LiveTvChannel channel; - - if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out channel)) + if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel)) { channel = _libraryManager.GetItemList(new InternalItemsQuery { @@ -2781,15 +2777,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase)); - if (configuredDevice != null) + if (configuredDevice != null && !string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase)) { - if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase)) - { - _logger.LogInformation("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); + _logger.LogInformation("Tuner url has changed from {PreviousUrl} to {NewUrl}", configuredDevice.Url, device.Url); - configuredDevice.Url = device.Url; - await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false); - } + configuredDevice.Url = device.Url; + await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 4ea83b7ac..c09ee9348 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -1,27 +1,25 @@ -using System; +using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.IO; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Controller.Library; +using MediaBrowser.Model.IO; using MediaBrowser.Model.Reflection; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -55,14 +53,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _assemblyInfo = assemblyInfo; } - private bool CopySubtitles - { - get - { - return false; - //return string.Equals(OutputFormat, "mkv", StringComparison.OrdinalIgnoreCase); - } - } + private static bool CopySubtitles => false; public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile) { @@ -214,19 +205,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var outputParam = string.Empty; - var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"", - inputTempFile, - targetFile, - videoArgs, - GetAudioArgs(mediaSource), - subtitleArgs, - durationParam, + var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"", + inputTempFile, + targetFile, + videoArgs, + GetAudioArgs(mediaSource), + subtitleArgs, + durationParam, outputParam); return inputModifier + " " + commandLineArgs; } - private string GetAudioArgs(MediaSourceInfo mediaSource) + private static string GetAudioArgs(MediaSourceInfo mediaSource) { var mediaStreams = mediaSource.MediaStreams ?? new List(); var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty; @@ -242,7 +233,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV //return "-codec:a:0 aac -strict experimental -ab 320000"; } - private bool EncodeVideo(MediaSourceInfo mediaSource) + private static bool EncodeVideo(MediaSourceInfo mediaSource) { return false; } @@ -383,6 +374,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (ObjectDisposedException) { + // TODO Investigate and properly fix. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux } catch (Exception ex) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs index cc9e80a82..982a54b68 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs @@ -1,4 +1,3 @@ -using System; using MediaBrowser.Controller.Plugins; namespace Emby.Server.Implementations.LiveTv.EmbyTV diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs index e639a312c..6eced3050 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 9f179dc2c..1b8287ed1 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,12 +1,10 @@ -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; - -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -68,7 +66,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (newList == null) { - throw new ArgumentNullException("newList"); + throw new ArgumentNullException(nameof(newList)); } var file = _dataPath + ".json"; @@ -85,7 +83,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } var list = GetAll().ToList(); @@ -106,7 +104,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } var list = GetAll().ToList(); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs index e694a8281..ded3c7607 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs @@ -1,6 +1,6 @@ -using MediaBrowser.Controller.LiveTv; using System; using System.Globalization; +using MediaBrowser.Controller.LiveTv; namespace Emby.Server.Implementations.LiveTv.EmbyTV { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 620ba7650..d2ad65a1e 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -1,8 +1,8 @@ -using MediaBrowser.Controller.LiveTv; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using System; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index 76a044c02..7f67d70a9 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,15 +1,14 @@ -using System; +using System; using System.Collections.Concurrent; using System.Globalization; using System.Linq; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Threading; -using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -20,14 +19,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public event EventHandler> TimerFired; private readonly ITimerFactory _timerFactory; - private readonly IPowerManagement _powerManagement; - public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1, ITimerFactory timerFactory, IPowerManagement powerManagement) + public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1, ITimerFactory timerFactory) : base(fileSystem, jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)) { _logger = logger1; _timerFactory = timerFactory; - _powerManagement = powerManagement; } public void RestartTimers() @@ -36,7 +33,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var item in GetAll().ToList()) { - AddOrUpdateSystemTimer(item, false); + AddOrUpdateSystemTimer(item); } } @@ -59,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public override void Update(TimerInfo item) { base.Update(item); - AddOrUpdateSystemTimer(item, false); + AddOrUpdateSystemTimer(item); } public void AddOrUpdate(TimerInfo item, bool resetTimer) @@ -90,10 +87,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } base.Add(item); - AddOrUpdateSystemTimer(item, true); + AddOrUpdateSystemTimer(item); } - private bool ShouldStartTimer(TimerInfo item) + private static bool ShouldStartTimer(TimerInfo item) { if (item.Status == RecordingStatus.Completed || item.Status == RecordingStatus.Cancelled) @@ -104,7 +101,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return true; } - private void AddOrUpdateSystemTimer(TimerInfo item, bool scheduleSystemWakeTimer) + private void AddOrUpdateSystemTimer(TimerInfo item) { StopTimer(item); @@ -124,23 +121,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var dueTime = startDate - now; StartTimer(item, dueTime); - - if (scheduleSystemWakeTimer && dueTime >= TimeSpan.FromMinutes(15)) - { - ScheduleSystemWakeTimer(startDate, item.Name); - } - } - - private void ScheduleSystemWakeTimer(DateTime startDate, string displayName) - { - try - { - _powerManagement.ScheduleWake(startDate.AddMinutes(-5), displayName); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error scheduling wake timer"); - } } private void StartTimer(TimerInfo item, TimeSpan dueTime) @@ -160,8 +140,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void StopTimer(TimerInfo item) { - ITimer timer; - if (_timers.TryRemove(item.Id, out timer)) + if (_timers.TryRemove(item.Id, out var timer)) { timer.Dispose(); } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index e8ffd0caa..0bbffb824 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -1,22 +1,22 @@ -using System.Net; -using MediaBrowser.Common; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Common; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Net; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.Listings { @@ -38,14 +38,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings _appHost = appHost; } - private string UserAgent - { - get { return "Emby/" + _appHost.ApplicationVersion; } - } + private string UserAgent => _appHost.ApplicationUserAgent; - private List GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc) + private static List GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc) { - List dates = new List(); + var dates = new List(); var start = new List { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date; var end = new List { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date; @@ -63,7 +60,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { if (string.IsNullOrEmpty(channelId)) { - throw new ArgumentNullException("channelId"); + throw new ArgumentNullException(nameof(channelId)); } // Normalize incoming input @@ -107,7 +104,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestHeaders["token"] = token; using (var response = await Post(httpOptions, true, info).ConfigureAwait(false)) - using (StreamReader reader = new StreamReader(response.Content)) + using (var reader = new StreamReader(response.Content)) { var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync>(response.Content).ConfigureAwait(false); _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); @@ -128,7 +125,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]"; using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false)) - using (StreamReader innerReader = new StreamReader(innerResponse.Content)) + using (var innerReader = new StreamReader(innerResponse.Content)) { var programDetails = await _jsonSerializer.DeserializeFromStreamAsync>(innerResponse.Content).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); @@ -139,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); - List programsInfo = new List(); + var programsInfo = new List(); foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs)) { //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID + @@ -189,7 +186,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - private int GetSizeOrder(ScheduleDirect.ImageData image) + private static int GetSizeOrder(ScheduleDirect.ImageData image) { if (!string.IsNullOrWhiteSpace(image.height)) { @@ -202,7 +199,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return 0; } - private string GetChannelNumber(ScheduleDirect.Map map) + private static string GetChannelNumber(ScheduleDirect.Map map) { var channelNumber = map.logicalChannelNumber; @@ -218,16 +215,16 @@ namespace Emby.Server.Implementations.LiveTv.Listings return channelNumber.TrimStart('0'); } - private bool IsMovie(ScheduleDirect.ProgramDetails programInfo) + private static bool IsMovie(ScheduleDirect.ProgramDetails programInfo) { return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase); } private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details) { - DateTime startAt = GetDate(programInfo.airDateTime); - DateTime endAt = startAt.AddSeconds(programInfo.duration); - ProgramAudio audioType = ProgramAudio.Stereo; + var startAt = GetDate(programInfo.airDateTime); + var endAt = startAt.AddSeconds(programInfo.duration); + var audioType = ProgramAudio.Stereo; var programId = programInfo.programID ?? string.Empty; @@ -390,7 +387,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return info; } - private DateTime GetDate(string value) + private static DateTime GetDate(string value) { var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture); @@ -429,7 +426,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - private double GetAspectRatio(ScheduleDirect.ImageData i) + private static double GetAspectRatio(ScheduleDirect.ImageData i) { int width = 0; int height = 0; @@ -664,7 +661,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);; + options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); return await Post(options, false, providerInfo).ConfigureAwait(false); } @@ -765,16 +762,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - public string Name - { - get { return "Schedules Direct"; } - } + public string Name => "Schedules Direct"; public static string TypeName = "SchedulesDirect"; - public string Type - { - get { return TypeName; } - } + public string Type => TypeName; private async Task HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken) { @@ -951,7 +942,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return null; } - private string NormalizeName(string value) + private static string NormalizeName(string value) { return value.Replace(" ", string.Empty).Replace("-", string.Empty); } diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 4d7c7fef4..e7a3d748d 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -36,15 +36,9 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings _zipClient = zipClient; } - public string Name - { - get { return "XmlTV"; } - } + public string Name => "XmlTV"; - public string Type - { - get { return "xmltv"; } - } + public string Type => "xmltv"; private string GetLanguage(ListingsProviderInfo info) { @@ -78,7 +72,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { CancellationToken = cancellationToken, Url = path, - Progress = new SimpleProgress(), + Progress = new SimpleProgress(), DecompressionMethod = CompressionMethod.Gzip, // It's going to come back gzipped regardless of this value @@ -164,7 +158,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { if (string.IsNullOrWhiteSpace(channelId)) { - throw new ArgumentNullException("channelId"); + throw new ArgumentNullException(nameof(channelId)); } /* @@ -187,7 +181,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings .Select(p => GetProgramInfo(p, info)); } - private ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) + private static ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) { string episodeTitle = program.Episode?.Title; @@ -210,9 +204,9 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), - ImageUrl = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null, - HasImage = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source), - OfficialRating = program.Rating != null && !String.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null, + ImageUrl = program.Icon != null && !string.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null, + HasImage = program.Icon != null && !string.IsNullOrEmpty(program.Icon.Source), + OfficialRating = program.Rating != null && !string.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null, CommunityRating = program.StarRating, SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N") }; @@ -246,7 +240,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings } // Construct an id from the channel and start date - programInfo.Id = String.Format("{0}_{1:O}", program.ChannelId, program.StartDate); + programInfo.Id = string.Format("{0}_{1:O}", program.ChannelId, program.StartDate); if (programInfo.IsMovie) { @@ -287,14 +281,14 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); _logger.LogDebug("Opening XmlTvReader for {path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); - IEnumerable results = reader.GetChannels(); + var results = reader.GetChannels(); // Should this method be async? return results.Select(c => new ChannelInfo { Id = c.Id, Name = c.DisplayName, - ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null, + ImageUrl = c.Icon != null && !string.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null, Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number }).ToList(); diff --git a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs index 205a767eb..f9b274acb 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs @@ -1,6 +1,6 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.LiveTv; using System.Collections.Generic; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.LiveTv; namespace Emby.Server.Implementations.LiveTv { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index 6fe578715..724e8afdf 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -1,21 +1,19 @@ -using MediaBrowser.Common; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Extensions; -using System.Collections.Generic; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv { @@ -28,11 +26,16 @@ namespace Emby.Server.Implementations.LiveTv private readonly IApplicationHost _appHost; private readonly ILibraryManager _libraryManager; - public LiveTvDtoService(IDtoService dtoService, IImageProcessor imageProcessor, ILogger logger, IApplicationHost appHost, ILibraryManager libraryManager) + public LiveTvDtoService( + IDtoService dtoService, + IImageProcessor imageProcessor, + ILoggerFactory loggerFactory, + IApplicationHost appHost, + ILibraryManager libraryManager) { _dtoService = dtoService; _imageProcessor = imageProcessor; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(LiveTvDtoService)); _appHost = appHost; _libraryManager = libraryManager; } @@ -321,6 +324,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogDebug(ex, "GetImageCacheTag raised an exception in LiveTvDtoService.FillImages."); } } @@ -331,10 +335,10 @@ namespace Emby.Server.Implementations.LiveTv { try { - dto.ParentBackdropImageTags = new string[] - { - _imageProcessor.GetImageCacheTag(program, image) - }; + dto.ParentBackdropImageTags = new[] + { + _imageProcessor.GetImageCacheTag(program, image) + }; dto.ParentBackdropItemId = program.Id.ToString("N"); } catch (Exception ex) diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index b597a935a..575cb1c77 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,10 +1,21 @@ -using MediaBrowser.Common.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Emby.Server.Implementations.Library; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Persistence; @@ -12,28 +23,15 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Common.Security; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Tasks; -using Emby.Server.Implementations.LiveTv.Listings; -using MediaBrowser.Controller.Channels; -using Emby.Server.Implementations.Library; -using MediaBrowser.Controller; -using MediaBrowser.Common.Net; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv { @@ -51,7 +49,6 @@ namespace Emby.Server.Implementations.LiveTv private readonly ITaskManager _taskManager; private readonly IJsonSerializer _jsonSerializer; private readonly IProviderManager _providerManager; - private readonly ISecurityManager _security; private readonly Func _channelManager; private readonly IDtoService _dtoService; @@ -75,14 +72,25 @@ namespace Emby.Server.Implementations.LiveTv return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id); } - private IServerApplicationHost _appHost; - private IHttpClient _httpClient; - - public LiveTvManager(IServerApplicationHost appHost, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager, IFileSystem fileSystem, ISecurityManager security, Func channelManager) + public LiveTvManager( + IServerApplicationHost appHost, + IServerConfigurationManager config, + ILoggerFactory loggerFactory, + IItemRepository itemRepo, + IImageProcessor imageProcessor, + IUserDataManager userDataManager, + IDtoService dtoService, + IUserManager userManager, + ILibraryManager libraryManager, + ITaskManager taskManager, + ILocalizationManager localization, + IJsonSerializer jsonSerializer, + IProviderManager providerManager, + IFileSystem fileSystem, + Func channelManager) { - _appHost = appHost; _config = config; - _logger = logger; + _logger = loggerFactory.CreateLogger(nameof(LiveTvManager)); _itemRepo = itemRepo; _userManager = userManager; _libraryManager = libraryManager; @@ -91,23 +99,18 @@ namespace Emby.Server.Implementations.LiveTv _jsonSerializer = jsonSerializer; _providerManager = providerManager; _fileSystem = fileSystem; - _security = security; _dtoService = dtoService; _userDataManager = userDataManager; _channelManager = channelManager; - _httpClient = httpClient; - _tvDtoService = new LiveTvDtoService(dtoService, imageProcessor, logger, appHost, _libraryManager); + _tvDtoService = new LiveTvDtoService(dtoService, imageProcessor, loggerFactory, appHost, _libraryManager); } /// /// Gets the services. /// /// The services. - public IReadOnlyList Services - { - get { return _services; } - } + public IReadOnlyList Services => _services; private LiveTvOptions GetConfiguration() { @@ -167,15 +170,9 @@ namespace Emby.Server.Implementations.LiveTv }); } - public ITunerHost[] TunerHosts - { - get { return _tunerHosts; } - } + public ITunerHost[] TunerHosts => _tunerHosts; - public IListingsProvider[] ListingProviders - { - get { return _listingProviders; } - } + public IListingsProvider[] ListingProviders => _listingProviders; public List GetTunerHostTypes() { @@ -251,7 +248,7 @@ namespace Emby.Server.Implementations.LiveTv var channel = (LiveTvChannel)_libraryManager.GetItemById(id); bool isVideo = channel.ChannelType == ChannelType.TV; - ILiveTvService service = GetService(channel); + var service = GetService(channel); _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); MediaSourceInfo info; @@ -323,7 +320,7 @@ namespace Emby.Server.Implementations.LiveTv return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)); } - private void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo) + private static void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo) { // Not all of the plugins are setting this mediaSource.IsInfiniteStream = true; @@ -537,8 +534,7 @@ namespace Emby.Server.Implementations.LiveTv var isNew = false; var forceUpdate = false; - LiveTvProgram item; - if (!allExistingPrograms.TryGetValue(id, out item)) + if (!allExistingPrograms.TryGetValue(id, out LiveTvProgram item)) { isNew = true; item = new LiveTvProgram @@ -901,7 +897,7 @@ namespace Emby.Server.Implementations.LiveTv var programList = _libraryManager.QueryItems(internalQuery).Items; var totalCount = programList.Length; - IOrderedEnumerable orderedPrograms = programList.Cast().OrderBy(i => i.StartDate.Date); + var orderedPrograms = programList.Cast().OrderBy(i => i.StartDate.Date); if (query.IsAiring ?? false) { @@ -917,10 +913,10 @@ namespace Emby.Server.Implementations.LiveTv } return new QueryResult - { - Items = programs.ToArray(), - TotalRecordCount = totalCount - }; + { + Items = programs.ToArray(), + TotalRecordCount = totalCount + }; } public QueryResult GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken) @@ -935,10 +931,10 @@ namespace Emby.Server.Implementations.LiveTv var internalResult = GetRecommendedProgramsInternal(query, options, cancellationToken); return new QueryResult - { - Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User), - TotalRecordCount = internalResult.TotalRecordCount - }; + { + Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User), + TotalRecordCount = internalResult.TotalRecordCount + }; } private int GetRecommendationScore(LiveTvProgram program, User user, bool factorChannelWatchCount) @@ -1056,7 +1052,7 @@ namespace Emby.Server.Implementations.LiveTv var numComplete = 0; double progressPerService = _services.Length == 0 ? 0 - : 1 / _services.Length; + : 1.0 / _services.Length; var newChannelIdList = new List(); var newProgramIdList = new List(); @@ -1262,7 +1258,7 @@ namespace Emby.Server.Implementations.LiveTv } numComplete++; - double percent = numComplete / allChannelsList.Count; + double percent = numComplete / (double)allChannelsList.Count; progress.Report(85 * percent + 15); } @@ -1307,7 +1303,7 @@ namespace Emby.Server.Implementations.LiveTv } numComplete++; - double percent = numComplete / list.Count; + double percent = numComplete / (double)list.Count; progress.Report(100 * percent); } @@ -1418,6 +1414,7 @@ namespace Emby.Server.Implementations.LiveTv if (query.IsInProgress ?? false) { + //TODO Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues. result.Items = result .Items .OfType