SyncJobProcessor.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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)
  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)
  145. {
  146. return itemIds
  147. .SelectMany(i => GetItemsForSync(i, user))
  148. .Where(_syncManager.SupportsSync)
  149. .DistinctBy(i => i.Id);
  150. }
  151. private IEnumerable<BaseItem> GetItemsForSync(string id, User user)
  152. {
  153. var item = _libraryManager.GetItemById(id);
  154. if (item == null)
  155. {
  156. return new List<BaseItem>();
  157. }
  158. return GetItemsForSync(item, user);
  159. }
  160. private IEnumerable<BaseItem> GetItemsForSync(BaseItem item, User user)
  161. {
  162. var itemByName = item as IItemByName;
  163. if (itemByName != null)
  164. {
  165. var items = user.RootFolder
  166. .GetRecursiveChildren(user);
  167. return itemByName.GetTaggedItems(items);
  168. }
  169. if (item.IsFolder)
  170. {
  171. var folder = (Folder)item;
  172. var items = folder.GetRecursiveChildren(user);
  173. items = items.Where(i => !i.IsFolder);
  174. if (!folder.IsPreSorted)
  175. {
  176. items = items.OrderBy(i => i.SortName);
  177. }
  178. return items;
  179. }
  180. return new[] { item };
  181. }
  182. public async Task EnsureSyncJobs(CancellationToken cancellationToken)
  183. {
  184. var jobResult = _syncRepo.GetJobs(new SyncJobQuery
  185. {
  186. IsCompleted = false
  187. });
  188. foreach (var job in jobResult.Items)
  189. {
  190. cancellationToken.ThrowIfCancellationRequested();
  191. if (job.SyncNewContent)
  192. {
  193. await EnsureJobItems(job).ConfigureAwait(false);
  194. }
  195. }
  196. }
  197. public async Task Sync(IProgress<double> progress, CancellationToken cancellationToken)
  198. {
  199. await EnsureSyncJobs(cancellationToken).ConfigureAwait(false);
  200. var result = _syncRepo.GetJobItems(new SyncJobItemQuery
  201. {
  202. IsCompleted = false
  203. });
  204. var jobItems = result.Items;
  205. var index = 0;
  206. foreach (var item in jobItems)
  207. {
  208. double percent = index;
  209. percent /= result.TotalRecordCount;
  210. progress.Report(100 * percent);
  211. cancellationToken.ThrowIfCancellationRequested();
  212. if (item.Status == SyncJobItemStatus.Queued)
  213. {
  214. await ProcessJobItem(item, cancellationToken).ConfigureAwait(false);
  215. }
  216. var job = _syncRepo.GetJob(item.JobId);
  217. await UpdateJobStatus(job).ConfigureAwait(false);
  218. index++;
  219. }
  220. }
  221. private async Task ProcessJobItem(SyncJobItem jobItem, CancellationToken cancellationToken)
  222. {
  223. var item = _libraryManager.GetItemById(jobItem.ItemId);
  224. if (item == null)
  225. {
  226. jobItem.Status = SyncJobItemStatus.Failed;
  227. _logger.Error("Unable to locate library item for JobItem {0}, ItemId {1}", jobItem.Id, jobItem.ItemId);
  228. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  229. return;
  230. }
  231. var deviceProfile = _syncManager.GetDeviceProfile(jobItem.TargetId);
  232. if (deviceProfile == null)
  233. {
  234. jobItem.Status = SyncJobItemStatus.Failed;
  235. _logger.Error("Unable to locate SyncTarget for JobItem {0}, SyncTargetId {1}", jobItem.Id, jobItem.TargetId);
  236. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  237. return;
  238. }
  239. jobItem.Progress = 0;
  240. jobItem.Status = SyncJobItemStatus.Converting;
  241. var video = item as Video;
  242. if (video != null)
  243. {
  244. jobItem.OutputPath = await Sync(jobItem, video, deviceProfile, cancellationToken).ConfigureAwait(false);
  245. }
  246. else if (item is Audio)
  247. {
  248. jobItem.OutputPath = await Sync(jobItem, (Audio)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  249. }
  250. else if (item is Photo)
  251. {
  252. jobItem.OutputPath = await Sync(jobItem, (Photo)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  253. }
  254. else if (item is Game)
  255. {
  256. jobItem.OutputPath = await Sync(jobItem, (Game)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  257. }
  258. else if (item is Book)
  259. {
  260. jobItem.OutputPath = await Sync(jobItem, (Book)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  261. }
  262. jobItem.Progress = 50;
  263. jobItem.Status = SyncJobItemStatus.Transferring;
  264. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  265. }
  266. private async Task<string> Sync(SyncJobItem jobItem, Video item, DeviceProfile profile, CancellationToken cancellationToken)
  267. {
  268. var options = new VideoOptions
  269. {
  270. Context = EncodingContext.Streaming,
  271. ItemId = item.Id.ToString("N"),
  272. DeviceId = jobItem.TargetId,
  273. Profile = profile,
  274. MediaSources = item.GetMediaSources(false).ToList()
  275. };
  276. var streamInfo = new StreamBuilder().BuildVideoItem(options);
  277. var mediaSource = streamInfo.MediaSource;
  278. if (streamInfo.PlayMethod != PlayMethod.Transcode)
  279. {
  280. if (mediaSource.Protocol == MediaProtocol.File)
  281. {
  282. return mediaSource.Path;
  283. }
  284. if (mediaSource.Protocol == MediaProtocol.Http)
  285. {
  286. return await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  287. }
  288. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  289. }
  290. // TODO: Transcode
  291. return mediaSource.Path;
  292. }
  293. private async Task<string> Sync(SyncJobItem jobItem, Audio item, DeviceProfile profile, CancellationToken cancellationToken)
  294. {
  295. var options = new AudioOptions
  296. {
  297. Context = EncodingContext.Streaming,
  298. ItemId = item.Id.ToString("N"),
  299. DeviceId = jobItem.TargetId,
  300. Profile = profile,
  301. MediaSources = item.GetMediaSources(false).ToList()
  302. };
  303. var streamInfo = new StreamBuilder().BuildAudioItem(options);
  304. var mediaSource = streamInfo.MediaSource;
  305. if (streamInfo.PlayMethod != PlayMethod.Transcode)
  306. {
  307. if (mediaSource.Protocol == MediaProtocol.File)
  308. {
  309. return mediaSource.Path;
  310. }
  311. if (mediaSource.Protocol == MediaProtocol.Http)
  312. {
  313. return await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  314. }
  315. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  316. }
  317. // TODO: Transcode
  318. return mediaSource.Path;
  319. }
  320. private async Task<string> Sync(SyncJobItem jobItem, Photo item, DeviceProfile profile, CancellationToken cancellationToken)
  321. {
  322. return item.Path;
  323. }
  324. private async Task<string> Sync(SyncJobItem jobItem, Game item, DeviceProfile profile, CancellationToken cancellationToken)
  325. {
  326. return item.Path;
  327. }
  328. private async Task<string> Sync(SyncJobItem jobItem, Book item, DeviceProfile profile, CancellationToken cancellationToken)
  329. {
  330. return item.Path;
  331. }
  332. private async Task<string> DownloadFile(SyncJobItem jobItem, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  333. {
  334. // TODO: Download
  335. return mediaSource.Path;
  336. }
  337. }
  338. }