MediaSync.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Sync;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Sync;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Sync
  19. {
  20. public class MediaSync
  21. {
  22. private readonly ISyncManager _syncManager;
  23. private readonly IServerApplicationHost _appHost;
  24. private readonly ILogger _logger;
  25. private readonly IFileSystem _fileSystem;
  26. public MediaSync(ILogger logger, ISyncManager syncManager, IServerApplicationHost appHost, IFileSystem fileSystem)
  27. {
  28. _logger = logger;
  29. _syncManager = syncManager;
  30. _appHost = appHost;
  31. _fileSystem = fileSystem;
  32. }
  33. public async Task Sync(IServerSyncProvider provider,
  34. ISyncDataProvider dataProvider,
  35. SyncTarget target,
  36. IProgress<double> progress,
  37. CancellationToken cancellationToken)
  38. {
  39. var serverId = _appHost.SystemId;
  40. await SyncData(provider, dataProvider, serverId, target, cancellationToken).ConfigureAwait(false);
  41. progress.Report(3);
  42. var innerProgress = new ActionableProgress<double>();
  43. innerProgress.RegisterAction(pct =>
  44. {
  45. var totalProgress = pct * .97;
  46. totalProgress += 1;
  47. progress.Report(totalProgress);
  48. });
  49. await GetNewMedia(provider, dataProvider, target, serverId, innerProgress, cancellationToken);
  50. // Do the data sync twice so the server knows what was removed from the device
  51. await SyncData(provider, dataProvider, serverId, target, cancellationToken).ConfigureAwait(false);
  52. progress.Report(100);
  53. }
  54. private async Task SyncData(IServerSyncProvider provider,
  55. ISyncDataProvider dataProvider,
  56. string serverId,
  57. SyncTarget target,
  58. CancellationToken cancellationToken)
  59. {
  60. var localIds = await dataProvider.GetServerItemIds(target, serverId).ConfigureAwait(false);
  61. var result = await _syncManager.SyncData(new SyncDataRequest
  62. {
  63. TargetId = target.Id,
  64. LocalItemIds = localIds
  65. }).ConfigureAwait(false);
  66. cancellationToken.ThrowIfCancellationRequested();
  67. foreach (var itemIdToRemove in result.ItemIdsToRemove)
  68. {
  69. try
  70. {
  71. await RemoveItem(provider, dataProvider, serverId, itemIdToRemove, target, cancellationToken).ConfigureAwait(false);
  72. }
  73. catch (Exception ex)
  74. {
  75. _logger.ErrorException("Error deleting item from device. Id: {0}", ex, itemIdToRemove);
  76. }
  77. }
  78. }
  79. private async Task GetNewMedia(IServerSyncProvider provider,
  80. ISyncDataProvider dataProvider,
  81. SyncTarget target,
  82. string serverId,
  83. IProgress<double> progress,
  84. CancellationToken cancellationToken)
  85. {
  86. var jobItems = await _syncManager.GetReadySyncItems(target.Id).ConfigureAwait(false);
  87. var numComplete = 0;
  88. double startingPercent = 0;
  89. double percentPerItem = 1;
  90. if (jobItems.Count > 0)
  91. {
  92. percentPerItem /= jobItems.Count;
  93. }
  94. foreach (var jobItem in jobItems)
  95. {
  96. cancellationToken.ThrowIfCancellationRequested();
  97. var currentPercent = startingPercent;
  98. var innerProgress = new ActionableProgress<double>();
  99. innerProgress.RegisterAction(pct =>
  100. {
  101. var totalProgress = pct * percentPerItem;
  102. totalProgress += currentPercent;
  103. progress.Report(totalProgress);
  104. });
  105. await GetItem(provider, dataProvider, target, serverId, jobItem, innerProgress, cancellationToken).ConfigureAwait(false);
  106. numComplete++;
  107. startingPercent = numComplete;
  108. startingPercent /= jobItems.Count;
  109. startingPercent *= 100;
  110. progress.Report(startingPercent);
  111. }
  112. }
  113. private async Task GetItem(IServerSyncProvider provider,
  114. ISyncDataProvider dataProvider,
  115. SyncTarget target,
  116. string serverId,
  117. SyncedItem jobItem,
  118. IProgress<double> progress,
  119. CancellationToken cancellationToken)
  120. {
  121. var libraryItem = jobItem.Item;
  122. var internalSyncJobItem = _syncManager.GetJobItem(jobItem.SyncJobItemId);
  123. var fileTransferProgress = new ActionableProgress<double>();
  124. fileTransferProgress.RegisterAction(pct => progress.Report(pct * .92));
  125. var localItem = CreateLocalItem(provider, jobItem.SyncJobId, jobItem.SyncJobItemId, target, libraryItem, serverId, jobItem.OriginalFileName);
  126. await _syncManager.ReportSyncJobItemTransferBeginning(internalSyncJobItem.Id);
  127. var transferSuccess = false;
  128. Exception transferException = null;
  129. try
  130. {
  131. var sendFileResult = await SendFile(provider, internalSyncJobItem.OutputPath, localItem, target, cancellationToken).ConfigureAwait(false);
  132. if (localItem.Item.MediaSources != null)
  133. {
  134. var mediaSource = localItem.Item.MediaSources.FirstOrDefault();
  135. if (mediaSource != null)
  136. {
  137. mediaSource.Path = sendFileResult.Path;
  138. mediaSource.Protocol = sendFileResult.Protocol;
  139. mediaSource.SupportsTranscoding = false;
  140. }
  141. }
  142. // Create db record
  143. await dataProvider.AddOrUpdate(target, localItem).ConfigureAwait(false);
  144. if (localItem.Item.MediaSources != null)
  145. {
  146. var mediaSource = localItem.Item.MediaSources.FirstOrDefault();
  147. if (mediaSource != null)
  148. {
  149. mediaSource.Path = sendFileResult.Path;
  150. mediaSource.Protocol = sendFileResult.Protocol;
  151. mediaSource.SupportsTranscoding = false;
  152. }
  153. }
  154. progress.Report(92);
  155. transferSuccess = true;
  156. progress.Report(99);
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.ErrorException("Error transferring sync job file", ex);
  161. transferException = ex;
  162. }
  163. if (transferSuccess)
  164. {
  165. await _syncManager.ReportSyncJobItemTransferred(jobItem.SyncJobItemId).ConfigureAwait(false);
  166. }
  167. else
  168. {
  169. await _syncManager.ReportSyncJobItemTransferFailed(jobItem.SyncJobItemId).ConfigureAwait(false);
  170. throw transferException;
  171. }
  172. }
  173. private async Task SendSubtitles(LocalItem localItem, MediaSourceInfo mediaSource, IServerSyncProvider provider, ISyncDataProvider dataProvider, SyncTarget target, CancellationToken cancellationToken)
  174. {
  175. foreach (var mediaStream in mediaSource.MediaStreams
  176. .Where(i => i.Type == MediaStreamType.Subtitle && i.IsExternal)
  177. .ToList())
  178. {
  179. var sendFileResult = await SendFile(provider, mediaStream.Path, localItem, target, cancellationToken).ConfigureAwait(false);
  180. mediaStream.Path = sendFileResult.Path;
  181. await dataProvider.AddOrUpdate(target, localItem).ConfigureAwait(false);
  182. }
  183. }
  184. private async Task RemoveItem(IServerSyncProvider provider,
  185. ISyncDataProvider dataProvider,
  186. string serverId,
  187. string itemId,
  188. SyncTarget target,
  189. CancellationToken cancellationToken)
  190. {
  191. var localItems = await dataProvider.GetCachedItems(target, serverId, itemId);
  192. foreach (var localItem in localItems)
  193. {
  194. var files = await GetFiles(provider, localItem, target, cancellationToken);
  195. foreach (var file in files)
  196. {
  197. await provider.DeleteFile(file.Path, target, cancellationToken).ConfigureAwait(false);
  198. }
  199. await dataProvider.Delete(target, localItem.Id).ConfigureAwait(false);
  200. }
  201. }
  202. private async Task<SendFileResult> SendFile(IServerSyncProvider provider, string inputPath, LocalItem item, SyncTarget target, CancellationToken cancellationToken)
  203. {
  204. _logger.Debug("Sending {0} to {1}. Remote path: {2}", inputPath, provider.Name, item.LocalPath);
  205. using (var stream = _fileSystem.GetFileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  206. {
  207. return await provider.SendFile(stream, item.LocalPath, target, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  208. }
  209. }
  210. private static string GetLocalId(string jobItemId, string itemId)
  211. {
  212. var bytes = Encoding.UTF8.GetBytes(jobItemId + itemId);
  213. bytes = CreateMd5(bytes);
  214. return BitConverter.ToString(bytes, 0, bytes.Length).Replace("-", string.Empty);
  215. }
  216. private static byte[] CreateMd5(byte[] value)
  217. {
  218. using (var provider = MD5.Create())
  219. {
  220. return provider.ComputeHash(value);
  221. }
  222. }
  223. public LocalItem CreateLocalItem(IServerSyncProvider provider, string syncJobId, string syncJobItemId, SyncTarget target, BaseItemDto libraryItem, string serverId, string originalFileName)
  224. {
  225. var path = GetDirectoryPath(provider, syncJobId, libraryItem, serverId);
  226. path.Add(GetLocalFileName(provider, libraryItem, originalFileName));
  227. var localPath = provider.GetFullPath(path, target);
  228. foreach (var mediaSource in libraryItem.MediaSources)
  229. {
  230. mediaSource.Path = localPath;
  231. mediaSource.Protocol = MediaProtocol.File;
  232. }
  233. return new LocalItem
  234. {
  235. Item = libraryItem,
  236. ItemId = libraryItem.Id,
  237. ServerId = serverId,
  238. LocalPath = localPath,
  239. Id = GetLocalId(syncJobItemId, libraryItem.Id)
  240. };
  241. }
  242. private List<string> GetDirectoryPath(IServerSyncProvider provider, string syncJobId, BaseItemDto item, string serverId)
  243. {
  244. var parts = new List<string>
  245. {
  246. serverId,
  247. syncJobId
  248. };
  249. if (item.IsType("episode"))
  250. {
  251. parts.Add("TV");
  252. if (!string.IsNullOrWhiteSpace(item.SeriesName))
  253. {
  254. parts.Add(item.SeriesName);
  255. }
  256. }
  257. else if (item.IsVideo)
  258. {
  259. parts.Add("Videos");
  260. parts.Add(item.Name);
  261. }
  262. else if (item.IsAudio)
  263. {
  264. parts.Add("Music");
  265. if (!string.IsNullOrWhiteSpace(item.AlbumArtist))
  266. {
  267. parts.Add(item.AlbumArtist);
  268. }
  269. if (!string.IsNullOrWhiteSpace(item.Album))
  270. {
  271. parts.Add(item.Album);
  272. }
  273. }
  274. else if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
  275. {
  276. parts.Add("Photos");
  277. if (!string.IsNullOrWhiteSpace(item.Album))
  278. {
  279. parts.Add(item.Album);
  280. }
  281. }
  282. return parts.Select(i => GetValidFilename(provider, i)).ToList();
  283. }
  284. private string GetLocalFileName(IServerSyncProvider provider, BaseItemDto item, string originalFileName)
  285. {
  286. var filename = originalFileName;
  287. if (string.IsNullOrWhiteSpace(filename))
  288. {
  289. filename = item.Name;
  290. }
  291. return GetValidFilename(provider, filename);
  292. }
  293. private string GetValidFilename(IServerSyncProvider provider, string filename)
  294. {
  295. // We can always add this method to the sync provider if it's really needed
  296. return _fileSystem.GetValidFilename(filename);
  297. }
  298. private async Task<List<ItemFileInfo>> GetFiles(IServerSyncProvider provider, LocalItem item, SyncTarget target, CancellationToken cancellationToken)
  299. {
  300. var path = item.LocalPath;
  301. path = provider.GetParentDirectoryPath(path, target);
  302. var list = await provider.GetFileSystemEntries(path, target, cancellationToken).ConfigureAwait(false);
  303. var itemFiles = new List<ItemFileInfo>();
  304. var name = Path.GetFileNameWithoutExtension(item.LocalPath);
  305. foreach (var file in list.Where(f => f.Name.Contains(name)))
  306. {
  307. var itemFile = new ItemFileInfo
  308. {
  309. Path = file.Path,
  310. Name = file.Name
  311. };
  312. if (IsSubtitleFile(file.Name))
  313. {
  314. itemFile.Type = ItemFileType.Subtitles;
  315. }
  316. itemFiles.Add(itemFile);
  317. }
  318. return itemFiles;
  319. }
  320. private static readonly string[] SupportedSubtitleExtensions = { ".srt", ".vtt" };
  321. private bool IsSubtitleFile(string path)
  322. {
  323. var ext = Path.GetExtension(path) ?? string.Empty;
  324. return SupportedSubtitleExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  325. }
  326. }
  327. }