FileOrganizationService.cs 9.9 KB

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