diff options
Diffstat (limited to 'MediaBrowser.Common.Implementations')
17 files changed, 230 insertions, 86 deletions
diff --git a/MediaBrowser.Common.Implementations/Archiving/ZipClient.cs b/MediaBrowser.Common.Implementations/Archiving/ZipClient.cs index cdcbc311a..1377e9d55 100644 --- a/MediaBrowser.Common.Implementations/Archiving/ZipClient.cs +++ b/MediaBrowser.Common.Implementations/Archiving/ZipClient.cs @@ -7,6 +7,7 @@ using SharpCompress.Reader; using SharpCompress.Reader.Zip; using System; using System.IO; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.Archiving { @@ -15,7 +16,14 @@ namespace MediaBrowser.Common.Implementations.Archiving /// </summary> public class ZipClient : IZipClient { - /// <summary> + private IFileSystem _fileSystem; + + public ZipClient(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + + /// <summary> /// Extracts all. /// </summary> /// <param name="sourceFile">The source file.</param> @@ -23,7 +31,7 @@ namespace MediaBrowser.Common.Implementations.Archiving /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = File.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAll(fileStream, targetPath, overwriteExistingFiles); } @@ -73,7 +81,7 @@ namespace MediaBrowser.Common.Implementations.Archiving /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = File.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles); } @@ -112,7 +120,7 @@ namespace MediaBrowser.Common.Implementations.Archiving /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = File.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles); } @@ -150,7 +158,7 @@ namespace MediaBrowser.Common.Implementations.Archiving /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> public void ExtractAllFromRar(string sourceFile, string targetPath, bool overwriteExistingFiles) { - using (var fileStream = File.OpenRead(sourceFile)) + using (var fileStream = _fileSystem.OpenRead(sourceFile)) { ExtractAllFromRar(fileStream, targetPath, overwriteExistingFiles); } diff --git a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs index 70ed5c319..af41635f3 100644 --- a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs +++ b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Common.Implementations /// <summary> /// The _XML serializer /// </summary> - protected readonly IXmlSerializer XmlSerializer = new XmlSerializer(); + protected readonly IXmlSerializer XmlSerializer; /// <summary> /// Gets assemblies that failed to load @@ -180,7 +180,7 @@ namespace MediaBrowser.Common.Implementations { if (_deviceId == null) { - _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId")); + _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager); } return _deviceId.Value; @@ -199,6 +199,7 @@ namespace MediaBrowser.Common.Implementations ILogManager logManager, IFileSystem fileSystem) { + XmlSerializer = new MediaBrowser.Common.Implementations.Serialization.XmlSerializer (fileSystem); FailedAssemblies = new List<string>(); ApplicationPaths = applicationPaths; @@ -320,7 +321,7 @@ namespace MediaBrowser.Common.Implementations protected virtual IJsonSerializer CreateJsonSerializer() { - return new JsonSerializer(); + return new JsonSerializer(FileSystemManager); } private void SetHttpLimit() @@ -449,7 +450,7 @@ namespace MediaBrowser.Common.Implementations RegisterSingleInstance<IApplicationPaths>(ApplicationPaths); - TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger); + TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger, FileSystemManager); RegisterSingleInstance(JsonSerializer); RegisterSingleInstance(XmlSerializer); @@ -473,7 +474,7 @@ namespace MediaBrowser.Common.Implementations InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager); RegisterSingleInstance(InstallationManager); - ZipClient = new ZipClient(); + ZipClient = new ZipClient(FileSystemManager); RegisterSingleInstance(ZipClient); IsoManager = new IsoManager(); @@ -581,7 +582,7 @@ namespace MediaBrowser.Common.Implementations protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true) where T : class { - Container.RegisterSingle(obj); + Container.RegisterSingleton(obj); if (manageLifetime) { @@ -607,7 +608,7 @@ namespace MediaBrowser.Common.Implementations protected void RegisterSingleInstance<T>(Func<T> func) where T : class { - Container.RegisterSingle(func); + Container.RegisterSingleton(func); } void IDependencyContainer.Register(Type typeInterface, Type typeImplementation) diff --git a/MediaBrowser.Common.Implementations/Configuration/ConfigurationHelper.cs b/MediaBrowser.Common.Implementations/Configuration/ConfigurationHelper.cs index ff5b8bd59..276da58d4 100644 --- a/MediaBrowser.Common.Implementations/Configuration/ConfigurationHelper.cs +++ b/MediaBrowser.Common.Implementations/Configuration/ConfigurationHelper.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Linq; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.Configuration { @@ -27,7 +28,7 @@ namespace MediaBrowser.Common.Implementations.Configuration // Use try/catch to avoid the extra file system lookup using File.Exists try { - buffer = File.ReadAllBytes(path); + buffer = File.ReadAllBytes(path); configuration = xmlSerializer.DeserializeFromBytes(type, buffer); } @@ -46,10 +47,10 @@ namespace MediaBrowser.Common.Implementations.Configuration // If the file didn't exist before, or if something has changed, re-save if (buffer == null || !buffer.SequenceEqual(newBytes)) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); + Directory.CreateDirectory(Path.GetDirectoryName(path)); // Save it after load in case we got new items - File.WriteAllBytes(path, newBytes); + File.WriteAllBytes(path, newBytes); } return configuration; diff --git a/MediaBrowser.Common.Implementations/Devices/DeviceId.cs b/MediaBrowser.Common.Implementations/Devices/DeviceId.cs index 2a1c8877d..39f11fabf 100644 --- a/MediaBrowser.Common.Implementations/Devices/DeviceId.cs +++ b/MediaBrowser.Common.Implementations/Devices/DeviceId.cs @@ -3,13 +3,15 @@ using MediaBrowser.Model.Logging; using System; using System.IO; using System.Text; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.Devices { public class DeviceId { private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; private readonly object _syncLock = new object(); @@ -24,7 +26,7 @@ namespace MediaBrowser.Common.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)) @@ -55,11 +57,11 @@ namespace MediaBrowser.Common.Implementations.Devices { var path = CachePath; - Directory.CreateDirectory(Path.GetDirectoryName(path)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); lock (_syncLock) { - File.WriteAllText(path, id, Encoding.UTF8); + _fileSystem.WriteAllText(path, id, Encoding.UTF8); } } catch (Exception ex) @@ -88,10 +90,15 @@ namespace MediaBrowser.Common.Implementations.Devices private string _id; - public DeviceId(IApplicationPaths appPaths, ILogger logger) + public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem) { + if (fileSystem == null) { + throw new ArgumentNullException ("fileSystem"); + } + _appPaths = appPaths; _logger = logger; + _fileSystem = fileSystem; } public string Value diff --git a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs index 89f405e8a..7157f6325 100644 --- a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs +++ b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs @@ -355,7 +355,7 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager private async Task CacheResponse(HttpResponseInfo response, string responseCachePath) { - Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(responseCachePath)); using (var responseStream = response.Content) { @@ -599,7 +599,7 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager { ValidateParams(options); - Directory.CreateDirectory(_appPaths.TempDirectory); + _fileSystem.CreateDirectory(_appPaths.TempDirectory); var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp"); @@ -869,25 +869,11 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true); - asyncTask.ContinueWith(task => - { - taskCompletion.TrySetResult(task.Result); - - }, TaskContinuationOptions.NotOnFaulted); + var callback = new TaskCallback { taskCompletion = taskCompletion }; + asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted); // Handle errors - asyncTask.ContinueWith(task => - { - if (task.Exception != null) - { - taskCompletion.TrySetException(task.Exception); - } - else - { - taskCompletion.TrySetException(new List<Exception>()); - } - - }, TaskContinuationOptions.OnlyOnFaulted); + asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted); return taskCompletion.Task; } @@ -903,5 +889,27 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager } } } + + private class TaskCallback + { + public TaskCompletionSource<WebResponse> taskCompletion; + + public void OnSuccess(Task<WebResponse> task) + { + taskCompletion.TrySetResult(task.Result); + } + + public void OnError(Task<WebResponse> task) + { + if (task.Exception != null) + { + taskCompletion.TrySetException(task.Exception); + } + else + { + taskCompletion.TrySetException(new List<Exception>()); + } + } + } } } diff --git a/MediaBrowser.Common.Implementations/IO/CommonFileSystem.cs b/MediaBrowser.Common.Implementations/IO/CommonFileSystem.cs index e9ef84663..b899e88c2 100644 --- a/MediaBrowser.Common.Implementations/IO/CommonFileSystem.cs +++ b/MediaBrowser.Common.Implementations/IO/CommonFileSystem.cs @@ -4,6 +4,8 @@ using MediaBrowser.Model.Logging; using System; using System.IO; using System.Text; +using System.Collections.Generic; +using System.Linq; namespace MediaBrowser.Common.Implementations.IO { @@ -75,7 +77,7 @@ namespace MediaBrowser.Common.Implementations.IO if (string.Equals(Path.GetExtension(filename), ".mblink", StringComparison.OrdinalIgnoreCase)) { - var path = File.ReadAllText(filename); + var path = ReadAllText(filename); return NormalizePath(path); } @@ -105,7 +107,7 @@ namespace MediaBrowser.Common.Implementations.IO throw new ArgumentNullException("target"); } - File.WriteAllText(shortcutPath, target); + File.WriteAllText(shortcutPath, target); } /// <summary> @@ -230,7 +232,7 @@ namespace MediaBrowser.Common.Implementations.IO /// <param name="share">The share.</param> /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param> /// <returns>FileStream.</returns> - public FileStream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share, bool isAsync = false) + public Stream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share, bool isAsync = false) { if (_supportsAsyncFileStreams && isAsync) { @@ -264,11 +266,11 @@ namespace MediaBrowser.Common.Implementations.IO RemoveHiddenAttribute(file1); RemoveHiddenAttribute(file2); - File.Copy(file1, temp1, true); - File.Copy(file2, temp2, true); + CopyFile(file1, temp1, true); + CopyFile(file2, temp2, true); - File.Copy(temp1, file2, true); - File.Copy(temp2, file1, true); + CopyFile(temp1, file2, true); + CopyFile(temp2, file1, true); DeleteFile(temp1); DeleteFile(temp2); @@ -410,24 +412,110 @@ namespace MediaBrowser.Common.Implementations.IO //return Path.IsPathRooted(path); } - public void DeleteFile(string path, bool sendToRecycleBin) + public void DeleteFile(string path) { File.Delete(path); } - public void DeleteDirectory(string path, bool recursive, bool sendToRecycleBin) + public void DeleteDirectory(string path, bool recursive) { Directory.Delete(path, recursive); + } + + public void CreateDirectory(string path) + { + Directory.CreateDirectory(path); + } + + public IEnumerable<DirectoryInfo> GetDirectories(string path, bool recursive = false) + { + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + + return new DirectoryInfo (path).EnumerateDirectories("*", searchOption); + } + + public IEnumerable<FileInfo> GetFiles(string path, bool recursive = false) + { + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + + return new DirectoryInfo (path).EnumerateFiles("*", searchOption); + } + + public IEnumerable<FileSystemInfo> GetFileSystemEntries(string path, bool recursive = false) + { + var directoryInfo = new DirectoryInfo (path); + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + + return directoryInfo.EnumerateDirectories("*", searchOption) + .Concat<FileSystemInfo>(directoryInfo.EnumerateFiles("*", searchOption)); + } + + public Stream OpenRead(string path) + { + return File.OpenRead(path); } - public void DeleteFile(string path) + public void CopyFile(string source, string target, bool overwrite) { - DeleteFile(path, false); + File.Copy(source, target, overwrite); } - public void DeleteDirectory(string path, bool recursive) + public void MoveFile(string source, string target) + { + File.Move(source, target); + } + + public void MoveDirectory(string source, string target) + { + Directory.Move(source, target); + } + + public bool DirectoryExists(string path) + { + return Directory.Exists(path); + } + + public bool FileExists(string path) + { + return File.Exists(path); + } + + public string ReadAllText(string path) + { + return File.ReadAllText(path); + } + + public void WriteAllText(string path, string text, Encoding encoding) + { + File.WriteAllText(path, text, encoding); + } + + public void WriteAllText(string path, string text) + { + File.WriteAllText(path, text); + } + + public string ReadAllText(string path, Encoding encoding) + { + return File.ReadAllText(path, encoding); + } + + public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false) + { + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + return Directory.EnumerateDirectories(path, "*", searchOption); + } + + public IEnumerable<string> GetFilePaths(string path, bool recursive = false) + { + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + return Directory.EnumerateFiles(path, "*", searchOption); + } + + public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false) { - DeleteDirectory(path, recursive, false); + var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + return Directory.EnumerateFileSystemEntries(path, "*", searchOption); } } } diff --git a/MediaBrowser.Common.Implementations/Logging/NlogManager.cs b/MediaBrowser.Common.Implementations/Logging/NlogManager.cs index 698792802..391e7c212 100644 --- a/MediaBrowser.Common.Implementations/Logging/NlogManager.cs +++ b/MediaBrowser.Common.Implementations/Logging/NlogManager.cs @@ -170,7 +170,7 @@ namespace MediaBrowser.Common.Implementations.Logging /// </summary> /// <param name="name">The name.</param> /// <returns>ILogger.</returns> - public ILogger GetLogger(string name) + public Model.Logging.ILogger GetLogger(string name) { return new NLogger(name, this); } @@ -208,7 +208,7 @@ namespace MediaBrowser.Common.Implementations.Logging { LogFilePath = Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Round(DateTime.Now.Ticks / 10000000) + ".txt"); - Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath)); + Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath)); AddFileTarget(LogFilePath, level); diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index e603ea373..eb1122902 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -48,18 +48,17 @@ <RunPostBuildEvent>Always</RunPostBuildEvent> </PropertyGroup> <ItemGroup> - <Reference Include="NLog, Version=3.2.1.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL"> + <Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\NLog.3.2.1\lib\net45\NLog.dll</HintPath> + <HintPath>..\packages\NLog.4.1.1\lib\net45\NLog.dll</HintPath> </Reference> <Reference Include="SharpCompress, Version=0.10.2.0, Culture=neutral, PublicKeyToken=beaf6f427e128133, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\ThirdParty\SharpCompress\SharpCompress.dll</HintPath> </Reference> - <Reference Include="SimpleInjector, Version=2.7.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL"> + <Reference Include="SimpleInjector, Version=2.8.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\SimpleInjector.2.8.0\lib\net45\SimpleInjector.dll</HintPath> - <Private>True</Private> + <HintPath>..\packages\SimpleInjector.3.0.5\lib\net45\SimpleInjector.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core" /> diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index cbd1c1ac5..906184c75 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -12,6 +12,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.ScheduledTasks { @@ -51,6 +52,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// </summary> /// <value>The task manager.</value> private ITaskManager TaskManager { get; set; } + private readonly IFileSystem _fileSystem; /// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. @@ -71,7 +73,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// or /// logger /// </exception> - public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger) + public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem) { if (scheduledTask == null) { @@ -99,6 +101,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks TaskManager = taskManager; JsonSerializer = jsonSerializer; Logger = logger; + _fileSystem = fileSystem; ReloadTriggerEvents(true); } @@ -154,7 +157,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks _lastExecutionResult = value; var path = GetHistoryFilePath(); - Directory.CreateDirectory(Path.GetDirectoryName(path)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); lock (_lastExecutionResultSyncLock) { @@ -552,7 +555,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks { var path = GetConfigurationFilePath(); - Directory.CreateDirectory(Path.GetDirectoryName(path)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); JsonSerializer.SerializeToFile(triggers.Select(ScheduledTaskHelpers.GetTriggerInfo), path); } diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs index de7987bd2..9419bdf22 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs @@ -10,6 +10,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.ScheduledTasks { @@ -50,6 +51,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// </summary> /// <value>The logger.</value> private ILogger Logger { get; set; } + private readonly IFileSystem _fileSystem; /// <summary> /// Initializes a new instance of the <see cref="TaskManager" /> class. @@ -58,11 +60,12 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentException">kernel</exception> - public TaskManager(IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger) + public TaskManager(IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem) { ApplicationPaths = applicationPaths; JsonSerializer = jsonSerializer; Logger = logger; + _fileSystem = fileSystem; ScheduledTasks = new IScheduledTaskWorker[] { }; } @@ -106,9 +109,16 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks public void QueueScheduledTask<T>(TaskExecutionOptions options) where T : IScheduledTask { - var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T)); + var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T)); - QueueScheduledTask(scheduledTask, options); + if (scheduledTask == null) + { + Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); + } + else + { + QueueScheduledTask(scheduledTask, options); + } } public void QueueScheduledTask<T>() @@ -124,9 +134,16 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// <param name="options">The task options.</param> public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options) { - var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == task.GetType()); + var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType()); - QueueScheduledTask(scheduledTask, options); + if (scheduledTask == null) + { + Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); + } + else + { + QueueScheduledTask(scheduledTask, options); + } } /// <summary> @@ -161,7 +178,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks var myTasks = ScheduledTasks.ToList(); var list = tasks.ToList(); - myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger))); + myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem))); ScheduledTasks = myTasks.ToArray(); } diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index d9c178d8b..6d5516ebd 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -95,7 +95,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks /// <param name="progress">The progress.</param> private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress) { - var filesToDelete = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories) + var filesToDelete = _fileSystem.GetFiles(directory, true) .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified) .ToList(); @@ -120,14 +120,14 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks progress.Report(100); } - private static void DeleteEmptyFolders(string parent) + private void DeleteEmptyFolders(string parent) { foreach (var directory in Directory.GetDirectories(parent)) { DeleteEmptyFolders(directory); if (!Directory.EnumerateFileSystemEntries(directory).Any()) { - Directory.Delete(directory, false); + _fileSystem.DeleteDirectory(directory, false); } } } diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs index b2759c52a..ffba3d9da 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs @@ -58,7 +58,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks // Delete log files more than n days old var minDateModified = DateTime.UtcNow.AddDays(-(ConfigurationManager.CommonConfiguration.LogFileRetentionDays)); - var filesToDelete = new DirectoryInfo(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath).EnumerateFileSystemInfos("*", SearchOption.AllDirectories) + var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, true) .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified) .ToList(); diff --git a/MediaBrowser.Common.Implementations/Security/MBLicenseFile.cs b/MediaBrowser.Common.Implementations/Security/MBLicenseFile.cs index 63381efcd..79e558794 100644 --- a/MediaBrowser.Common.Implementations/Security/MBLicenseFile.cs +++ b/MediaBrowser.Common.Implementations/Security/MBLicenseFile.cs @@ -99,7 +99,7 @@ namespace MediaBrowser.Common.Implementations.Security { try { - contents = File.ReadAllLines(licenseFile); + contents = File.ReadAllLines(licenseFile); } catch (DirectoryNotFoundException) { @@ -107,7 +107,7 @@ namespace MediaBrowser.Common.Implementations.Security } catch (FileNotFoundException) { - (File.Create(licenseFile)).Close(); + (File.Create(licenseFile)).Close(); } } if (contents != null && contents.Length > 0) @@ -150,8 +150,8 @@ namespace MediaBrowser.Common.Implementations.Security } var licenseFile = Filename; - Directory.CreateDirectory(Path.GetDirectoryName(licenseFile)); - lock (_fileLock) File.WriteAllLines(licenseFile, lines); + Directory.CreateDirectory(Path.GetDirectoryName(licenseFile)); + lock (_fileLock) File.WriteAllLines(licenseFile, lines); } } } diff --git a/MediaBrowser.Common.Implementations/Serialization/JsonSerializer.cs b/MediaBrowser.Common.Implementations/Serialization/JsonSerializer.cs index f194b334a..a758a0c1e 100644 --- a/MediaBrowser.Common.Implementations/Serialization/JsonSerializer.cs +++ b/MediaBrowser.Common.Implementations/Serialization/JsonSerializer.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Model.Serialization; +using MediaBrowser.Common.IO; +using MediaBrowser.Model.Serialization; using System; using System.IO; @@ -9,8 +10,11 @@ namespace MediaBrowser.Common.Implementations.Serialization /// </summary> public class JsonSerializer : IJsonSerializer { - public JsonSerializer() + private readonly IFileSystem _fileSystem; + + public JsonSerializer(IFileSystem fileSystem) { + _fileSystem = fileSystem; Configure(); } @@ -53,7 +57,7 @@ namespace MediaBrowser.Common.Implementations.Serialization throw new ArgumentNullException("file"); } - using (Stream stream = File.Open(file, FileMode.Create)) + using (Stream stream = _fileSystem.GetFileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) { SerializeToStream(obj, stream); } diff --git a/MediaBrowser.Common.Implementations/Serialization/XmlSerializer.cs b/MediaBrowser.Common.Implementations/Serialization/XmlSerializer.cs index 04030522f..41a59fb2b 100644 --- a/MediaBrowser.Common.Implementations/Serialization/XmlSerializer.cs +++ b/MediaBrowser.Common.Implementations/Serialization/XmlSerializer.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.IO; using System.Xml; +using MediaBrowser.Common.IO; namespace MediaBrowser.Common.Implementations.Serialization { @@ -11,6 +12,13 @@ namespace MediaBrowser.Common.Implementations.Serialization /// </summary> public class XmlSerializer : IXmlSerializer { + private IFileSystem _fileSystem; + + public XmlSerializer(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + // Need to cache these // http://dotnetcodebox.blogspot.com/2013/01/xmlserializer-class-may-result-in.html private readonly ConcurrentDictionary<string, System.Xml.Serialization.XmlSerializer> _serializers = @@ -83,7 +91,7 @@ namespace MediaBrowser.Common.Implementations.Serialization /// <returns>System.Object.</returns> public object DeserializeFromFile(Type type, string file) { - using (var stream = File.OpenRead(file)) + using (var stream = _fileSystem.OpenRead(file)) { return DeserializeFromStream(type, stream); } diff --git a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs index 5f205d69e..12afdd8d7 100644 --- a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs +++ b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs @@ -553,7 +553,7 @@ namespace MediaBrowser.Common.Implementations.Updates if (packageChecksum != Guid.Empty) // support for legacy uploads for now { using (var crypto = new MD5CryptoServiceProvider()) - using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000)) + using (var stream = new BufferedStream(_fileSystem.OpenRead(tempFile), 100000)) { var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty)); if (check != packageChecksum) @@ -568,12 +568,12 @@ namespace MediaBrowser.Common.Implementations.Updates // Success - move it to the real target try { - Directory.CreateDirectory(Path.GetDirectoryName(target)); - File.Copy(tempFile, target, true); + _fileSystem.CreateDirectory(Path.GetDirectoryName(target)); + _fileSystem.CopyFile(tempFile, target, true); //If it is an archive - write out a version file so we know what it is if (isArchive) { - File.WriteAllText(target + ".ver", package.versionStr); + File.WriteAllText(target + ".ver", package.versionStr); } } catch (IOException e) diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index e57c874f2..151a3a36d 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="NLog" version="3.2.1" targetFramework="net45" /> - <package id="SimpleInjector" version="2.8.0" targetFramework="net45" /> + <package id="NLog" version="4.1.0" targetFramework="net45" /> + <package id="SimpleInjector" version="3.0.5" targetFramework="net45" /> </packages> |
