2
0

SyncJobProcessor.cs 17 KB

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