FileOrganizationService.cs 10.0 KB

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