LiveTvManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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<LiveTvChannel> _channels = new List<LiveTvChannel>();
  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<LiveTvChannel> channels = _channels;
  69. if (user != null)
  70. {
  71. channels = channels
  72. .Where(i => i.IsParentalAllowed(user, _localization))
  73. .OrderBy(i =>
  74. {
  75. double number = 0;
  76. if (!string.IsNullOrEmpty(i.ChannelInfo.Number))
  77. {
  78. double.TryParse(i.ChannelInfo.Number, out number);
  79. }
  80. return number;
  81. });
  82. }
  83. var returnChannels = channels.OrderBy(i =>
  84. {
  85. double number = 0;
  86. if (!string.IsNullOrEmpty(i.ChannelInfo.Number))
  87. {
  88. double.TryParse(i.ChannelInfo.Number, out number);
  89. }
  90. return number;
  91. }).ThenBy(i => i.Name)
  92. .Select(i => _tvDtoService.GetChannelInfoDto(i, user))
  93. .ToArray();
  94. var result = new QueryResult<ChannelInfoDto>
  95. {
  96. Items = returnChannels,
  97. TotalRecordCount = returnChannels.Length
  98. };
  99. return Task.FromResult(result);
  100. }
  101. public LiveTvChannel GetInternalChannel(string id)
  102. {
  103. var guid = new Guid(id);
  104. return _channels.FirstOrDefault(i => i.Id == guid);
  105. }
  106. public async Task<LiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  107. {
  108. var service = ActiveService;
  109. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  110. var recording = recordings.FirstOrDefault(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  111. return await GetRecording(recording, service.Name, cancellationToken).ConfigureAwait(false);
  112. }
  113. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  114. {
  115. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(serviceName), _fileSystem.GetValidFilename(channelInfo.Name));
  116. var fileInfo = new DirectoryInfo(path);
  117. var isNew = false;
  118. if (!fileInfo.Exists)
  119. {
  120. Directory.CreateDirectory(path);
  121. fileInfo = new DirectoryInfo(path);
  122. if (!fileInfo.Exists)
  123. {
  124. throw new IOException("Path not created: " + path);
  125. }
  126. isNew = true;
  127. }
  128. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id, channelInfo.Name);
  129. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  130. if (item == null)
  131. {
  132. item = new LiveTvChannel
  133. {
  134. Name = channelInfo.Name,
  135. Id = id,
  136. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  137. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  138. Path = path
  139. };
  140. isNew = true;
  141. }
  142. item.ChannelInfo = channelInfo;
  143. item.ServiceName = serviceName;
  144. // Set this now so we don't cause additional file system access during provider executions
  145. item.ResetResolveArgs(fileInfo);
  146. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  147. return item;
  148. }
  149. private async Task<LiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  150. {
  151. var isNew = false;
  152. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  153. var item = _itemRepo.RetrieveItem(id) as LiveTvRecording;
  154. if (item == null)
  155. {
  156. item = new LiveTvRecording
  157. {
  158. Name = info.Name,
  159. Id = id,
  160. DateCreated = DateTime.UtcNow,
  161. DateModified = DateTime.UtcNow
  162. };
  163. isNew = true;
  164. }
  165. item.RecordingInfo = info;
  166. item.ServiceName = serviceName;
  167. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  168. return item;
  169. }
  170. public Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  171. {
  172. var program = _programs.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  173. return Task.FromResult(program);
  174. }
  175. public Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  176. {
  177. IEnumerable<ProgramInfoDto> programs = _programs
  178. .OrderBy(i => i.StartDate)
  179. .ThenBy(i => i.EndDate);
  180. if (query.ChannelIdList.Length > 0)
  181. {
  182. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  183. programs = programs.Where(i => guids.Contains(new Guid(i.ChannelId)));
  184. }
  185. var returnArray = programs.ToArray();
  186. var result = new QueryResult<ProgramInfoDto>
  187. {
  188. Items = returnArray,
  189. TotalRecordCount = returnArray.Length
  190. };
  191. return Task.FromResult(result);
  192. }
  193. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  194. {
  195. // Avoid implicitly captured closure
  196. var service = ActiveService;
  197. if (service == null)
  198. {
  199. progress.Report(100);
  200. return;
  201. }
  202. progress.Report(10);
  203. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  204. var allChannelsList = allChannels.ToList();
  205. var list = new List<LiveTvChannel>();
  206. var programs = new List<ProgramInfoDto>();
  207. var numComplete = 0;
  208. foreach (var channelInfo in allChannelsList)
  209. {
  210. try
  211. {
  212. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  213. var channelPrograms = await service.GetProgramsAsync(channelInfo.Item2.Id, cancellationToken).ConfigureAwait(false);
  214. programs.AddRange(channelPrograms.Select(program => _tvDtoService.GetProgramInfoDto(program, item)));
  215. list.Add(item);
  216. }
  217. catch (OperationCanceledException)
  218. {
  219. throw;
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  224. }
  225. numComplete++;
  226. double percent = numComplete;
  227. percent /= allChannelsList.Count;
  228. progress.Report(90 * percent + 10);
  229. }
  230. _programs = programs;
  231. _channels = list;
  232. }
  233. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  234. {
  235. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  236. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  237. }
  238. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  239. {
  240. var service = ActiveService;
  241. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  242. var list = new List<RecordingInfo>();
  243. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  244. list.AddRange(recordings);
  245. if (!string.IsNullOrEmpty(query.ChannelId))
  246. {
  247. list = list
  248. .Where(i => _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId, i.ChannelName) == new Guid(query.ChannelId))
  249. .ToList();
  250. }
  251. if (!string.IsNullOrEmpty(query.Id))
  252. {
  253. list = list
  254. .Where(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(query.Id))
  255. .ToList();
  256. }
  257. var entities = await GetEntities(list, service.Name, cancellationToken).ConfigureAwait(false);
  258. var returnArray = entities
  259. .Select(i => _tvDtoService.GetRecordingInfoDto(i, ActiveService, user))
  260. .OrderByDescending(i => i.StartDate)
  261. .ToArray();
  262. return new QueryResult<RecordingInfoDto>
  263. {
  264. Items = returnArray,
  265. TotalRecordCount = returnArray.Length
  266. };
  267. }
  268. private Task<LiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  269. {
  270. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  271. return Task.WhenAll(tasks);
  272. }
  273. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  274. {
  275. IEnumerable<ILiveTvService> services = _services;
  276. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  277. {
  278. var channelIdGuid = new Guid(channelId);
  279. serviceName = _channels.Where(i => i.Id == channelIdGuid)
  280. .Select(i => i.ServiceName)
  281. .FirstOrDefault();
  282. }
  283. if (!string.IsNullOrEmpty(serviceName))
  284. {
  285. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  286. }
  287. return services;
  288. }
  289. public Task ScheduleRecording(string programId)
  290. {
  291. throw new NotImplementedException();
  292. }
  293. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  294. {
  295. var list = new List<TimerInfoDto>();
  296. if (ActiveService != null)
  297. {
  298. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  299. var dtos = timers.Select(i => _tvDtoService.GetTimerInfoDto(i, ActiveService));
  300. list.AddRange(dtos);
  301. }
  302. if (!string.IsNullOrEmpty(query.ChannelId))
  303. {
  304. list = list.Where(i => string.Equals(i.ChannelId, query.ChannelId))
  305. .ToList();
  306. }
  307. var returnArray = list.OrderBy(i => i.StartDate)
  308. .ToArray();
  309. return new QueryResult<TimerInfoDto>
  310. {
  311. Items = returnArray,
  312. TotalRecordCount = returnArray.Length
  313. };
  314. }
  315. public async Task DeleteRecording(string recordingId)
  316. {
  317. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  318. if (recording == null)
  319. {
  320. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  321. }
  322. var service = GetServices(recording.ServiceName, null)
  323. .First();
  324. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  325. }
  326. public async Task CancelTimer(string id)
  327. {
  328. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  329. if (timer == null)
  330. {
  331. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  332. }
  333. var service = GetServices(timer.ServiceName, null)
  334. .First();
  335. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  336. }
  337. public async Task CancelSeriesTimer(string id)
  338. {
  339. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  340. if (timer == null)
  341. {
  342. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  343. }
  344. var service = GetServices(timer.ServiceName, null)
  345. .First();
  346. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  347. }
  348. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  349. {
  350. var results = await GetRecordings(new RecordingQuery
  351. {
  352. UserId = user == null ? null : user.Id.ToString("N"),
  353. Id = id
  354. }, cancellationToken).ConfigureAwait(false);
  355. return results.Items.FirstOrDefault();
  356. }
  357. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  358. {
  359. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  360. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  361. }
  362. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  363. {
  364. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  365. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  366. }
  367. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  368. {
  369. var list = new List<SeriesTimerInfoDto>();
  370. if (ActiveService != null)
  371. {
  372. var timers = await ActiveService.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  373. var dtos = timers.Select(i => _tvDtoService.GetSeriesTimerInfoDto(i, ActiveService));
  374. list.AddRange(dtos);
  375. }
  376. var returnArray = list.OrderByDescending(i => i.StartDate)
  377. .ToArray();
  378. return new QueryResult<SeriesTimerInfoDto>
  379. {
  380. Items = returnArray,
  381. TotalRecordCount = returnArray.Length
  382. };
  383. }
  384. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  385. {
  386. var results = await GetChannels(new ChannelQuery
  387. {
  388. UserId = user == null ? null : user.Id.ToString("N")
  389. }, cancellationToken).ConfigureAwait(false);
  390. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  391. }
  392. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  393. {
  394. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  395. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService);
  396. obj.Id = obj.ExternalId = string.Empty;
  397. return obj;
  398. }
  399. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  400. {
  401. var info = await GetNewTimerDefaults(cancellationToken).ConfigureAwait(false);
  402. var program = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  403. info.Days = new List<DayOfWeek>
  404. {
  405. program.StartDate.ToLocalTime().DayOfWeek
  406. };
  407. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  408. info.Name = program.Name;
  409. info.ChannelId = program.ChannelId;
  410. info.ChannelName = program.ChannelName;
  411. info.EndDate = program.EndDate;
  412. info.StartDate = program.StartDate;
  413. info.Name = program.Name;
  414. info.Overview = program.Overview;
  415. info.ProgramId = program.Id;
  416. info.ExternalProgramId = program.ExternalId;
  417. return info;
  418. }
  419. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  420. {
  421. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  422. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  423. // Set priority from default values
  424. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  425. info.Priority = defaultValues.Priority;
  426. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  427. }
  428. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  429. {
  430. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  431. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  432. // Set priority from default values
  433. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  434. info.Priority = defaultValues.Priority;
  435. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  436. }
  437. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  438. {
  439. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  440. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  441. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  442. }
  443. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  444. {
  445. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  446. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  447. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  448. }
  449. }
  450. }