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