LiveTvManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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.Entities;
  12. using MediaBrowser.Model.LiveTv;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.Querying;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Server.Implementations.LiveTv
  22. {
  23. /// <summary>
  24. /// Class LiveTvManager
  25. /// </summary>
  26. public class LiveTvManager : ILiveTvManager
  27. {
  28. private readonly IServerApplicationPaths _appPaths;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly ILogger _logger;
  31. private readonly IItemRepository _itemRepo;
  32. private readonly IImageProcessor _imageProcessor;
  33. private readonly IUserManager _userManager;
  34. private readonly ILocalizationManager _localization;
  35. private readonly IUserDataManager _userDataManager;
  36. private readonly IDtoService _dtoService;
  37. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  38. private List<Channel> _channels = new List<Channel>();
  39. private List<ProgramInfoDto> _programs = new List<ProgramInfoDto>();
  40. public LiveTvManager(IServerApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserManager userManager, ILocalizationManager localization, IUserDataManager userDataManager, IDtoService dtoService)
  41. {
  42. _appPaths = appPaths;
  43. _fileSystem = fileSystem;
  44. _logger = logger;
  45. _itemRepo = itemRepo;
  46. _imageProcessor = imageProcessor;
  47. _userManager = userManager;
  48. _localization = localization;
  49. _userDataManager = userDataManager;
  50. _dtoService = dtoService;
  51. }
  52. /// <summary>
  53. /// Gets the services.
  54. /// </summary>
  55. /// <value>The services.</value>
  56. public IReadOnlyList<ILiveTvService> Services
  57. {
  58. get { return _services; }
  59. }
  60. public ILiveTvService ActiveService { get; private set; }
  61. /// <summary>
  62. /// Adds the parts.
  63. /// </summary>
  64. /// <param name="services">The services.</param>
  65. public void AddParts(IEnumerable<ILiveTvService> services)
  66. {
  67. _services.AddRange(services);
  68. ActiveService = _services.FirstOrDefault();
  69. }
  70. /// <summary>
  71. /// Gets the channel info dto.
  72. /// </summary>
  73. /// <param name="info">The info.</param>
  74. /// <param name="user">The user.</param>
  75. /// <returns>ChannelInfoDto.</returns>
  76. public ChannelInfoDto GetChannelInfoDto(Channel info, User user)
  77. {
  78. var dto = new ChannelInfoDto
  79. {
  80. Name = info.Name,
  81. ServiceName = info.ServiceName,
  82. ChannelType = info.ChannelType,
  83. Number = info.ChannelNumber,
  84. Type = info.GetType().Name,
  85. Id = info.Id.ToString("N"),
  86. MediaType = info.MediaType
  87. };
  88. if (user != null)
  89. {
  90. dto.UserData = _dtoService.GetUserItemDataDto(_userDataManager.GetUserData(user.Id, info.GetUserDataKey()));
  91. }
  92. var imageTag = GetLogoImageTag(info);
  93. if (imageTag.HasValue)
  94. {
  95. dto.ImageTags[ImageType.Primary] = imageTag.Value;
  96. }
  97. return dto;
  98. }
  99. private Guid? GetLogoImageTag(Channel info)
  100. {
  101. var path = info.PrimaryImagePath;
  102. if (string.IsNullOrEmpty(path))
  103. {
  104. return null;
  105. }
  106. try
  107. {
  108. return _imageProcessor.GetImageCacheTag(info, ImageType.Primary, path);
  109. }
  110. catch (Exception ex)
  111. {
  112. _logger.ErrorException("Error getting channel image info for {0}", ex, info.Name);
  113. }
  114. return null;
  115. }
  116. public QueryResult<ChannelInfoDto> GetChannels(ChannelQuery query)
  117. {
  118. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  119. IEnumerable<Channel> channels = _channels;
  120. if (user != null)
  121. {
  122. channels = channels.Where(i => i.IsParentalAllowed(user, _localization))
  123. .OrderBy(i =>
  124. {
  125. double number = 0;
  126. if (!string.IsNullOrEmpty(i.ChannelNumber))
  127. {
  128. double.TryParse(i.ChannelNumber, out number);
  129. }
  130. return number;
  131. });
  132. }
  133. var returnChannels = channels.OrderBy(i =>
  134. {
  135. double number = 0;
  136. if (!string.IsNullOrEmpty(i.ChannelNumber))
  137. {
  138. double.TryParse(i.ChannelNumber, out number);
  139. }
  140. return number;
  141. }).ThenBy(i => i.Name)
  142. .Select(i => GetChannelInfoDto(i, user))
  143. .ToArray();
  144. return new QueryResult<ChannelInfoDto>
  145. {
  146. Items = returnChannels,
  147. TotalRecordCount = returnChannels.Length
  148. };
  149. }
  150. public Channel GetChannel(string id)
  151. {
  152. var guid = new Guid(id);
  153. return _channels.FirstOrDefault(i => i.Id == guid);
  154. }
  155. public ChannelInfoDto GetChannelInfoDto(string id, string userId)
  156. {
  157. var channel = GetChannel(id);
  158. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(new Guid(userId));
  159. return channel == null ? null : GetChannelInfoDto(channel, user);
  160. }
  161. private ProgramInfoDto GetProgramInfoDto(ProgramInfo program, Channel channel)
  162. {
  163. var id = GetInternalProgramIdId(channel.ServiceName, program.Id).ToString("N");
  164. return new ProgramInfoDto
  165. {
  166. ChannelId = channel.Id.ToString("N"),
  167. Overview = program.Overview,
  168. EndDate = program.EndDate,
  169. Genres = program.Genres,
  170. ExternalId = program.Id,
  171. Id = id,
  172. Name = program.Name,
  173. ServiceName = channel.ServiceName,
  174. StartDate = program.StartDate,
  175. OfficialRating = program.OfficialRating,
  176. IsHD = program.IsHD,
  177. OriginalAirDate = program.OriginalAirDate,
  178. Audio = program.Audio,
  179. CommunityRating = program.CommunityRating,
  180. AspectRatio = program.AspectRatio,
  181. IsRepeat = program.IsRepeat,
  182. EpisodeTitle = program.EpisodeTitle
  183. };
  184. }
  185. private Guid GetInternalChannelId(string serviceName, string externalChannelId, string channelName)
  186. {
  187. var name = serviceName + externalChannelId + channelName;
  188. return name.ToLower().GetMBId(typeof(Channel));
  189. }
  190. private Guid GetInternalProgramIdId(string serviceName, string externalProgramId)
  191. {
  192. var name = serviceName + externalProgramId;
  193. return name.ToLower().GetMD5();
  194. }
  195. private async Task<Channel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  196. {
  197. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(serviceName), _fileSystem.GetValidFilename(channelInfo.Name));
  198. var fileInfo = new DirectoryInfo(path);
  199. var isNew = false;
  200. if (!fileInfo.Exists)
  201. {
  202. Directory.CreateDirectory(path);
  203. fileInfo = new DirectoryInfo(path);
  204. if (!fileInfo.Exists)
  205. {
  206. throw new IOException("Path not created: " + path);
  207. }
  208. isNew = true;
  209. }
  210. var id = GetInternalChannelId(serviceName, channelInfo.Id, channelInfo.Name);
  211. var item = _itemRepo.RetrieveItem(id) as Channel;
  212. if (item == null)
  213. {
  214. item = new Channel
  215. {
  216. Name = channelInfo.Name,
  217. Id = id,
  218. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  219. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  220. Path = path,
  221. ChannelId = channelInfo.Id,
  222. ChannelNumber = channelInfo.Number,
  223. ServiceName = serviceName
  224. };
  225. isNew = true;
  226. }
  227. // Set this now so we don't cause additional file system access during provider executions
  228. item.ResetResolveArgs(fileInfo);
  229. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  230. return item;
  231. }
  232. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  233. {
  234. IEnumerable<ProgramInfoDto> programs = _programs
  235. .OrderBy(i => i.StartDate)
  236. .ThenBy(i => i.EndDate);
  237. if (query.ChannelIdList.Length > 0)
  238. {
  239. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  240. programs = programs.Where(i => guids.Contains(new Guid(i.ChannelId)));
  241. }
  242. var returnArray = programs.ToArray();
  243. return new QueryResult<ProgramInfoDto>
  244. {
  245. Items = returnArray,
  246. TotalRecordCount = returnArray.Length
  247. };
  248. }
  249. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  250. {
  251. // Avoid implicitly captured closure
  252. var service = ActiveService;
  253. if (service == null)
  254. {
  255. progress.Report(100);
  256. return;
  257. }
  258. progress.Report(10);
  259. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  260. var allChannelsList = allChannels.ToList();
  261. var list = new List<Channel>();
  262. var programs = new List<ProgramInfoDto>();
  263. var numComplete = 0;
  264. foreach (var channelInfo in allChannelsList)
  265. {
  266. try
  267. {
  268. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  269. var channelPrograms = await service.GetProgramsAsync(channelInfo.Item2.Id, cancellationToken).ConfigureAwait(false);
  270. programs.AddRange(channelPrograms.Select(program => GetProgramInfoDto(program, item)));
  271. list.Add(item);
  272. }
  273. catch (OperationCanceledException)
  274. {
  275. throw;
  276. }
  277. catch (Exception ex)
  278. {
  279. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  280. }
  281. numComplete++;
  282. double percent = numComplete;
  283. percent /= allChannelsList.Count;
  284. progress.Report(90 * percent + 10);
  285. }
  286. _programs = programs;
  287. _channels = list;
  288. }
  289. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  290. {
  291. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  292. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  293. }
  294. private async Task<IEnumerable<RecordingInfoDto>> GetRecordings(ILiveTvService service, CancellationToken cancellationToken)
  295. {
  296. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  297. return recordings.Select(i => GetRecordingInfoDto(i, service));
  298. }
  299. private RecordingInfoDto GetRecordingInfoDto(RecordingInfo info, ILiveTvService service)
  300. {
  301. var id = service.Name + info.ChannelId + info.Id;
  302. id = id.GetMD5().ToString("N");
  303. var dto = new RecordingInfoDto
  304. {
  305. ChannelName = info.ChannelName,
  306. Overview = info.Overview,
  307. EndDate = info.EndDate,
  308. Name = info.Name,
  309. StartDate = info.StartDate,
  310. Id = id,
  311. ExternalId = info.Id,
  312. ChannelId = GetInternalChannelId(service.Name, info.ChannelId, info.ChannelName).ToString("N"),
  313. Status = info.Status,
  314. Path = info.Path,
  315. Genres = info.Genres,
  316. IsRepeat = info.IsRepeat,
  317. EpisodeTitle = info.EpisodeTitle,
  318. ChannelType = info.ChannelType,
  319. MediaType = info.ChannelType == ChannelType.Radio ? MediaType.Audio : MediaType.Video,
  320. CommunityRating = info.CommunityRating,
  321. OfficialRating = info.OfficialRating,
  322. Audio = info.Audio,
  323. IsHD = info.IsHD
  324. };
  325. var duration = info.EndDate - info.StartDate;
  326. dto.DurationMs = Convert.ToInt32(duration.TotalMilliseconds);
  327. if (!string.IsNullOrEmpty(info.ProgramId))
  328. {
  329. dto.ProgramId = GetInternalProgramIdId(service.Name, info.ProgramId).ToString("N");
  330. }
  331. return dto;
  332. }
  333. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  334. {
  335. var list = new List<RecordingInfoDto>();
  336. if (ActiveService != null)
  337. {
  338. var recordings = await GetRecordings(ActiveService, cancellationToken).ConfigureAwait(false);
  339. list.AddRange(recordings);
  340. }
  341. if (!string.IsNullOrEmpty(query.ChannelId))
  342. {
  343. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  344. .ToList();
  345. }
  346. var returnArray = list.OrderByDescending(i => i.StartDate)
  347. .ToArray();
  348. return new QueryResult<RecordingInfoDto>
  349. {
  350. Items = returnArray,
  351. TotalRecordCount = returnArray.Length
  352. };
  353. }
  354. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  355. {
  356. IEnumerable<ILiveTvService> services = _services;
  357. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  358. {
  359. var channelIdGuid = new Guid(channelId);
  360. serviceName = _channels.Where(i => i.Id == channelIdGuid)
  361. .Select(i => i.ServiceName)
  362. .FirstOrDefault();
  363. }
  364. if (!string.IsNullOrEmpty(serviceName))
  365. {
  366. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  367. }
  368. return services;
  369. }
  370. public Task ScheduleRecording(string programId)
  371. {
  372. throw new NotImplementedException();
  373. }
  374. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  375. {
  376. var list = new List<TimerInfoDto>();
  377. if (ActiveService != null)
  378. {
  379. var timers = await GetTimers(ActiveService, cancellationToken).ConfigureAwait(false);
  380. list.AddRange(timers);
  381. }
  382. if (!string.IsNullOrEmpty(query.ChannelId))
  383. {
  384. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  385. .ToList();
  386. }
  387. var returnArray = list.OrderByDescending(i => i.StartDate)
  388. .ToArray();
  389. return new QueryResult<TimerInfoDto>
  390. {
  391. Items = returnArray,
  392. TotalRecordCount = returnArray.Length
  393. };
  394. }
  395. private async Task<IEnumerable<TimerInfoDto>> GetTimers(ILiveTvService service, CancellationToken cancellationToken)
  396. {
  397. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  398. return timers.Select(i => GetTimerInfoDto(i, service));
  399. }
  400. private TimerInfoDto GetTimerInfoDto(TimerInfo info, ILiveTvService service)
  401. {
  402. var id = service.Name + info.ChannelId + info.Id;
  403. id = id.GetMD5().ToString("N");
  404. var dto = new TimerInfoDto
  405. {
  406. ChannelName = info.ChannelName,
  407. Description = info.Description,
  408. EndDate = info.EndDate,
  409. Name = info.Name,
  410. StartDate = info.StartDate,
  411. Id = id,
  412. ExternalId = info.Id,
  413. ChannelId = GetInternalChannelId(service.Name, info.ChannelId, info.ChannelName).ToString("N"),
  414. Status = info.Status,
  415. SeriesTimerId = info.SeriesTimerId,
  416. RequestedPostPaddingSeconds = info.RequestedPostPaddingSeconds,
  417. RequestedPrePaddingSeconds = info.RequestedPrePaddingSeconds,
  418. RequiredPostPaddingSeconds = info.RequiredPostPaddingSeconds,
  419. RequiredPrePaddingSeconds = info.RequiredPrePaddingSeconds
  420. };
  421. var duration = info.EndDate - info.StartDate;
  422. dto.DurationMs = Convert.ToInt32(duration.TotalMilliseconds);
  423. if (!string.IsNullOrEmpty(info.ProgramId))
  424. {
  425. dto.ProgramId = GetInternalProgramIdId(service.Name, info.ProgramId).ToString("N");
  426. }
  427. return dto;
  428. }
  429. public async Task DeleteRecording(string recordingId)
  430. {
  431. var recordings = await GetRecordings(new RecordingQuery
  432. {
  433. }, CancellationToken.None).ConfigureAwait(false);
  434. var recording = recordings.Items
  435. .FirstOrDefault(i => string.Equals(recordingId, i.Id, StringComparison.OrdinalIgnoreCase));
  436. if (recording == null)
  437. {
  438. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  439. }
  440. var channel = GetChannel(recording.ChannelId);
  441. var service = GetServices(channel.ServiceName, null)
  442. .First();
  443. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  444. }
  445. public async Task CancelTimer(string id)
  446. {
  447. var timers = await GetTimers(new TimerQuery
  448. {
  449. }, CancellationToken.None).ConfigureAwait(false);
  450. var timer = timers.Items
  451. .FirstOrDefault(i => string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase));
  452. if (timer == null)
  453. {
  454. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  455. }
  456. var channel = GetChannel(timer.ChannelId);
  457. var service = GetServices(channel.ServiceName, null)
  458. .First();
  459. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  460. }
  461. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken)
  462. {
  463. var results = await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  464. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  465. }
  466. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  467. {
  468. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  469. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  470. }
  471. }
  472. }