LiveTvManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  144. {
  145. var program = _programs.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  146. return Task.FromResult(program);
  147. }
  148. public Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  149. {
  150. IEnumerable<ProgramInfoDto> programs = _programs
  151. .OrderBy(i => i.StartDate)
  152. .ThenBy(i => i.EndDate);
  153. if (query.ChannelIdList.Length > 0)
  154. {
  155. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  156. programs = programs.Where(i => guids.Contains(new Guid(i.ChannelId)));
  157. }
  158. var returnArray = programs.ToArray();
  159. var result = new QueryResult<ProgramInfoDto>
  160. {
  161. Items = returnArray,
  162. TotalRecordCount = returnArray.Length
  163. };
  164. return Task.FromResult(result);
  165. }
  166. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  167. {
  168. // Avoid implicitly captured closure
  169. var service = ActiveService;
  170. if (service == null)
  171. {
  172. progress.Report(100);
  173. return;
  174. }
  175. progress.Report(10);
  176. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  177. var allChannelsList = allChannels.ToList();
  178. var list = new List<Channel>();
  179. var programs = new List<ProgramInfoDto>();
  180. var numComplete = 0;
  181. foreach (var channelInfo in allChannelsList)
  182. {
  183. try
  184. {
  185. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  186. var channelPrograms = await service.GetProgramsAsync(channelInfo.Item2.Id, cancellationToken).ConfigureAwait(false);
  187. programs.AddRange(channelPrograms.Select(program => _tvDtoService.GetProgramInfoDto(program, item)));
  188. list.Add(item);
  189. }
  190. catch (OperationCanceledException)
  191. {
  192. throw;
  193. }
  194. catch (Exception ex)
  195. {
  196. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  197. }
  198. numComplete++;
  199. double percent = numComplete;
  200. percent /= allChannelsList.Count;
  201. progress.Report(90 * percent + 10);
  202. }
  203. _programs = programs;
  204. _channels = list;
  205. }
  206. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  207. {
  208. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  209. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  210. }
  211. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  212. {
  213. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  214. var list = new List<RecordingInfoDto>();
  215. if (ActiveService != null)
  216. {
  217. var recordings = await ActiveService.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  218. var dtos = recordings.Select(i => _tvDtoService.GetRecordingInfoDto(i, ActiveService, user));
  219. list.AddRange(dtos);
  220. }
  221. if (!string.IsNullOrEmpty(query.ChannelId))
  222. {
  223. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  224. .ToList();
  225. }
  226. var returnArray = list.OrderByDescending(i => i.StartDate)
  227. .ToArray();
  228. return new QueryResult<RecordingInfoDto>
  229. {
  230. Items = returnArray,
  231. TotalRecordCount = returnArray.Length
  232. };
  233. }
  234. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  235. {
  236. IEnumerable<ILiveTvService> services = _services;
  237. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  238. {
  239. var channelIdGuid = new Guid(channelId);
  240. serviceName = _channels.Where(i => i.Id == channelIdGuid)
  241. .Select(i => i.ServiceName)
  242. .FirstOrDefault();
  243. }
  244. if (!string.IsNullOrEmpty(serviceName))
  245. {
  246. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  247. }
  248. return services;
  249. }
  250. public Task ScheduleRecording(string programId)
  251. {
  252. throw new NotImplementedException();
  253. }
  254. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  255. {
  256. var list = new List<TimerInfoDto>();
  257. if (ActiveService != null)
  258. {
  259. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  260. var dtos = timers.Select(i => _tvDtoService.GetTimerInfoDto(i, ActiveService));
  261. list.AddRange(dtos);
  262. }
  263. if (!string.IsNullOrEmpty(query.ChannelId))
  264. {
  265. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  266. .ToList();
  267. }
  268. var returnArray = list.OrderBy(i => i.StartDate)
  269. .ToArray();
  270. return new QueryResult<TimerInfoDto>
  271. {
  272. Items = returnArray,
  273. TotalRecordCount = returnArray.Length
  274. };
  275. }
  276. public async Task DeleteRecording(string recordingId)
  277. {
  278. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  279. if (recording == null)
  280. {
  281. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  282. }
  283. var service = GetServices(recording.ServiceName, null)
  284. .First();
  285. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  286. }
  287. public async Task CancelTimer(string id)
  288. {
  289. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  290. if (timer == null)
  291. {
  292. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  293. }
  294. var service = GetServices(timer.ServiceName, null)
  295. .First();
  296. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  297. }
  298. public async Task CancelSeriesTimer(string id)
  299. {
  300. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  301. if (timer == null)
  302. {
  303. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  304. }
  305. var service = GetServices(timer.ServiceName, null)
  306. .First();
  307. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  308. }
  309. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  310. {
  311. var results = await GetRecordings(new RecordingQuery
  312. {
  313. UserId = user == null ? null : user.Id.ToString("N")
  314. }, cancellationToken).ConfigureAwait(false);
  315. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  316. }
  317. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  318. {
  319. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  320. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  321. }
  322. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  323. {
  324. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  325. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  326. }
  327. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  328. {
  329. var list = new List<SeriesTimerInfoDto>();
  330. if (ActiveService != null)
  331. {
  332. var timers = await ActiveService.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  333. var dtos = timers.Select(i => _tvDtoService.GetSeriesTimerInfoDto(i, ActiveService));
  334. list.AddRange(dtos);
  335. }
  336. var returnArray = list.OrderByDescending(i => i.StartDate)
  337. .ToArray();
  338. return new QueryResult<SeriesTimerInfoDto>
  339. {
  340. Items = returnArray,
  341. TotalRecordCount = returnArray.Length
  342. };
  343. }
  344. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  345. {
  346. var results = await GetChannels(new ChannelQuery
  347. {
  348. UserId = user == null ? null : user.Id.ToString("N")
  349. }, cancellationToken).ConfigureAwait(false);
  350. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  351. }
  352. public async Task<TimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  353. {
  354. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  355. return _tvDtoService.GetTimerInfoDto(info, ActiveService);
  356. }
  357. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  358. {
  359. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  360. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  361. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  362. }
  363. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  364. {
  365. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  366. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  367. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  368. }
  369. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  370. {
  371. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  372. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  373. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  374. }
  375. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  376. {
  377. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  378. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  379. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  380. }
  381. }
  382. }