LiveTvManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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.Persistence;
  10. using MediaBrowser.Model.Entities;
  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 LiveTvDtoService _tvDtoService;
  33. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  34. private Dictionary<Guid, LiveTvChannel> _channels = new Dictionary<Guid, LiveTvChannel>();
  35. private Dictionary<Guid, LiveTvProgram> _programs = new Dictionary<Guid, LiveTvProgram>();
  36. public LiveTvManager(IServerApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager)
  37. {
  38. _appPaths = appPaths;
  39. _fileSystem = fileSystem;
  40. _logger = logger;
  41. _itemRepo = itemRepo;
  42. _userManager = userManager;
  43. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, _itemRepo);
  44. }
  45. /// <summary>
  46. /// Gets the services.
  47. /// </summary>
  48. /// <value>The services.</value>
  49. public IReadOnlyList<ILiveTvService> Services
  50. {
  51. get { return _services; }
  52. }
  53. public ILiveTvService ActiveService { get; private set; }
  54. /// <summary>
  55. /// Adds the parts.
  56. /// </summary>
  57. /// <param name="services">The services.</param>
  58. public void AddParts(IEnumerable<ILiveTvService> services)
  59. {
  60. _services.AddRange(services);
  61. ActiveService = _services.FirstOrDefault();
  62. }
  63. public Task<QueryResult<ChannelInfoDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
  64. {
  65. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  66. IEnumerable<LiveTvChannel> channels = _channels.Values;
  67. if (user != null)
  68. {
  69. // Avoid implicitly captured closure
  70. var currentUser = user;
  71. channels = channels
  72. .Where(i => i.IsParentalAllowed(currentUser))
  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, GetCurrentProgram(i.ChannelInfo.Id), 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. return GetInternalChannel(new Guid(id));
  104. }
  105. private LiveTvChannel GetInternalChannel(Guid id)
  106. {
  107. LiveTvChannel channel = null;
  108. _channels.TryGetValue(id, out channel);
  109. return channel;
  110. }
  111. public LiveTvProgram GetInternalProgram(string id)
  112. {
  113. var guid = new Guid(id);
  114. LiveTvProgram obj = null;
  115. _programs.TryGetValue(guid, out obj);
  116. return obj;
  117. }
  118. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  119. {
  120. var service = ActiveService;
  121. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  122. var recording = recordings.FirstOrDefault(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  123. return await GetRecording(recording, service.Name, cancellationToken).ConfigureAwait(false);
  124. }
  125. public async Task<LiveStreamInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  126. {
  127. var service = ActiveService;
  128. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  129. var recording = recordings.First(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  130. return await service.GetRecordingStream(recording.Id, cancellationToken).ConfigureAwait(false);
  131. }
  132. public async Task<LiveStreamInfo> GetChannelStream(string id, CancellationToken cancellationToken)
  133. {
  134. var service = ActiveService;
  135. var channel = GetInternalChannel(id);
  136. return await service.GetChannelStream(channel.ChannelInfo.Id, cancellationToken).ConfigureAwait(false);
  137. }
  138. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  139. {
  140. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(serviceName), _fileSystem.GetValidFilename(channelInfo.Name));
  141. var fileInfo = new DirectoryInfo(path);
  142. var isNew = false;
  143. if (!fileInfo.Exists)
  144. {
  145. Directory.CreateDirectory(path);
  146. fileInfo = new DirectoryInfo(path);
  147. if (!fileInfo.Exists)
  148. {
  149. throw new IOException("Path not created: " + path);
  150. }
  151. isNew = true;
  152. }
  153. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  154. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  155. if (item == null)
  156. {
  157. item = new LiveTvChannel
  158. {
  159. Name = channelInfo.Name,
  160. Id = id,
  161. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  162. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  163. Path = path
  164. };
  165. isNew = true;
  166. }
  167. item.ChannelInfo = channelInfo;
  168. item.ServiceName = serviceName;
  169. // Set this now so we don't cause additional file system access during provider executions
  170. item.ResetResolveArgs(fileInfo);
  171. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  172. return item;
  173. }
  174. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  175. {
  176. var isNew = false;
  177. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  178. var item = _itemRepo.RetrieveItem(id) as LiveTvProgram;
  179. if (item == null)
  180. {
  181. item = new LiveTvProgram
  182. {
  183. Name = info.Name,
  184. Id = id,
  185. DateCreated = DateTime.UtcNow,
  186. DateModified = DateTime.UtcNow
  187. };
  188. isNew = true;
  189. }
  190. item.ChannelType = channelType;
  191. item.ProgramInfo = info;
  192. item.ServiceName = serviceName;
  193. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  194. return item;
  195. }
  196. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  197. {
  198. var isNew = false;
  199. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  200. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  201. if (item == null)
  202. {
  203. if (info.ChannelType == ChannelType.TV)
  204. {
  205. item = new LiveTvVideoRecording
  206. {
  207. Name = info.Name,
  208. Id = id,
  209. DateCreated = DateTime.UtcNow,
  210. DateModified = DateTime.UtcNow,
  211. VideoType = VideoType.VideoFile
  212. };
  213. }
  214. else
  215. {
  216. item = new LiveTvAudioRecording
  217. {
  218. Name = info.Name,
  219. Id = id,
  220. DateCreated = DateTime.UtcNow,
  221. DateModified = DateTime.UtcNow
  222. };
  223. }
  224. if (!string.IsNullOrEmpty(info.Path))
  225. {
  226. item.Path = info.Path;
  227. }
  228. else if (!string.IsNullOrEmpty(info.Url))
  229. {
  230. item.Path = info.Url;
  231. }
  232. isNew = true;
  233. }
  234. item.RecordingInfo = info;
  235. item.ServiceName = serviceName;
  236. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  237. return item;
  238. }
  239. private LiveTvChannel GetChannel(LiveTvProgram program)
  240. {
  241. var programChannelId = program.ProgramInfo.ChannelId;
  242. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  243. return GetInternalChannel(internalProgramChannelId);
  244. }
  245. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  246. {
  247. var program = GetInternalProgram(id);
  248. var channel = GetChannel(program);
  249. var channelName = channel == null ? null : channel.ChannelInfo.Name;
  250. var dto = _tvDtoService.GetProgramInfoDto(program, channelName, user);
  251. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  252. return dto;
  253. }
  254. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  255. {
  256. IEnumerable<LiveTvProgram> programs = _programs.Values;
  257. if (query.MinEndDate.HasValue)
  258. {
  259. var val = query.MinEndDate.Value;
  260. programs = programs.Where(i => i.ProgramInfo.EndDate >= val);
  261. }
  262. if (query.MinStartDate.HasValue)
  263. {
  264. var val = query.MinStartDate.Value;
  265. programs = programs.Where(i => i.ProgramInfo.StartDate >= val);
  266. }
  267. if (query.MaxEndDate.HasValue)
  268. {
  269. var val = query.MaxEndDate.Value;
  270. programs = programs.Where(i => i.ProgramInfo.EndDate <= val);
  271. }
  272. if (query.MaxStartDate.HasValue)
  273. {
  274. var val = query.MaxStartDate.Value;
  275. programs = programs.Where(i => i.ProgramInfo.StartDate <= val);
  276. }
  277. if (query.ChannelIdList.Length > 0)
  278. {
  279. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  280. var serviceName = ActiveService.Name;
  281. programs = programs.Where(i =>
  282. {
  283. var programChannelId = i.ProgramInfo.ChannelId;
  284. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
  285. return guids.Contains(internalProgramChannelId);
  286. });
  287. }
  288. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  289. if (user != null)
  290. {
  291. // Avoid implicitly captured closure
  292. var currentUser = user;
  293. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  294. }
  295. var returnArray = programs
  296. .OrderBy(i => i.ProgramInfo.StartDate)
  297. .Select(i =>
  298. {
  299. var channel = GetChannel(i);
  300. var channelName = channel == null ? null : channel.ChannelInfo.Name;
  301. return _tvDtoService.GetProgramInfoDto(i, channelName, user);
  302. })
  303. .ToArray();
  304. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  305. var result = new QueryResult<ProgramInfoDto>
  306. {
  307. Items = returnArray,
  308. TotalRecordCount = returnArray.Length
  309. };
  310. return result;
  311. }
  312. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  313. {
  314. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  315. var timerList = timers.ToList();
  316. foreach (var program in programs)
  317. {
  318. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  319. if (timer != null)
  320. {
  321. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  322. .ToString("N");
  323. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  324. {
  325. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  326. .ToString("N");
  327. }
  328. }
  329. }
  330. }
  331. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  332. {
  333. // Avoid implicitly captured closure
  334. var service = ActiveService;
  335. if (service == null)
  336. {
  337. progress.Report(100);
  338. return;
  339. }
  340. progress.Report(10);
  341. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  342. var allChannelsList = allChannels.ToList();
  343. var list = new List<LiveTvChannel>();
  344. var numComplete = 0;
  345. foreach (var channelInfo in allChannelsList)
  346. {
  347. try
  348. {
  349. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  350. list.Add(item);
  351. }
  352. catch (OperationCanceledException)
  353. {
  354. throw;
  355. }
  356. catch (Exception ex)
  357. {
  358. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  359. }
  360. numComplete++;
  361. double percent = numComplete;
  362. percent /= allChannelsList.Count;
  363. progress.Report(5 * percent + 10);
  364. }
  365. _channels = list.ToDictionary(i => i.Id);
  366. progress.Report(15);
  367. numComplete = 0;
  368. var programs = new List<LiveTvProgram>();
  369. foreach (var item in list)
  370. {
  371. // Avoid implicitly captured closure
  372. var currentChannel = item;
  373. try
  374. {
  375. var channelPrograms = await service.GetProgramsAsync(currentChannel.ChannelInfo.Id, cancellationToken).ConfigureAwait(false);
  376. var programTasks = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelInfo.ChannelType, service.Name, cancellationToken));
  377. var programEntities = await Task.WhenAll(programTasks).ConfigureAwait(false);
  378. programs.AddRange(programEntities);
  379. }
  380. catch (OperationCanceledException)
  381. {
  382. throw;
  383. }
  384. catch (Exception ex)
  385. {
  386. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  387. }
  388. numComplete++;
  389. double percent = numComplete;
  390. percent /= allChannelsList.Count;
  391. progress.Report(90 * percent + 10);
  392. }
  393. _programs = programs.ToDictionary(i => i.Id);
  394. }
  395. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  396. {
  397. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  398. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  399. }
  400. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  401. {
  402. var service = ActiveService;
  403. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  404. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  405. if (!string.IsNullOrEmpty(query.ChannelId))
  406. {
  407. var guid = new Guid(query.ChannelId);
  408. var currentServiceName = service.Name;
  409. recordings = recordings
  410. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  411. }
  412. if (!string.IsNullOrEmpty(query.Id))
  413. {
  414. var guid = new Guid(query.Id);
  415. var currentServiceName = service.Name;
  416. recordings = recordings
  417. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  418. }
  419. if (!string.IsNullOrEmpty(query.GroupId))
  420. {
  421. var guid = new Guid(query.GroupId);
  422. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  423. }
  424. if (query.IsRecording.HasValue)
  425. {
  426. var val = query.IsRecording.Value;
  427. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  428. }
  429. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  430. entities = entities.OrderByDescending(i => i.RecordingInfo.StartDate);
  431. if (user != null)
  432. {
  433. var currentUser = user;
  434. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  435. }
  436. if (query.StartIndex.HasValue)
  437. {
  438. entities = entities.Skip(query.StartIndex.Value);
  439. }
  440. if (query.Limit.HasValue)
  441. {
  442. entities = entities.Take(query.Limit.Value);
  443. }
  444. var returnArray = entities
  445. .Select(i =>
  446. {
  447. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  448. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  449. })
  450. .ToArray();
  451. return new QueryResult<RecordingInfoDto>
  452. {
  453. Items = returnArray,
  454. TotalRecordCount = returnArray.Length
  455. };
  456. }
  457. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  458. {
  459. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  460. return Task.WhenAll(tasks);
  461. }
  462. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  463. {
  464. IEnumerable<ILiveTvService> services = _services;
  465. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  466. {
  467. var channel = GetInternalChannel(channelId);
  468. if (channel != null)
  469. {
  470. serviceName = channel.ServiceName;
  471. }
  472. }
  473. if (!string.IsNullOrEmpty(serviceName))
  474. {
  475. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  476. }
  477. return services;
  478. }
  479. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  480. {
  481. var service = ActiveService;
  482. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  483. if (!string.IsNullOrEmpty(query.ChannelId))
  484. {
  485. var guid = new Guid(query.ChannelId);
  486. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  487. }
  488. var returnArray = timers
  489. .Select(i =>
  490. {
  491. var program = string.IsNullOrEmpty(i.ProgramId) ? null : GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"));
  492. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  493. return _tvDtoService.GetTimerInfoDto(i, service, program, channel);
  494. })
  495. .OrderBy(i => i.StartDate)
  496. .ToArray();
  497. return new QueryResult<TimerInfoDto>
  498. {
  499. Items = returnArray,
  500. TotalRecordCount = returnArray.Length
  501. };
  502. }
  503. public async Task DeleteRecording(string recordingId)
  504. {
  505. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  506. if (recording == null)
  507. {
  508. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  509. }
  510. var service = GetServices(recording.ServiceName, null)
  511. .First();
  512. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  513. }
  514. public async Task CancelTimer(string id)
  515. {
  516. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  517. if (timer == null)
  518. {
  519. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  520. }
  521. var service = GetServices(timer.ServiceName, null)
  522. .First();
  523. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  524. }
  525. public async Task CancelSeriesTimer(string id)
  526. {
  527. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  528. if (timer == null)
  529. {
  530. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  531. }
  532. var service = GetServices(timer.ServiceName, null)
  533. .First();
  534. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  535. }
  536. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  537. {
  538. var results = await GetRecordings(new RecordingQuery
  539. {
  540. UserId = user == null ? null : user.Id.ToString("N"),
  541. Id = id
  542. }, cancellationToken).ConfigureAwait(false);
  543. return results.Items.FirstOrDefault();
  544. }
  545. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  546. {
  547. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  548. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  549. }
  550. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  551. {
  552. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  553. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  554. }
  555. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  556. {
  557. var service = ActiveService;
  558. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  559. var returnArray = timers
  560. .Select(i =>
  561. {
  562. string channelName = null;
  563. if (!string.IsNullOrEmpty(i.ChannelId))
  564. {
  565. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  566. var channel = GetInternalChannel(internalChannelId);
  567. channelName = channel == null ? null : channel.ChannelInfo.Name;
  568. }
  569. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  570. })
  571. .OrderByDescending(i => i.StartDate)
  572. .ToArray();
  573. return new QueryResult<SeriesTimerInfoDto>
  574. {
  575. Items = returnArray,
  576. TotalRecordCount = returnArray.Length
  577. };
  578. }
  579. public Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  580. {
  581. var channel = GetInternalChannel(id);
  582. var dto = _tvDtoService.GetChannelInfoDto(channel, GetCurrentProgram(channel.ChannelInfo.Id), user);
  583. return Task.FromResult(dto);
  584. }
  585. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  586. {
  587. var now = DateTime.UtcNow;
  588. return _programs.Values
  589. .Where(i => string.Equals(externalChannelId, i.ProgramInfo.ChannelId, StringComparison.OrdinalIgnoreCase))
  590. .OrderBy(i => i.ProgramInfo.StartDate)
  591. .SkipWhile(i => now >= i.ProgramInfo.EndDate)
  592. .FirstOrDefault();
  593. }
  594. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  595. {
  596. var service = ActiveService;
  597. var info = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  598. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, service, null);
  599. obj.Id = obj.ExternalId = string.Empty;
  600. return obj;
  601. }
  602. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  603. {
  604. var info = await GetNewTimerDefaults(cancellationToken).ConfigureAwait(false);
  605. var program = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  606. info.Days = new List<DayOfWeek>
  607. {
  608. program.StartDate.ToLocalTime().DayOfWeek
  609. };
  610. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  611. info.Name = program.Name;
  612. info.ChannelId = program.ChannelId;
  613. info.ChannelName = program.ChannelName;
  614. info.EndDate = program.EndDate;
  615. info.StartDate = program.StartDate;
  616. info.Name = program.Name;
  617. info.Overview = program.Overview;
  618. info.ProgramId = program.Id;
  619. info.ExternalProgramId = program.ExternalId;
  620. return info;
  621. }
  622. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  623. {
  624. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  625. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  626. // Set priority from default values
  627. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  628. info.Priority = defaultValues.Priority;
  629. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  630. }
  631. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  632. {
  633. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  634. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  635. // Set priority from default values
  636. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  637. info.Priority = defaultValues.Priority;
  638. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  639. }
  640. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  641. {
  642. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  643. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  644. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  645. }
  646. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  647. {
  648. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  649. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  650. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  651. }
  652. private List<string> GetRecordingGroupNames(RecordingInfo recording)
  653. {
  654. var list = new List<string>();
  655. if (recording.IsSeries)
  656. {
  657. list.Add(recording.Name);
  658. }
  659. if (recording.IsKids)
  660. {
  661. list.Add("Kids");
  662. }
  663. if (recording.IsMovie)
  664. {
  665. list.Add("Movies");
  666. }
  667. if (recording.IsNews)
  668. {
  669. list.Add("News");
  670. }
  671. if (recording.IsSports)
  672. {
  673. list.Add("Sports");
  674. }
  675. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  676. {
  677. list.Add("Others");
  678. }
  679. return list;
  680. }
  681. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  682. {
  683. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  684. .GetMD5())
  685. .ToList();
  686. }
  687. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  688. {
  689. var recordingResult = await GetRecordings(new RecordingQuery
  690. {
  691. UserId = query.UserId
  692. }, cancellationToken).ConfigureAwait(false);
  693. var recordings = recordingResult.Items;
  694. var groups = new List<RecordingGroupDto>();
  695. var series = recordings
  696. .Where(i => i.IsSeries)
  697. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  698. .ToList();
  699. groups.AddRange(series.OrderBy(i => i.Key).Select(i => new RecordingGroupDto
  700. {
  701. Name = i.Key,
  702. RecordingCount = i.Count()
  703. }));
  704. groups.Add(new RecordingGroupDto
  705. {
  706. Name = "Kids",
  707. RecordingCount = recordings.Count(i => i.IsKids)
  708. });
  709. groups.Add(new RecordingGroupDto
  710. {
  711. Name = "Movies",
  712. RecordingCount = recordings.Count(i => i.IsMovie)
  713. });
  714. groups.Add(new RecordingGroupDto
  715. {
  716. Name = "News",
  717. RecordingCount = recordings.Count(i => i.IsNews)
  718. });
  719. groups.Add(new RecordingGroupDto
  720. {
  721. Name = "Sports",
  722. RecordingCount = recordings.Count(i => i.IsSports)
  723. });
  724. groups.Add(new RecordingGroupDto
  725. {
  726. Name = "Others",
  727. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  728. });
  729. groups = groups
  730. .Where(i => i.RecordingCount > 0)
  731. .ToList();
  732. foreach (var group in groups)
  733. {
  734. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  735. }
  736. return new QueryResult<RecordingGroupDto>
  737. {
  738. Items = groups.ToArray(),
  739. TotalRecordCount = groups.Count
  740. };
  741. }
  742. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  743. {
  744. return ActiveService.CloseLiveStream(id, cancellationToken);
  745. }
  746. public GuideInfo GetGuideInfo()
  747. {
  748. var programs = _programs.ToList();
  749. var startDate = programs.Select(i => i.Value.ProgramInfo.StartDate).Min();
  750. var endDate = programs.Select(i => i.Value.ProgramInfo.StartDate).Max();
  751. return new GuideInfo
  752. {
  753. StartDate = startDate,
  754. EndDate = endDate
  755. };
  756. }
  757. }
  758. }