SyncJobProcessor.cs 14 KB

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