SyncJobProcessor.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Controller.Sync;
  7. using MediaBrowser.Controller.TV;
  8. using MediaBrowser.Model.Dlna;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.MediaInfo;
  13. using MediaBrowser.Model.Querying;
  14. using MediaBrowser.Model.Session;
  15. using MediaBrowser.Model.Sync;
  16. using MoreLinq;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.Server.Implementations.Sync
  23. {
  24. public class SyncJobProcessor
  25. {
  26. private readonly ILibraryManager _libraryManager;
  27. private readonly ISyncRepository _syncRepo;
  28. private readonly ISyncManager _syncManager;
  29. private readonly ILogger _logger;
  30. private readonly IUserManager _userManager;
  31. private readonly ITVSeriesManager _tvSeriesManager;
  32. private readonly IMediaEncoder _mediaEncoder;
  33. public SyncJobProcessor(ILibraryManager libraryManager, ISyncRepository syncRepo, ISyncManager syncManager, ILogger logger, IUserManager userManager, ITVSeriesManager tvSeriesManager, IMediaEncoder mediaEncoder)
  34. {
  35. _libraryManager = libraryManager;
  36. _syncRepo = syncRepo;
  37. _syncManager = syncManager;
  38. _logger = logger;
  39. _userManager = userManager;
  40. _tvSeriesManager = tvSeriesManager;
  41. _mediaEncoder = mediaEncoder;
  42. }
  43. public async Task EnsureJobItems(SyncJob job)
  44. {
  45. var user = _userManager.GetUserById(job.UserId);
  46. if (user == null)
  47. {
  48. throw new InvalidOperationException("Cannot proceed with sync because user no longer exists.");
  49. }
  50. var items = (await GetItemsForSync(job.Category, job.ParentId, job.RequestedItemIds, user, job.UnwatchedOnly).ConfigureAwait(false))
  51. .ToList();
  52. var jobItems = _syncRepo.GetJobItems(new SyncJobItemQuery
  53. {
  54. JobId = job.Id
  55. }).Items.ToList();
  56. foreach (var item in items)
  57. {
  58. // Respect ItemLimit, if set
  59. if (job.ItemLimit.HasValue)
  60. {
  61. if (jobItems.Count(j => j.Status != SyncJobItemStatus.RemovedFromDevice && j.Status != SyncJobItemStatus.Failed) >= job.ItemLimit.Value)
  62. {
  63. break;
  64. }
  65. }
  66. var itemId = item.Id.ToString("N");
  67. var jobItem = jobItems.FirstOrDefault(i => string.Equals(i.ItemId, itemId, StringComparison.OrdinalIgnoreCase));
  68. if (jobItem != null)
  69. {
  70. continue;
  71. }
  72. jobItem = new SyncJobItem
  73. {
  74. Id = Guid.NewGuid().ToString("N"),
  75. ItemId = itemId,
  76. ItemName = GetSyncJobItemName(item),
  77. JobId = job.Id,
  78. TargetId = job.TargetId,
  79. DateCreated = DateTime.UtcNow
  80. };
  81. await _syncRepo.Create(jobItem).ConfigureAwait(false);
  82. jobItems.Add(jobItem);
  83. }
  84. jobItems = jobItems
  85. .OrderBy(i => i.DateCreated)
  86. .ToList();
  87. await UpdateJobStatus(job, jobItems).ConfigureAwait(false);
  88. }
  89. private string GetSyncJobItemName(BaseItem item)
  90. {
  91. return item.Name;
  92. }
  93. public Task UpdateJobStatus(string id)
  94. {
  95. var job = _syncRepo.GetJob(id);
  96. return UpdateJobStatus(job);
  97. }
  98. private Task UpdateJobStatus(SyncJob job)
  99. {
  100. if (job == null)
  101. {
  102. throw new ArgumentNullException("job");
  103. }
  104. var result = _syncRepo.GetJobItems(new SyncJobItemQuery
  105. {
  106. JobId = job.Id
  107. });
  108. return UpdateJobStatus(job, result.Items.ToList());
  109. }
  110. private Task UpdateJobStatus(SyncJob job, List<SyncJobItem> jobItems)
  111. {
  112. job.ItemCount = jobItems.Count;
  113. double pct = 0;
  114. foreach (var item in jobItems)
  115. {
  116. if (item.Status == SyncJobItemStatus.Failed || item.Status == SyncJobItemStatus.Synced || item.Status == SyncJobItemStatus.RemovedFromDevice)
  117. {
  118. pct += 100;
  119. }
  120. else
  121. {
  122. pct += item.Progress ?? 0;
  123. }
  124. }
  125. if (job.ItemCount > 0)
  126. {
  127. pct /= job.ItemCount;
  128. job.Progress = pct;
  129. }
  130. else
  131. {
  132. job.Progress = null;
  133. }
  134. if (pct >= 100)
  135. {
  136. if (jobItems.Any(i => i.Status == SyncJobItemStatus.Failed))
  137. {
  138. job.Status = SyncJobStatus.CompletedWithError;
  139. }
  140. else
  141. {
  142. job.Status = SyncJobStatus.Completed;
  143. }
  144. }
  145. else if (pct.Equals(0))
  146. {
  147. job.Status = SyncJobStatus.Queued;
  148. }
  149. else
  150. {
  151. job.Status = SyncJobStatus.InProgress;
  152. }
  153. return _syncRepo.Update(job);
  154. }
  155. public async Task<IEnumerable<BaseItem>> GetItemsForSync(SyncCategory? category, string parentId, IEnumerable<string> itemIds, User user, bool unwatchedOnly)
  156. {
  157. var items = category.HasValue ?
  158. await GetItemsForSync(category.Value, parentId, user).ConfigureAwait(false) :
  159. itemIds.SelectMany(i => GetItemsForSync(i, user))
  160. .Where(_syncManager.SupportsSync);
  161. if (unwatchedOnly)
  162. {
  163. // Avoid implicitly captured closure
  164. var currentUser = user;
  165. items = items.Where(i =>
  166. {
  167. var video = i as Video;
  168. if (video != null)
  169. {
  170. return !video.IsPlayed(currentUser);
  171. }
  172. return true;
  173. });
  174. }
  175. return items.DistinctBy(i => i.Id);
  176. }
  177. private async Task<IEnumerable<BaseItem>> GetItemsForSync(SyncCategory category, string parentId, User user)
  178. {
  179. var parent = string.IsNullOrWhiteSpace(parentId)
  180. ? user.RootFolder
  181. : (Folder)_libraryManager.GetItemById(parentId);
  182. InternalItemsQuery query;
  183. switch (category)
  184. {
  185. case SyncCategory.Latest:
  186. query = new InternalItemsQuery
  187. {
  188. IsFolder = false,
  189. SortBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName },
  190. SortOrder = SortOrder.Descending,
  191. Recursive = true
  192. };
  193. break;
  194. case SyncCategory.Resume:
  195. query = new InternalItemsQuery
  196. {
  197. IsFolder = false,
  198. SortBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName },
  199. SortOrder = SortOrder.Descending,
  200. Recursive = true,
  201. IsResumable = true,
  202. MediaTypes = new[] { MediaType.Video }
  203. };
  204. break;
  205. case SyncCategory.NextUp:
  206. return _tvSeriesManager.GetNextUp(new NextUpQuery
  207. {
  208. ParentId = parentId,
  209. UserId = user.Id.ToString("N")
  210. }).Items;
  211. default:
  212. throw new ArgumentException("Unrecognized category: " + category);
  213. }
  214. query.User = user;
  215. var result = await parent.GetItems(query).ConfigureAwait(false);
  216. return result.Items;
  217. }
  218. private IEnumerable<BaseItem> GetItemsForSync(string id, User user)
  219. {
  220. var item = _libraryManager.GetItemById(id);
  221. if (item == null)
  222. {
  223. return new List<BaseItem>();
  224. }
  225. return GetItemsForSync(item, user);
  226. }
  227. private IEnumerable<BaseItem> GetItemsForSync(BaseItem item, User user)
  228. {
  229. var itemByName = item as IItemByName;
  230. if (itemByName != null)
  231. {
  232. var items = user.RootFolder
  233. .GetRecursiveChildren(user);
  234. return itemByName.GetTaggedItems(items);
  235. }
  236. if (item.IsFolder)
  237. {
  238. var folder = (Folder)item;
  239. var items = folder.GetRecursiveChildren(user);
  240. items = items.Where(i => !i.IsFolder);
  241. if (!folder.IsPreSorted)
  242. {
  243. items = items.OrderBy(i => i.SortName);
  244. }
  245. return items;
  246. }
  247. return new[] { item };
  248. }
  249. public async Task EnsureSyncJobs(CancellationToken cancellationToken)
  250. {
  251. var jobResult = _syncRepo.GetJobs(new SyncJobQuery
  252. {
  253. IsCompleted = false
  254. });
  255. foreach (var job in jobResult.Items)
  256. {
  257. cancellationToken.ThrowIfCancellationRequested();
  258. if (job.SyncNewContent)
  259. {
  260. await EnsureJobItems(job).ConfigureAwait(false);
  261. }
  262. }
  263. }
  264. public async Task Sync(IProgress<double> progress, CancellationToken cancellationToken)
  265. {
  266. await EnsureSyncJobs(cancellationToken).ConfigureAwait(false);
  267. // If it already has a converting status then is must have been aborted during conversion
  268. var result = _syncRepo.GetJobItems(new SyncJobItemQuery
  269. {
  270. Statuses = new List<SyncJobItemStatus> { SyncJobItemStatus.Queued, SyncJobItemStatus.Converting }
  271. });
  272. var jobItems = result.Items;
  273. var index = 0;
  274. foreach (var item in jobItems)
  275. {
  276. double percent = index;
  277. percent /= result.TotalRecordCount;
  278. progress.Report(100 * percent);
  279. cancellationToken.ThrowIfCancellationRequested();
  280. var innerProgress = new ActionableProgress<double>();
  281. await ProcessJobItem(item, innerProgress, cancellationToken).ConfigureAwait(false);
  282. var job = _syncRepo.GetJob(item.JobId);
  283. await UpdateJobStatus(job).ConfigureAwait(false);
  284. index++;
  285. }
  286. }
  287. private async Task ProcessJobItem(SyncJobItem jobItem, IProgress<double> progress, CancellationToken cancellationToken)
  288. {
  289. var item = _libraryManager.GetItemById(jobItem.ItemId);
  290. if (item == null)
  291. {
  292. jobItem.Status = SyncJobItemStatus.Failed;
  293. _logger.Error("Unable to locate library item for JobItem {0}, ItemId {1}", jobItem.Id, jobItem.ItemId);
  294. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  295. return;
  296. }
  297. var deviceProfile = _syncManager.GetDeviceProfile(jobItem.TargetId);
  298. if (deviceProfile == null)
  299. {
  300. jobItem.Status = SyncJobItemStatus.Failed;
  301. _logger.Error("Unable to locate SyncTarget for JobItem {0}, SyncTargetId {1}", jobItem.Id, jobItem.TargetId);
  302. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  303. return;
  304. }
  305. jobItem.Progress = 0;
  306. jobItem.Status = SyncJobItemStatus.Converting;
  307. var video = item as Video;
  308. if (video != null)
  309. {
  310. await Sync(jobItem, video, deviceProfile, progress, cancellationToken).ConfigureAwait(false);
  311. }
  312. else if (item is Audio)
  313. {
  314. await Sync(jobItem, (Audio)item, deviceProfile, progress, cancellationToken).ConfigureAwait(false);
  315. }
  316. else if (item is Photo)
  317. {
  318. await Sync(jobItem, (Photo)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  319. }
  320. else
  321. {
  322. await SyncGeneric(jobItem, item, deviceProfile, cancellationToken).ConfigureAwait(false);
  323. }
  324. }
  325. private async Task Sync(SyncJobItem jobItem, Video item, DeviceProfile profile, IProgress<double> progress, CancellationToken cancellationToken)
  326. {
  327. var options = new VideoOptions
  328. {
  329. Context = EncodingContext.Static,
  330. ItemId = item.Id.ToString("N"),
  331. DeviceId = jobItem.TargetId,
  332. Profile = profile,
  333. MediaSources = item.GetMediaSources(false).ToList()
  334. };
  335. var streamInfo = new StreamBuilder().BuildVideoItem(options);
  336. var mediaSource = streamInfo.MediaSource;
  337. jobItem.MediaSourceId = streamInfo.MediaSourceId;
  338. if (streamInfo.PlayMethod == PlayMethod.Transcode)
  339. {
  340. jobItem.Status = SyncJobItemStatus.Converting;
  341. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  342. try
  343. {
  344. jobItem.OutputPath = await _mediaEncoder.EncodeVideo(new EncodingJobOptions(streamInfo, profile), progress,
  345. cancellationToken);
  346. }
  347. catch (OperationCanceledException)
  348. {
  349. jobItem.Status = SyncJobItemStatus.Queued;
  350. }
  351. catch (Exception ex)
  352. {
  353. jobItem.Status = SyncJobItemStatus.Failed;
  354. _logger.ErrorException("Error during sync transcoding", ex);
  355. }
  356. if (jobItem.Status == SyncJobItemStatus.Failed || jobItem.Status == SyncJobItemStatus.Queued)
  357. {
  358. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  359. return;
  360. }
  361. }
  362. else
  363. {
  364. if (mediaSource.Protocol == MediaProtocol.File)
  365. {
  366. jobItem.OutputPath = mediaSource.Path;
  367. }
  368. else if (mediaSource.Protocol == MediaProtocol.Http)
  369. {
  370. jobItem.OutputPath = await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  371. }
  372. else
  373. {
  374. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  375. }
  376. }
  377. jobItem.Progress = 50;
  378. jobItem.Status = SyncJobItemStatus.Transferring;
  379. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  380. }
  381. private async Task Sync(SyncJobItem jobItem, Audio item, DeviceProfile profile, IProgress<double> progress, CancellationToken cancellationToken)
  382. {
  383. var options = new AudioOptions
  384. {
  385. Context = EncodingContext.Static,
  386. ItemId = item.Id.ToString("N"),
  387. DeviceId = jobItem.TargetId,
  388. Profile = profile,
  389. MediaSources = item.GetMediaSources(false).ToList()
  390. };
  391. var streamInfo = new StreamBuilder().BuildAudioItem(options);
  392. var mediaSource = streamInfo.MediaSource;
  393. jobItem.MediaSourceId = streamInfo.MediaSourceId;
  394. if (streamInfo.PlayMethod == PlayMethod.Transcode)
  395. {
  396. jobItem.Status = SyncJobItemStatus.Converting;
  397. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  398. try
  399. {
  400. jobItem.OutputPath = await _mediaEncoder.EncodeAudio(new EncodingJobOptions(streamInfo, profile), progress, cancellationToken);
  401. }
  402. catch (OperationCanceledException)
  403. {
  404. jobItem.Status = SyncJobItemStatus.Queued;
  405. }
  406. catch (Exception ex)
  407. {
  408. jobItem.Status = SyncJobItemStatus.Failed;
  409. _logger.ErrorException("Error during sync transcoding", ex);
  410. }
  411. if (jobItem.Status == SyncJobItemStatus.Failed || jobItem.Status == SyncJobItemStatus.Queued)
  412. {
  413. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  414. return;
  415. }
  416. }
  417. else
  418. {
  419. if (mediaSource.Protocol == MediaProtocol.File)
  420. {
  421. jobItem.OutputPath = mediaSource.Path;
  422. }
  423. else if (mediaSource.Protocol == MediaProtocol.Http)
  424. {
  425. jobItem.OutputPath = await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  426. }
  427. else
  428. {
  429. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  430. }
  431. }
  432. jobItem.Progress = 50;
  433. jobItem.Status = SyncJobItemStatus.Transferring;
  434. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  435. }
  436. private async Task Sync(SyncJobItem jobItem, Photo item, DeviceProfile profile, CancellationToken cancellationToken)
  437. {
  438. jobItem.OutputPath = item.Path;
  439. jobItem.Progress = 50;
  440. jobItem.Status = SyncJobItemStatus.Transferring;
  441. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  442. }
  443. private async Task SyncGeneric(SyncJobItem jobItem, BaseItem item, DeviceProfile profile, CancellationToken cancellationToken)
  444. {
  445. jobItem.OutputPath = item.Path;
  446. jobItem.Progress = 50;
  447. jobItem.Status = SyncJobItemStatus.Transferring;
  448. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  449. }
  450. private async Task<string> DownloadFile(SyncJobItem jobItem, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  451. {
  452. // TODO: Download
  453. return mediaSource.Path;
  454. }
  455. }
  456. }