replace file system calls with IFileSystem when needed

This commit is contained in:
Luke Pulverenti
2013-10-31 10:03:23 -04:00
parent 579b507f7f
commit 6c8d919298
80 changed files with 570 additions and 302 deletions

View File

@@ -5,6 +5,7 @@ using MediaBrowser.Common.Constants;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Implementations;
using MediaBrowser.Common.Implementations.ScheduledTasks;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
@@ -170,8 +171,6 @@ namespace MediaBrowser.ServerApplication
private Task<IHttpServer> _httpServerCreationTask;
private IFileSystem FileSystemManager { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationHost"/> class.
/// </summary>
@@ -237,7 +236,7 @@ namespace MediaBrowser.ServerApplication
await base.RegisterResources().ConfigureAwait(false);
RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager));
RegisterSingleInstance<IServerApplicationHost>(this);
RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
@@ -249,9 +248,6 @@ namespace MediaBrowser.ServerApplication
RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
FileSystemManager = FileSystemFactory.CreateFileSystemManager(LogManager);
RegisterSingleInstance(FileSystemManager);
var mediaEncoderTask = RegisterMediaEncoder();
UserDataManager = new UserDataManager(LogManager);
@@ -275,7 +271,7 @@ namespace MediaBrowser.ServerApplication
DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
RegisterSingleInstance(DirectoryWatchers);
ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager);
ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, FileSystemManager);
RegisterSingleInstance(ProviderManager);
RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
@@ -289,10 +285,10 @@ namespace MediaBrowser.ServerApplication
ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
RegisterSingleInstance(ServerManager);
LocalizationManager = new LocalizationManager(ServerConfigurationManager);
LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
RegisterSingleInstance(LocalizationManager);
ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
RegisterSingleInstance(ImageProcessor);
DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor);
@@ -317,15 +313,20 @@ namespace MediaBrowser.ServerApplication
return new NetworkManager();
}
protected override IFileSystem CreateFileSystemManager()
{
return FileSystemFactory.CreateFileSystemManager(LogManager);
}
/// <summary>
/// Registers the media encoder.
/// </summary>
/// <returns>Task.</returns>
private async Task RegisterMediaEncoder()
{
var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient).GetFFMpegInfo().ConfigureAwait(false);
var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo().ConfigureAwait(false);
MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version);
MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
RegisterSingleInstance(MediaEncoder);
}
@@ -335,7 +336,7 @@ namespace MediaBrowser.ServerApplication
private void SetKernelProperties()
{
Parallel.Invoke(
() => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
() => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository, FileSystemManager),
() => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
SetStaticProperties
);

View File

@@ -1,6 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
@@ -20,18 +21,20 @@ namespace MediaBrowser.ServerApplication.FFMpeg
private readonly IApplicationPaths _appPaths;
private readonly ILogger _logger;
private readonly IZipClient _zipClient;
private readonly IFileSystem _fileSystem;
private readonly string[] _fontUrls = new[]
{
"https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1"
};
public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient)
public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem)
{
_logger = logger;
_appPaths = appPaths;
_httpClient = httpClient;
_zipClient = zipClient;
_fileSystem = fileSystem;
}
public async Task<FFMpegInfo> GetFFMpegInfo()
@@ -272,9 +275,8 @@ namespace MediaBrowser.ServerApplication.FFMpeg
var bytes = Encoding.UTF8.GetBytes(contents);
using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize,
FileOptions.Asynchronous))
using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
FileShare.Read, true))
{
await fileStream.WriteAsync(bytes, 0, bytes.Length);
}

View File

