FileOrganizationService.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.FileOrganization;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Model.FileOrganization;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Querying;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using CommonIO;
  18. using MediaBrowser.Controller.Session;
  19. using MediaBrowser.Model.Events;
  20. using MediaBrowser.Common.Events;
  21. namespace MediaBrowser.Server.Implementations.FileOrganization
  22. {
  23. public class FileOrganizationService : IFileOrganizationService
  24. {
  25. private readonly ITaskManager _taskManager;
  26. private readonly IFileOrganizationRepository _repo;
  27. private readonly ILogger _logger;
  28. private readonly ILibraryMonitor _libraryMonitor;
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IServerConfigurationManager _config;
  31. private readonly IFileSystem _fileSystem;
  32. private readonly IProviderManager _providerManager;
  33. private readonly ConcurrentDictionary<string, bool> _inProgressItemIds = new ConcurrentDictionary<string, bool>();
  34. public event EventHandler<GenericEventArgs<FileOrganizationResult>> ItemAdded;
  35. public event EventHandler<GenericEventArgs<FileOrganizationResult>> ItemUpdated;
  36. public event EventHandler<GenericEventArgs<FileOrganizationResult>> ItemRemoved;
  37. public event EventHandler LogReset;
  38. public FileOrganizationService(ITaskManager taskManager, IFileOrganizationRepository repo, ILogger logger, ILibraryMonitor libraryMonitor, ILibraryManager libraryManager, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager)
  39. {
  40. _taskManager = taskManager;
  41. _repo = repo;
  42. _logger = logger;
  43. _libraryMonitor = libraryMonitor;
  44. _libraryManager = libraryManager;
  45. _config = config;
  46. _fileSystem = fileSystem;
  47. _providerManager = providerManager;
  48. }
  49. public void BeginProcessNewFiles()
  50. {
  51. _taskManager.CancelIfRunningAndQueue<OrganizerScheduledTask>();
  52. }
  53. public Task SaveResult(FileOrganizationResult result, CancellationToken cancellationToken)
  54. {
  55. if (result == null || string.IsNullOrEmpty(result.OriginalPath))
  56. {
  57. throw new ArgumentNullException("result");
  58. }
  59. result.Id = result.OriginalPath.GetMD5().ToString("N");
  60. return _repo.SaveResult(result, cancellationToken);
  61. }
  62. public QueryResult<FileOrganizationResult> GetResults(FileOrganizationResultQuery query)
  63. {
  64. var results = _repo.GetResults(query);
  65. foreach (var result in results.Items)
  66. {
  67. result.IsInProgress = _inProgressItemIds.ContainsKey(result.Id);
  68. }
  69. return results;
  70. }
  71. public FileOrganizationResult GetResult(string id)
  72. {
  73. var result = _repo.GetResult(id);
  74. if (result != null)
  75. {
  76. result.IsInProgress = _inProgressItemIds.ContainsKey(result.Id);
  77. }
  78. return result;
  79. }
  80. public FileOrganizationResult GetResultBySourcePath(string path)
  81. {
  82. if (string.IsNullOrEmpty(path))
  83. {
  84. throw new ArgumentNullException("path");
  85. }
  86. var id = path.GetMD5().ToString("N");
  87. return GetResult(id);
  88. }
  89. public async Task DeleteOriginalFile(string resultId)
  90. {
  91. var result = _repo.GetResult(resultId);
  92. _logger.Info("Requested to delete {0}", result.OriginalPath);
  93. if (!AddToInProgressList(result, false))
  94. {
  95. throw new Exception("Path is currently processed otherwise. Please try again later.");
  96. }
  97. try
  98. {
  99. _fileSystem.DeleteFile(result.OriginalPath);
  100. }
  101. catch (Exception ex)
  102. {
  103. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  104. }
  105. finally
  106. {
  107. RemoveFromInprogressList(result);
  108. }
  109. await _repo.Delete(resultId);
  110. EventHelper.FireEventIfNotNull(ItemRemoved, this, new GenericEventArgs<FileOrganizationResult>(result), _logger);
  111. }
  112. private AutoOrganizeOptions GetAutoOrganizeOptions()
  113. {
  114. return _config.GetAutoOrganizeOptions();
  115. }
  116. public async Task PerformOrganization(string resultId)
  117. {
  118. var result = _repo.GetResult(resultId);
  119. if (string.IsNullOrEmpty(result.TargetPath))
  120. {
  121. throw new ArgumentException("No target path available.");
  122. }
  123. var organizer = new EpisodeFileOrganizer(this, _config, _fileSystem, _logger, _libraryManager,
  124. _libraryMonitor, _providerManager);
  125. var organizeResult = await organizer.OrganizeEpisodeFile(result.OriginalPath, GetAutoOrganizeOptions(), true, CancellationToken.None)
  126. .ConfigureAwait(false);
  127. if (organizeResult.Status != FileSortingStatus.Success)
  128. {
  129. throw new Exception(result.StatusMessage);
  130. }
  131. }
  132. public async Task ClearLog()
  133. {
  134. await _repo.DeleteAll();
  135. EventHelper.FireEventIfNotNull(LogReset, this, EventArgs.Empty, _logger);
  136. }
  137. public async Task PerformEpisodeOrganization(EpisodeFileOrganizationRequest request)
  138. {
  139. var organizer = new EpisodeFileOrganizer(this, _config, _fileSystem, _logger, _libraryManager,
  140. _libraryMonitor, _providerManager);
  141. var result = await organizer.OrganizeWithCorrection(request, GetAutoOrganizeOptions(), CancellationToken.None).ConfigureAwait(false);
  142. if (result.Status != FileSortingStatus.Success)
  143. {
  144. throw new Exception(result.StatusMessage);
  145. }
  146. }
  147. public QueryResult<SmartMatchInfo> GetSmartMatchInfos(FileOrganizationResultQuery query)
  148. {
  149. if (query == null)
  150. {
  151. throw new ArgumentNullException("query");
  152. }
  153. var options = GetAutoOrganizeOptions();
  154. var items = options.SmartMatchInfos.Skip(query.StartIndex ?? 0).Take(query.Limit ?? Int32.MaxValue).ToArray();
  155. return new QueryResult<SmartMatchInfo>()
  156. {
  157. Items = items,
  158. TotalRecordCount = options.SmartMatchInfos.Length
  159. };
  160. }
  161. public void DeleteSmartMatchEntry(string itemName, string matchString)
  162. {
  163. if (string.IsNullOrEmpty(itemName))
  164. {
  165. throw new ArgumentNullException("itemName");
  166. }
  167. if (string.IsNullOrEmpty(matchString))
  168. {
  169. throw new ArgumentNullException("matchString");
  170. }
  171. var options = GetAutoOrganizeOptions();
  172. SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(i => string.Equals(i.ItemName, itemName));
  173. if (info != null && info.MatchStrings.Contains(matchString))
  174. {
  175. var list = info.MatchStrings.ToList();
  176. list.Remove(matchString);
  177. info.MatchStrings = list.ToArray();
  178. if (info.MatchStrings.Length == 0)
  179. {
  180. var infos = options.SmartMatchInfos.ToList();
  181. infos.Remove(info);
  182. options.SmartMatchInfos = infos.ToArray();
  183. }
  184. _config.SaveAutoOrganizeOptions(options);
  185. }
  186. }
  187. /// <summary>
  188. /// Attempts to add a an item to the list of currently processed items.
  189. /// </summary>
  190. /// <param name="result">The result item.</param>
  191. /// <param name="isNewItem">Passing true will notify the client to reload all items, otherwise only a single item will be refreshed.</param>
  192. /// <returns>True if the item was added, False if the item is already contained in the list.</returns>
  193. public bool AddToInProgressList(FileOrganizationResult result, bool isNewItem)
  194. {
  195. if (string.IsNullOrWhiteSpace(result.Id))
  196. {
  197. result.Id = result.OriginalPath.GetMD5().ToString("N");
  198. }
  199. if (!_inProgressItemIds.TryAdd(result.Id, false))
  200. {
  201. return false;
  202. }
  203. result.IsInProgress = true;
  204. if (isNewItem)
  205. {
  206. EventHelper.FireEventIfNotNull(ItemAdded, this, new GenericEventArgs<FileOrganizationResult>(result), _logger);
  207. }
  208. else
  209. {
  210. EventHelper.FireEventIfNotNull(ItemUpdated, this, new GenericEventArgs<FileOrganizationResult>(result), _logger);
  211. }
  212. return true;
  213. }
  214. /// <summary>
  215. /// Removes an item from the list of currently processed items.
  216. /// </summary>
  217. /// <param name="result">The result item.</param>
  218. /// <returns>True if the item was removed, False if the item was not contained in the list.</returns>
  219. public bool RemoveFromInprogressList(FileOrganizationResult result)
  220. {
  221. bool itemValue;
  222. var retval = _inProgressItemIds.TryRemove(result.Id, out itemValue);
  223. result.IsInProgress = false;
  224. EventHelper.FireEventIfNotNull(ItemUpdated, this, new GenericEventArgs<FileOrganizationResult>(result), _logger);
  225. return retval;
  226. }
  227. }
  228. }