aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/IO/ManagedFileSystem.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Emby.Server.Implementations/IO/ManagedFileSystem.cs')
-rw-r--r--Emby.Server.Implementations/IO/ManagedFileSystem.cs229
1 files changed, 106 insertions, 123 deletions
diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
index 64d802457..0ba4a488b 100644
--- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs
+++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
@@ -1,17 +1,12 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Runtime.InteropServices;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
using Microsoft.Extensions.Logging;
-using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
namespace Emby.Server.Implementations.IO
{
@@ -20,20 +15,34 @@ namespace Emby.Server.Implementations.IO
/// </summary>
public class ManagedFileSystem : IFileSystem
{
- protected ILogger<ManagedFileSystem> Logger;
+ private readonly ILogger<ManagedFileSystem> _logger;
private readonly List<IShortcutHandler> _shortcutHandlers = new List<IShortcutHandler>();
private readonly string _tempPath;
- private static readonly bool _isEnvironmentCaseInsensitive = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
+ private static readonly bool _isEnvironmentCaseInsensitive = OperatingSystem.IsWindows();
+ private static readonly char[] _invalidPathCharacters =
+ {
+ '\"', '<', '>', '|', '\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, ':', '*', '?', '\\', '/'
+ };
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ManagedFileSystem"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger"/> instance to use.</param>
+ /// <param name="applicationPaths">The <see cref="IApplicationPaths"/> instance to use.</param>
public ManagedFileSystem(
ILogger<ManagedFileSystem> logger,
IApplicationPaths applicationPaths)
{
- Logger = logger;
+ _logger = logger;
_tempPath = applicationPaths.TempDirectory;
}
+ /// <inheritdoc />
public virtual void AddShortcutHandler(IShortcutHandler handler)
{
_shortcutHandlers.Add(handler);
@@ -44,13 +53,10 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
- /// <exception cref="ArgumentNullException">filename</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
public virtual bool IsShortcut(string filename)
{
- if (string.IsNullOrEmpty(filename))
- {
- throw new ArgumentNullException(nameof(filename));
- }
+ ArgumentException.ThrowIfNullOrEmpty(filename);
var extension = Path.GetExtension(filename);
return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
@@ -61,13 +67,10 @@ namespace Emby.Server.Implementations.IO
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
- /// <exception cref="ArgumentNullException">filename</exception>
+ /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
public virtual string? ResolveShortcut(string filename)
{
- if (string.IsNullOrEmpty(filename))
- {
- throw new ArgumentNullException(nameof(filename));
- }
+ ArgumentException.ThrowIfNullOrEmpty(filename);
var extension = Path.GetExtension(filename);
var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
@@ -75,6 +78,7 @@ namespace Emby.Server.Implementations.IO
return handler?.Resolve(filename);
}
+ /// <inheritdoc />
public virtual string MakeAbsolutePath(string folderPath, string filePath)
{
// path is actually a stream
@@ -134,20 +138,13 @@ namespace Emby.Server.Implementations.IO
/// <exception cref="ArgumentNullException">The shortcutPath or target is null.</exception>
public virtual void CreateShortcut(string shortcutPath, string target)
{
- if (string.IsNullOrEmpty(shortcutPath))
- {
- throw new ArgumentNullException(nameof(shortcutPath));
- }
-
- if (string.IsNullOrEmpty(target))
- {
- throw new ArgumentNullException(nameof(target));
- }
+ ArgumentException.ThrowIfNullOrEmpty(shortcutPath);
+ ArgumentException.ThrowIfNullOrEmpty(target);
var extension = Path.GetExtension(shortcutPath);
var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
- if (handler != null)
+ if (handler is not null)
{
handler.Create(shortcutPath, target);
}
@@ -236,9 +233,9 @@ namespace Emby.Server.Implementations.IO
result.IsDirectory = info is DirectoryInfo || (info.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
// if (!result.IsDirectory)
- //{
+ // {
// result.IsHidden = (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
- //}
+ // }
if (info is FileInfo fileInfo)
{
@@ -249,17 +246,21 @@ namespace Emby.Server.Implementations.IO
{
try
{
- using (Stream thisFileStream = File.OpenRead(fileInfo.FullName))
+ using (var fileHandle = File.OpenHandle(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
- result.Length = thisFileStream.Length;
+ result.Length = RandomAccess.GetLength(fileHandle);
}
}
catch (FileNotFoundException ex)
{
// Dangling symlinks cannot be detected before opening the file unfortunately...
- Logger.LogError(ex, "Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", fileInfo.FullName);
+ _logger.LogError(ex, "Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", fileInfo.FullName);
result.Exists = false;
}
+ catch (UnauthorizedAccessException ex)
+ {
+ _logger.LogError(ex, "Reading the file at {Path} failed due to a permissions exception.", fileInfo.FullName);
+ }
}
}
@@ -274,25 +275,6 @@ namespace Emby.Server.Implementations.IO
return result;
}
- private static ExtendedFileSystemInfo GetExtendedFileSystemInfo(string path)
- {
- var result = new ExtendedFileSystemInfo();
-
- var info = new FileInfo(path);
-
- if (info.Exists)
- {
- result.Exists = true;
-
- var attributes = info.Attributes;
-
- result.IsHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
- result.IsReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
- }
-
- return result;
- }
-
/// <summary>
/// Takes a filename and removes invalid characters.
/// </summary>
@@ -301,8 +283,7 @@ namespace Emby.Server.Implementations.IO
/// <exception cref="ArgumentNullException">The filename is null.</exception>
public string GetValidFilename(string filename)
{
- var invalid = Path.GetInvalidFileNameChars();
- var first = filename.IndexOfAny(invalid);
+ var first = filename.IndexOfAny(_invalidPathCharacters);
if (first == -1)
{
// Fast path for clean strings
@@ -311,7 +292,7 @@ namespace Emby.Server.Implementations.IO
return string.Create(
filename.Length,
- (filename, invalid, first),
+ (filename, _invalidPathCharacters, first),
(chars, state) =>
{
state.filename.AsSpan().CopyTo(chars);
@@ -319,7 +300,7 @@ namespace Emby.Server.Implementations.IO
chars[state.first++] = ' ';
var len = chars.Length;
- foreach (var c in state.invalid)
+ foreach (var c in state._invalidPathCharacters)
{
for (int i = state.first; i < len; i++)
{
@@ -346,7 +327,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
+ _logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -361,11 +342,13 @@ namespace Emby.Server.Implementations.IO
return GetCreationTimeUtc(GetFileSystemInfo(path));
}
+ /// <inheritdoc />
public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info)
{
return info.CreationTimeUtc;
}
+ /// <inheritdoc />
public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
{
return info.LastWriteTimeUtc;
@@ -385,7 +368,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
+ _logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -400,77 +383,74 @@ namespace Emby.Server.Implementations.IO
return GetLastWriteTimeUtc(GetFileSystemInfo(path));
}
+ /// <inheritdoc />
public virtual void SetHidden(string path, bool isHidden)
{
- if (OperatingSystem.Id != OperatingSystemId.Windows)
+ if (!OperatingSystem.IsWindows())
{
return;
}
- var info = GetExtendedFileSystemInfo(path);
+ var info = new FileInfo(path);
- if (info.Exists && info.IsHidden != isHidden)
+ if (info.Exists &&
+ ((info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) != isHidden)
{
if (isHidden)
{
- File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
+ File.SetAttributes(path, info.Attributes | FileAttributes.Hidden);
}
else
{
- var attributes = File.GetAttributes(path);
- attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
- File.SetAttributes(path, attributes);
+ File.SetAttributes(path, info.Attributes & ~FileAttributes.Hidden);
}
}
}
- public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
+ /// <inheritdoc />
+ public virtual void SetAttributes(string path, bool isHidden, bool readOnly)
{
- if (OperatingSystem.Id != OperatingSystemId.Windows)
+ if (!OperatingSystem.IsWindows())
{
return;
}
- var info = GetExtendedFileSystemInfo(path);
+ var info = new FileInfo(path);
if (!info.Exists)
{
return;
}
- if (info.IsReadOnly == isReadOnly && info.IsHidden == isHidden)
+ if (((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) == readOnly
+ && ((info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) == isHidden)
{
return;
}
- var attributes = File.GetAttributes(path);
+ var attributes = info.Attributes;
- if (isReadOnly)
+ if (readOnly)
{
- attributes = attributes | FileAttributes.ReadOnly;
+ attributes |= FileAttributes.ReadOnly;
}
else
{
- attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
+ attributes &= ~FileAttributes.ReadOnly;
}
if (isHidden)
{
- attributes = attributes | FileAttributes.Hidden;
+ attributes |= FileAttributes.Hidden;
}
else
{
- attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
+ attributes &= ~FileAttributes.Hidden;
}
File.SetAttributes(path, attributes);
}
- private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
- {
- return attributes & ~attributesToRemove;
- }
-
/// <summary>
/// Swaps the files.
/// </summary>
@@ -478,15 +458,8 @@ namespace Emby.Server.Implementations.IO
/// <param name="file2">The file2.</param>
public virtual void SwapFiles(string file1, string file2)
{
- if (string.IsNullOrEmpty(file1))
- {
- throw new ArgumentNullException(nameof(file1));
- }
-
- if (string.IsNullOrEmpty(file2))
- {
- throw new ArgumentNullException(nameof(file2));
- }
+ ArgumentException.ThrowIfNullOrEmpty(file1);
+ ArgumentException.ThrowIfNullOrEmpty(file2);
var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
@@ -501,29 +474,21 @@ namespace Emby.Server.Implementations.IO
File.Copy(temp1, file2, true);
}
+ /// <inheritdoc />
public virtual bool ContainsSubPath(string parentPath, string path)
{
- if (string.IsNullOrEmpty(parentPath))
- {
- throw new ArgumentNullException(nameof(parentPath));
- }
-
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
+ ArgumentException.ThrowIfNullOrEmpty(parentPath);
+ ArgumentException.ThrowIfNullOrEmpty(path);
return path.Contains(
Path.TrimEndingDirectorySeparator(parentPath) + Path.DirectorySeparatorChar,
_isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
+ /// <inheritdoc />
public virtual string NormalizePath(string path)
{
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
+ ArgumentException.ThrowIfNullOrEmpty(path);
if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
{
@@ -533,24 +498,16 @@ namespace Emby.Server.Implementations.IO
return Path.TrimEndingDirectorySeparator(path);
}
+ /// <inheritdoc />
public virtual bool AreEqual(string path1, string path2)
{
- if (path1 == null && path2 == null)
- {
- return true;
- }
-
- if (path1 == null || path2 == null)
- {
- return false;
- }
-
return string.Equals(
NormalizePath(path1),
NormalizePath(path2),
_isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
+ /// <inheritdoc />
public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
{
if (info.IsDirectory)
@@ -561,11 +518,11 @@ namespace Emby.Server.Implementations.IO
return Path.GetFileNameWithoutExtension(info.FullName);
}
+ /// <inheritdoc />
public virtual bool IsPathFile(string path)
{
- // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
- if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
- !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
+ if (path.Contains("://", StringComparison.OrdinalIgnoreCase)
+ && !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
return false;
}
@@ -573,49 +530,58 @@ namespace Emby.Server.Implementations.IO
return true;
}
+ /// <inheritdoc />
public virtual void DeleteFile(string path)
{
SetAttributes(path, false, false);
File.Delete(path);
}
- public virtual List<FileSystemMetadata> GetDrives()
+ /// <inheritdoc />
+ public virtual IEnumerable<FileSystemMetadata> GetDrives()
{
// check for ready state to avoid waiting for drives to timeout
// some drives on linux have no actual size or are used for other purposes
- return DriveInfo.GetDrives().Where(d => d.IsReady && d.TotalSize != 0 && d.DriveType != DriveType.Ram)
+ return DriveInfo.GetDrives()
+ .Where(
+ d => (d.DriveType == DriveType.Fixed || d.DriveType == DriveType.Network || d.DriveType == DriveType.Removable)
+ && d.IsReady
+ && d.TotalSize != 0)
.Select(d => new FileSystemMetadata
{
Name = d.Name,
FullName = d.RootDirectory.FullName,
IsDirectory = true
- }).ToList();
+ });
}
+ /// <inheritdoc />
public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive)));
}
+ /// <inheritdoc />
public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
{
return GetFiles(path, null, false, recursive);
}
+ /// <inheritdoc />
public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string>? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
var enumerationOptions = GetEnumerationOptions(recursive);
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
- if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
+ if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions is not null && extensions.Count == 1)
{
return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], enumerationOptions));
}
var files = new DirectoryInfo(path).EnumerateFiles("*", enumerationOptions);
- if (extensions != null && extensions.Count > 0)
+ if (extensions is not null && extensions.Count > 0)
{
files = files.Where(i =>
{
@@ -632,6 +598,7 @@ namespace Emby.Server.Implementations.IO
return ToMetadata(files);
}
+ /// <inheritdoc />
public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{
var directoryInfo = new DirectoryInfo(path);
@@ -645,30 +612,33 @@ namespace Emby.Server.Implementations.IO
return infos.Select(GetFileSystemMetadata);
}
+ /// <inheritdoc />
public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive));
}
+ /// <inheritdoc />
public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false)
{
return GetFilePaths(path, null, false, recursive);
}
+ /// <inheritdoc />
public virtual IEnumerable<string> GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
var enumerationOptions = GetEnumerationOptions(recursive);
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
- if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
+ if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions is not null && extensions.Length == 1)
{
return Directory.EnumerateFiles(path, "*" + extensions[0], enumerationOptions);
}
var files = Directory.EnumerateFiles(path, "*", enumerationOptions);
- if (extensions != null && extensions.Length > 0)
+ if (extensions is not null && extensions.Length > 0)
{
files = files.Where(i =>
{
@@ -685,11 +655,24 @@ namespace Emby.Server.Implementations.IO
return files;
}
+ /// <inheritdoc />
public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{
return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive));
}
+ /// <inheritdoc />
+ public virtual bool DirectoryExists(string path)
+ {
+ return Directory.Exists(path);
+ }
+
+ /// <inheritdoc />
+ public virtual bool FileExists(string path)
+ {
+ return File.Exists(path);
+ }
+
private EnumerationOptions GetEnumerationOptions(bool recursive)
{
return new EnumerationOptions