SyncJobProcessor.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. var itemId = item.Id.ToString("N");
  53. var jobItem = jobItems.FirstOrDefault(i => string.Equals(i.ItemId, itemId, StringComparison.OrdinalIgnoreCase));
  54. if (jobItem != null)
  55. {
  56. continue;
  57. }
  58. jobItem = new SyncJobItem
  59. {
  60. Id = Guid.NewGuid().ToString("N"),
  61. ItemId = itemId,
  62. JobId = job.Id,
  63. TargetId = job.TargetId,
  64. DateCreated = DateTime.UtcNow
  65. };
  66. await _syncRepo.Create(jobItem).ConfigureAwait(false);
  67. jobItems.Add(jobItem);
  68. }
  69. jobItems = jobItems
  70. .OrderBy(i => i.DateCreated)
  71. .ToList();
  72. await UpdateJobStatus(job, jobItems).ConfigureAwait(false);
  73. }
  74. private Task UpdateJobStatus(SyncJob job)
  75. {
  76. if (job == null)
  77. {
  78. throw new ArgumentNullException("job");
  79. }
  80. var result = _syncRepo.GetJobItems(new SyncJobItemQuery
  81. {
  82. JobId = job.Id
  83. });
  84. return UpdateJobStatus(job, result.Items.ToList());
  85. }
  86. private Task UpdateJobStatus(SyncJob job, List<SyncJobItem> jobItems)
  87. {
  88. job.ItemCount = jobItems.Count;
  89. double pct = 0;
  90. foreach (var item in jobItems)
  91. {
  92. if (item.Status == SyncJobItemStatus.Failed || item.Status == SyncJobItemStatus.Completed)
  93. {
  94. pct += 100;
  95. }
  96. else
  97. {
  98. pct += item.Progress ?? 0;
  99. }
  100. }
  101. if (job.ItemCount > 0)
  102. {
  103. pct /= job.ItemCount;
  104. job.Progress = pct;
  105. }
  106. else
  107. {
  108. job.Progress = null;
  109. }
  110. if (pct >= 100)
  111. {
  112. if (jobItems.Any(i => i.Status == SyncJobItemStatus.Failed))
  113. {
  114. job.Status = SyncJobStatus.CompletedWithError;
  115. }
  116. else
  117. {
  118. job.Status = SyncJobStatus.Completed;
  119. }
  120. }
  121. else if (pct.Equals(0))
  122. {
  123. job.Status = SyncJobStatus.Queued;
  124. }
  125. else
  126. {
  127. job.Status = SyncJobStatus.InProgress;
  128. }
  129. return _syncRepo.Update(job);
  130. }
  131. public IEnumerable<BaseItem> GetItemsForSync(IEnumerable<string> itemIds, User user)
  132. {
  133. return itemIds
  134. .SelectMany(i => GetItemsForSync(i, user))
  135. .Where(_syncManager.SupportsSync)
  136. .DistinctBy(i => i.Id);
  137. }
  138. private IEnumerable<BaseItem> GetItemsForSync(string id, User user)
  139. {
  140. var item = _libraryManager.GetItemById(id);
  141. if (item == null)
  142. {
  143. return new List<BaseItem>();
  144. }
  145. return GetItemsForSync(item, user);
  146. }
  147. private IEnumerable<BaseItem> GetItemsForSync(BaseItem item, User user)
  148. {
  149. var itemByName = item as IItemByName;
  150. if (itemByName != null)
  151. {
  152. var items = user.RootFolder
  153. .GetRecursiveChildren(user);
  154. return itemByName.GetTaggedItems(items);
  155. }
  156. if (item.IsFolder)
  157. {
  158. var folder = (Folder)item;
  159. var items = folder.GetRecursiveChildren(user);
  160. items = items.Where(i => !i.IsFolder);
  161. if (!folder.IsPreSorted)
  162. {
  163. items = items.OrderBy(i => i.SortName);
  164. }
  165. return items;
  166. }
  167. return new[] { item };
  168. }
  169. public async Task EnsureSyncJobs(CancellationToken cancellationToken)
  170. {
  171. var jobResult = _syncRepo.GetJobs(new SyncJobQuery
  172. {
  173. IsCompleted = false
  174. });
  175. foreach (var job in jobResult.Items)
  176. {
  177. cancellationToken.ThrowIfCancellationRequested();
  178. if (job.SyncNewContent)
  179. {
  180. await EnsureJobItems(job).ConfigureAwait(false);
  181. }
  182. }
  183. }
  184. public async Task Sync(IProgress<double> progress, CancellationToken cancellationToken)
  185. {
  186. await EnsureSyncJobs(cancellationToken).ConfigureAwait(false);
  187. var result = _syncRepo.GetJobItems(new SyncJobItemQuery
  188. {
  189. IsCompleted = false
  190. });
  191. var jobItems = result.Items;
  192. var index = 0;
  193. foreach (var item in jobItems)
  194. {
  195. double percent = index;
  196. percent /= result.TotalRecordCount;
  197. progress.Report(100 * percent);
  198. cancellationToken.ThrowIfCancellationRequested();
  199. if (item.Status == SyncJobItemStatus.Queued)
  200. {
  201. await ProcessJobItem(item, cancellationToken).ConfigureAwait(false);
  202. }
  203. var job = _syncRepo.GetJob(item.JobId);
  204. await UpdateJobStatus(job).ConfigureAwait(false);
  205. index++;
  206. }
  207. }
  208. private async Task ProcessJobItem(SyncJobItem jobItem, CancellationToken cancellationToken)
  209. {
  210. var item = _libraryManager.GetItemById(jobItem.ItemId);
  211. if (item == null)
  212. {
  213. jobItem.Status = SyncJobItemStatus.Failed;
  214. _logger.Error("Unable to locate library item for JobItem {0}, ItemId {1}", jobItem.Id, jobItem.ItemId);
  215. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  216. return;
  217. }
  218. var deviceProfile = _syncManager.GetDeviceProfile(jobItem.TargetId);
  219. if (deviceProfile == null)
  220. {
  221. jobItem.Status = SyncJobItemStatus.Failed;
  222. _logger.Error("Unable to locate SyncTarget for JobItem {0}, SyncTargetId {1}", jobItem.Id, jobItem.TargetId);
  223. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  224. return;
  225. }
  226. jobItem.Progress = 0;
  227. jobItem.Status = SyncJobItemStatus.Converting;
  228. var video = item as Video;
  229. if (video != null)
  230. {
  231. jobItem.OutputPath = await Sync(jobItem, video, deviceProfile, cancellationToken).ConfigureAwait(false);
  232. }
  233. else if (item is Audio)
  234. {
  235. jobItem.OutputPath = await Sync(jobItem, (Audio)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  236. }
  237. else if (item is Photo)
  238. {
  239. jobItem.OutputPath = await Sync(jobItem, (Photo)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  240. }
  241. else if (item is Game)
  242. {
  243. jobItem.OutputPath = await Sync(jobItem, (Game)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  244. }
  245. else if (item is Book)
  246. {
  247. jobItem.OutputPath = await Sync(jobItem, (Book)item, deviceProfile, cancellationToken).ConfigureAwait(false);
  248. }
  249. jobItem.Progress = 50;
  250. jobItem.Status = SyncJobItemStatus.Transferring;
  251. await _syncRepo.Update(jobItem).ConfigureAwait(false);
  252. }
  253. private async Task<string> Sync(SyncJobItem jobItem, Video item, DeviceProfile profile, CancellationToken cancellationToken)
  254. {
  255. var options = new VideoOptions
  256. {
  257. Context = EncodingContext.Streaming,
  258. ItemId = item.Id.ToString("N"),
  259. DeviceId = jobItem.TargetId,
  260. Profile = profile,
  261. MediaSources = item.GetMediaSources(false).ToList()
  262. };
  263. var streamInfo = new StreamBuilder().BuildVideoItem(options);
  264. var mediaSource = streamInfo.MediaSource;
  265. if (streamInfo.PlayMethod != PlayMethod.Transcode)
  266. {
  267. if (mediaSource.Protocol == MediaProtocol.File)
  268. {
  269. return mediaSource.Path;
  270. }
  271. if (mediaSource.Protocol == MediaProtocol.Http)
  272. {
  273. return await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  274. }
  275. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  276. }
  277. // TODO: Transcode
  278. return mediaSource.Path;
  279. }
  280. private async Task<string> Sync(SyncJobItem jobItem, Audio item, DeviceProfile profile, CancellationToken cancellationToken)
  281. {
  282. var options = new AudioOptions
  283. {
  284. Context = EncodingContext.Streaming,
  285. ItemId = item.Id.ToString("N"),
  286. DeviceId = jobItem.TargetId,
  287. Profile = profile,
  288. MediaSources = item.GetMediaSources(false).ToList()
  289. };
  290. var streamInfo = new StreamBuilder().BuildAudioItem(options);
  291. var mediaSource = streamInfo.MediaSource;
  292. if (streamInfo.PlayMethod != PlayMethod.Transcode)
  293. {
  294. if (mediaSource.Protocol == MediaProtocol.File)
  295. {
  296. return mediaSource.Path;
  297. }
  298. if (mediaSource.Protocol == MediaProtocol.Http)
  299. {
  300. return await DownloadFile(jobItem, mediaSource, cancellationToken).ConfigureAwait(false);
  301. }
  302. throw new InvalidOperationException(string.Format("Cannot direct stream {0} protocol", mediaSource.Protocol));
  303. }
  304. // TODO: Transcode
  305. return mediaSource.Path;
  306. }
  307. private async Task<string> Sync(SyncJobItem jobItem, Photo item, DeviceProfile profile, CancellationToken cancellationToken)
  308. {
  309. return item.Path;
  310. }
  311. private async Task<string> Sync(SyncJobItem jobItem, Game item, DeviceProfile profile, CancellationToken cancellationToken)
  312. {
  313. return item.Path;
  314. }
  315. private async Task<string> Sync(SyncJobItem jobItem, Book item, DeviceProfile profile, CancellationToken cancellationToken)
  316. {
  317. return item.Path;
  318. }
  319. private async Task<string> DownloadFile(SyncJobItem jobItem, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  320. {
  321. // TODO: Download
  322. return mediaSource.Path;
  323. }
  324. }
  325. }