LiveTvManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.Localization;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.LiveTv;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.Querying;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.LiveTv
  21. {
  22. /// <summary>
  23. /// Class LiveTvManager
  24. /// </summary>
  25. public class LiveTvManager : ILiveTvManager
  26. {
  27. private readonly IServerApplicationPaths _appPaths;
  28. private readonly IFileSystem _fileSystem;
  29. private readonly ILogger _logger;
  30. private readonly IItemRepository _itemRepo;
  31. private readonly IUserManager _userManager;
  32. private readonly ILocalizationManager _localization;
  33. private readonly LiveTvDtoService _tvDtoService;
  34. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  35. private List<Channel> _channels = new List<Channel>();
  36. private List<ProgramInfoDto> _programs = new List<ProgramInfoDto>();
  37. public LiveTvManager(IServerApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, ILocalizationManager localization, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager)
  38. {
  39. _appPaths = appPaths;
  40. _fileSystem = fileSystem;
  41. _logger = logger;
  42. _itemRepo = itemRepo;
  43. _localization = localization;
  44. _userManager = userManager;
  45. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger);
  46. }
  47. /// <summary>
  48. /// Gets the services.
  49. /// </summary>
  50. /// <value>The services.</value>
  51. public IReadOnlyList<ILiveTvService> Services
  52. {
  53. get { return _services; }
  54. }
  55. public ILiveTvService ActiveService { get; private set; }
  56. /// <summary>
  57. /// Adds the parts.
  58. /// </summary>
  59. /// <param name="services">The services.</param>
  60. public void AddParts(IEnumerable<ILiveTvService> services)
  61. {
  62. _services.AddRange(services);
  63. ActiveService = _services.FirstOrDefault();
  64. }
  65. public Task<QueryResult<ChannelInfoDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
  66. {
  67. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  68. IEnumerable<Channel> channels = _channels;
  69. if (user != null)
  70. {
  71. channels = channels.Where(i => i.IsParentalAllowed(user, _localization))
  72. .OrderBy(i =>
  73. {
  74. double number = 0;
  75. if (!string.IsNullOrEmpty(i.ChannelNumber))
  76. {
  77. double.TryParse(i.ChannelNumber, out number);
  78. }
  79. return number;
  80. });
  81. }
  82. var returnChannels = channels.OrderBy(i =>
  83. {
  84. double number = 0;
  85. if (!string.IsNullOrEmpty(i.ChannelNumber))
  86. {
  87. double.TryParse(i.ChannelNumber, out number);
  88. }
  89. return number;
  90. }).ThenBy(i => i.Name)
  91. .Select(i => _tvDtoService.GetChannelInfoDto(i, user))
  92. .ToArray();
  93. var result = new QueryResult<ChannelInfoDto>
  94. {
  95. Items = returnChannels,
  96. TotalRecordCount = returnChannels.Length
  97. };
  98. return Task.FromResult(result);
  99. }
  100. public Channel GetChannel(string id)
  101. {
  102. var guid = new Guid(id);
  103. return _channels.FirstOrDefault(i => i.Id == guid);
  104. }
  105. private async Task<Channel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  106. {
  107. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(serviceName), _fileSystem.GetValidFilename(channelInfo.Name));
  108. var fileInfo = new DirectoryInfo(path);
  109. var isNew = false;
  110. if (!fileInfo.Exists)
  111. {
  112. Directory.CreateDirectory(path);
  113. fileInfo = new DirectoryInfo(path);
  114. if (!fileInfo.Exists)
  115. {
  116. throw new IOException("Path not created: " + path);
  117. }
  118. isNew = true;
  119. }
  120. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id, channelInfo.Name);
  121. var item = _itemRepo.RetrieveItem(id) as Channel;
  122. if (item == null)
  123. {
  124. item = new Channel
  125. {
  126. Name = channelInfo.Name,
  127. Id = id,
  128. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  129. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  130. Path = path,
  131. ChannelId = channelInfo.Id,
  132. ChannelNumber = channelInfo.Number,
  133. ServiceName = serviceName,
  134. HasProviderImage = channelInfo.HasImage
  135. };
  136. isNew = true;
  137. }
  138. // Set this now so we don't cause additional file system access during provider executions
  139. item.ResetResolveArgs(fileInfo);
  140. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  141. return item;
  142. }
  143. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  144. {
  145. IEnumerable<ProgramInfoDto> programs = _programs
  146. .OrderBy(i => i.StartDate)
  147. .ThenBy(i => i.EndDate);
  148. if (query.ChannelIdList.Length > 0)
  149. {
  150. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  151. programs = programs.Where(i => guids.Contains(new Guid(i.ChannelId)));
  152. }
  153. var returnArray = programs.ToArray();
  154. return new QueryResult<ProgramInfoDto>
  155. {
  156. Items = returnArray,
  157. TotalRecordCount = returnArray.Length
  158. };
  159. }
  160. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  161. {
  162. // Avoid implicitly captured closure
  163. var service = ActiveService;
  164. if (service == null)
  165. {
  166. progress.Report(100);
  167. return;
  168. }
  169. progress.Report(10);
  170. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  171. var allChannelsList = allChannels.ToList();
  172. var list = new List<Channel>();
  173. var programs = new List<ProgramInfoDto>();
  174. var numComplete = 0;
  175. foreach (var channelInfo in allChannelsList)
  176. {
  177. try
  178. {
  179. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  180. var channelPrograms = await service.GetProgramsAsync(channelInfo.Item2.Id, cancellationToken).ConfigureAwait(false);
  181. programs.AddRange(channelPrograms.Select(program => _tvDtoService.GetProgramInfoDto(program, item)));
  182. list.Add(item);
  183. }
  184. catch (OperationCanceledException)
  185. {
  186. throw;
  187. }
  188. catch (Exception ex)
  189. {
  190. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  191. }
  192. numComplete++;
  193. double percent = numComplete;
  194. percent /= allChannelsList.Count;
  195. progress.Report(90 * percent + 10);
  196. }
  197. _programs = programs;
  198. _channels = list;
  199. }
  200. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  201. {
  202. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  203. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  204. }
  205. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  206. {
  207. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  208. var list = new List<RecordingInfoDto>();
  209. if (ActiveService != null)
  210. {
  211. var recordings = await ActiveService.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  212. var dtos = recordings.Select(i => _tvDtoService.GetRecordingInfoDto(i, ActiveService, user));
  213. list.AddRange(dtos);
  214. }
  215. if (!string.IsNullOrEmpty(query.ChannelId))
  216. {
  217. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  218. .ToList();
  219. }
  220. var returnArray = list.OrderByDescending(i => i.StartDate)
  221. .ToArray();
  222. return new QueryResult<RecordingInfoDto>
  223. {
  224. Items = returnArray,
  225. TotalRecordCount = returnArray.Length
  226. };
  227. }
  228. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  229. {
  230. IEnumerable<ILiveTvService> services = _services;
  231. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  232. {
  233. var channelIdGuid = new Guid(channelId);
  234. serviceName = _channels.Where(i => i.Id == channelIdGuid)
  235. .Select(i => i.ServiceName)
  236. .FirstOrDefault();
  237. }
  238. if (!string.IsNullOrEmpty(serviceName))
  239. {
  240. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  241. }
  242. return services;
  243. }
  244. public Task ScheduleRecording(string programId)
  245. {
  246. throw new NotImplementedException();
  247. }
  248. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  249. {
  250. var list = new List<TimerInfoDto>();
  251. if (ActiveService != null)
  252. {
  253. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  254. var dtos = timers.Select(i => _tvDtoService.GetTimerInfoDto(i, ActiveService));
  255. list.AddRange(dtos);
  256. }
  257. if (!string.IsNullOrEmpty(query.ChannelId))
  258. {
  259. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  260. .ToList();
  261. }
  262. var returnArray = list.OrderByDescending(i => i.StartDate)
  263. .ToArray();
  264. return new QueryResult<TimerInfoDto>
  265. {
  266. Items = returnArray,
  267. TotalRecordCount = returnArray.Length
  268. };
  269. }
  270. public async Task DeleteRecording(string recordingId)
  271. {
  272. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  273. if (recording == null)
  274. {
  275. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  276. }
  277. var service = GetServices(recording.ServiceName, null)
  278. .First();
  279. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  280. }
  281. public async Task CancelTimer(string id)
  282. {
  283. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  284. if (timer == null)
  285. {
  286. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  287. }
  288. var service = GetServices(timer.ServiceName, null)
  289. .First();
  290. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  291. }
  292. public async Task CancelSeriesTimer(string id)
  293. {
  294. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  295. if (timer == null)
  296. {
  297. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  298. }
  299. var service = GetServices(timer.ServiceName, null)
  300. .First();
  301. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  302. }
  303. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  304. {
  305. var results = await GetRecordings(new RecordingQuery
  306. {
  307. UserId = user == null ? null : user.Id.ToString("N")
  308. }, cancellationToken).ConfigureAwait(false);
  309. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  310. }
  311. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  312. {
  313. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  314. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  315. }
  316. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  317. {
  318. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  319. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  320. }
  321. public Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  322. {
  323. var info = _tvDtoService.GetTimerInfo(timer);
  324. return ActiveService.UpdateTimerAsync(info, cancellationToken);
  325. }
  326. public Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  327. {
  328. var info = _tvDtoService.GetSeriesTimerInfo(timer);
  329. return ActiveService.UpdateSeriesTimerAsync(info, cancellationToken);
  330. }
  331. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  332. {
  333. var list = new List<SeriesTimerInfoDto>();
  334. if (ActiveService != null)
  335. {
  336. var timers = await ActiveService.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  337. var dtos = timers.Select(i => _tvDtoService.GetSeriesTimerInfoDto(i, ActiveService));
  338. list.AddRange(dtos);
  339. }
  340. var returnArray = list.OrderByDescending(i => i.StartDate)
  341. .ToArray();
  342. return new QueryResult<SeriesTimerInfoDto>
  343. {
  344. Items = returnArray,
  345. TotalRecordCount = returnArray.Length
  346. };
  347. }
  348. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  349. {
  350. var results = await GetChannels(new ChannelQuery
  351. {
  352. UserId = user == null ? null : user.Id.ToString("N")
  353. }, cancellationToken).ConfigureAwait(false);
  354. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  355. }
  356. }
  357. }