@@ -1,291 +0,0 @@
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Logging;
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.ServerApplication.IO
{
/// <summary>
/// Class CommonFileSystem
/// </summary>
public class CommonFileSystem : IFileSystem
{
protected ILogger Logger;
public CommonFileSystem(ILogger logger)
{
Logger = logger;
}
/// <summary>
/// Determines whether the specified filename is shortcut.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
/// <exception cref="System.ArgumentNullException">filename</exception>
public virtual bool IsShortcut(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("filename");
}
var extension = Path.GetExtension(filename);
return string.Equals(extension, ".mblink", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Resolves the shortcut.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">filename</exception>
public virtual string ResolveShortcut(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("filename");
}
if (string.Equals(Path.GetExtension(filename), ".mblink", StringComparison.OrdinalIgnoreCase))
{
return File.ReadAllText(filename);
}
return null;
}
/// <summary>
/// Creates the shortcut.
/// </summary>
/// <param name="shortcutPath">The shortcut path.</param>
/// <param name="target">The target.</param>
/// <exception cref="System.ArgumentNullException">
/// shortcutPath
/// or
/// target
/// </exception>
public void CreateShortcut(string shortcutPath, string target)
{
if (string.IsNullOrEmpty(shortcutPath))
{
throw new ArgumentNullException("shortcutPath");
}
if (string.IsNullOrEmpty(target))
{
throw new ArgumentNullException("target");
}
File.WriteAllText(shortcutPath, target);
}
/// <summary>
/// Gets the file system info.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>FileSystemInfo.</returns>
public FileSystemInfo GetFileSystemInfo(string path)
{
// Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
if (Path.HasExtension(path))
{
var fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
return fileInfo;
}
return new DirectoryInfo(path);
}
else
{
var fileInfo = new DirectoryInfo(path);
if (fileInfo.Exists)
{
return fileInfo;
}
return new FileInfo(path);
}
}
/// <summary>
/// The space char
/// </summary>
private const char SpaceChar = ' ';
/// <summary>
/// The invalid file name chars
/// </summary>
private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>
/// Takes a filename and removes invalid characters
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">filename</exception>
public string GetValidFilename(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("filename");
}
var builder = new StringBuilder(filename);
foreach (var c in InvalidFileNameChars)
{
builder = builder.Replace(c, SpaceChar);
}
return builder.ToString();
}
/// <summary>
/// Gets the creation time UTC.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>DateTime.</returns>
public DateTime GetCreationTimeUtc(FileSystemInfo info)
{
// This could throw an error on some file systems that have dates out of range
try
{
return info.CreationTimeUtc;
}
catch (Exception ex)
{
Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
return DateTime.MinValue;
}
}
}
/// <summary>
/// Adapted from http://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java
/// </summary>
internal class WindowsShortcut
{
public bool IsDirectory { get; private set; }
public bool IsLocal { get; private set; }
public string ResolvedPath { get; private set; }
public WindowsShortcut(string file)
{
ParseLink(File.ReadAllBytes(file), Encoding.UTF8);
}
private static bool isMagicPresent(byte[] link)
{
const int magic = 0x0000004C;
const int magic_offset = 0x00;
return link.Length >= 32 && bytesToDword(link, magic_offset) == magic;
}
/**
* Gobbles up link data by parsing it and storing info in member fields
* @param link all the bytes from the .lnk file
*/
private void ParseLink(byte[] link, Encoding encoding)
{
if (!isMagicPresent(link))
throw new IOException("Invalid shortcut; magic is missing", 0);
// get the flags byte
byte flags = link[0x14];
// get the file attributes byte
const int file_atts_offset = 0x18;
byte file_atts = link[file_atts_offset];
byte is_dir_mask = (byte)0x10;
if ((file_atts & is_dir_mask) > 0)
{
IsDirectory = true;
}
else
{
IsDirectory = false;
}
// if the shell settings are present, skip them
const int shell_offset = 0x4c;
const byte has_shell_mask = (byte)0x01;
int shell_len = 0;
if ((flags & has_shell_mask) > 0)
{
// the plus 2 accounts for the length marker itself
shell_len = bytesToWord(link, shell_offset) + 2;
}
// get to the file settings
int file_start = 0x4c + shell_len;
const int file_location_info_flag_offset_offset = 0x08;
int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];
IsLocal = (file_location_info_flag & 2) == 0;
// get the local volume and local system values
//final int localVolumeTable_offset_offset = 0x0C;
const int basename_offset_offset = 0x10;
const int networkVolumeTable_offset_offset = 0x14;
const int finalname_offset_offset = 0x18;
int finalname_offset = link[file_start + finalname_offset_offset] + file_start;
String finalname = getNullDelimitedString(link, finalname_offset, encoding);
if (IsLocal)
{
int basename_offset = link[file_start + basename_offset_offset] + file_start;
String basename = getNullDelimitedString(link, basename_offset, encoding);
ResolvedPath = basename + finalname;
}
else
{
int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;
int shareName_offset_offset = 0x08;
int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]
+ networkVolumeTable_offset;
String shareName = getNullDelimitedString(link, shareName_offset, encoding);
ResolvedPath = shareName + "\\" + finalname;
}
}
private static string getNullDelimitedString(byte[] bytes, int off, Encoding encoding)
{
int len = 0;
// count bytes until the null character (0)
while (true)
{
if (bytes[off + len] == 0)
{
break;
}
len++;
}
return encoding.GetString(bytes, off, len);
}
/*
* convert two bytes into a short note, this is little endian because it's
* for an Intel only OS.
*/
private static int bytesToWord(byte[] bytes, int off)
{
return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
}
private static int bytesToDword(byte[] bytes, int off)
{
return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off);
}
}
}

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Controller.IO;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Logging;
namespace MediaBrowser.ServerApplication.IO

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Model.Logging;
using MediaBrowser.Common.Implementations.IO;
using MediaBrowser.Model.Logging;
using System;
using System.IO;
using System.Runtime.InteropServices;
@@ -10,7 +11,7 @@ namespace MediaBrowser.ServerApplication.IO
public class NativeFileSystem : CommonFileSystem
{
public NativeFileSystem(ILogger logger)
: base(logger)
: base(logger, true)
{
}

View File

@@ -190,7 +190,6 @@
<Compile Include="FFMpeg\FFMpegInfo.cs" />
<Compile Include="IO\FileSystemFactory.cs" />
<Compile Include="Native\Assemblies.cs" />
<Compile Include="IO\CommonFileSystem.cs" />
<Compile Include="Native\HttpClientFactory.cs" />
<Compile Include="Native\NativeApp.cs" />
<Compile Include="IO\NativeFileSystem.cs" />