LiveTvManager.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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.ChannelIdList.Length > 0)
  258. {
  259. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  260. var serviceName = ActiveService.Name;
  261. programs = programs.Where(i =>
  262. {
  263. var programChannelId = i.ProgramInfo.ChannelId;
  264. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
  265. return guids.Contains(internalProgramChannelId);
  266. });
  267. }
  268. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  269. if (user != null)
  270. {
  271. programs = programs.Where(i => i.IsParentalAllowed(user));
  272. }
  273. var returnArray = programs
  274. .OrderBy(i => i.ProgramInfo.StartDate)
  275. .Select(i =>
  276. {
  277. var channel = GetChannel(i);
  278. var channelName = channel == null ? null : channel.ChannelInfo.Name;
  279. return _tvDtoService.GetProgramInfoDto(i, channelName, user);
  280. })
  281. .ToArray();
  282. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  283. var result = new QueryResult<ProgramInfoDto>
  284. {
  285. Items = returnArray,
  286. TotalRecordCount = returnArray.Length
  287. };
  288. return result;
  289. }
  290. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  291. {
  292. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  293. var timerList = timers.ToList();
  294. foreach (var program in programs)
  295. {
  296. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  297. if (timer != null)
  298. {
  299. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  300. .ToString("N");
  301. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  302. {
  303. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  304. .ToString("N");
  305. }
  306. }
  307. }
  308. }
  309. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  310. {
  311. // Avoid implicitly captured closure
  312. var service = ActiveService;
  313. if (service == null)
  314. {
  315. progress.Report(100);
  316. return;
  317. }
  318. progress.Report(10);
  319. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  320. var allChannelsList = allChannels.ToList();
  321. var list = new List<LiveTvChannel>();
  322. var numComplete = 0;
  323. foreach (var channelInfo in allChannelsList)
  324. {
  325. try
  326. {
  327. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  328. list.Add(item);
  329. }
  330. catch (OperationCanceledException)
  331. {
  332. throw;
  333. }
  334. catch (Exception ex)
  335. {
  336. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  337. }
  338. numComplete++;
  339. double percent = numComplete;
  340. percent /= allChannelsList.Count;
  341. progress.Report(5 * percent + 10);
  342. }
  343. _channels = list.ToDictionary(i => i.Id);
  344. progress.Report(15);
  345. numComplete = 0;
  346. var programs = new List<LiveTvProgram>();
  347. foreach (var item in list)
  348. {
  349. // Avoid implicitly captured closure
  350. var currentChannel = item;
  351. try
  352. {
  353. var channelPrograms = await service.GetProgramsAsync(currentChannel.ChannelInfo.Id, cancellationToken).ConfigureAwait(false);
  354. var programTasks = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelInfo.ChannelType, service.Name, cancellationToken));
  355. var programEntities = await Task.WhenAll(programTasks).ConfigureAwait(false);
  356. programs.AddRange(programEntities);
  357. }
  358. catch (OperationCanceledException)
  359. {
  360. throw;
  361. }
  362. catch (Exception ex)
  363. {
  364. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  365. }
  366. numComplete++;
  367. double percent = numComplete;
  368. percent /= allChannelsList.Count;
  369. progress.Report(90 * percent + 10);
  370. }
  371. _programs = programs.ToDictionary(i => i.Id);
  372. }
  373. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  374. {
  375. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  376. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  377. }
  378. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  379. {
  380. var service = ActiveService;
  381. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  382. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  383. if (!string.IsNullOrEmpty(query.ChannelId))
  384. {
  385. var guid = new Guid(query.ChannelId);
  386. var currentServiceName = service.Name;
  387. recordings = recordings
  388. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  389. }
  390. if (!string.IsNullOrEmpty(query.Id))
  391. {
  392. var guid = new Guid(query.Id);
  393. var currentServiceName = service.Name;
  394. recordings = recordings
  395. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  396. }
  397. if (!string.IsNullOrEmpty(query.GroupId))
  398. {
  399. var guid = new Guid(query.GroupId);
  400. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  401. }
  402. if (query.IsRecording.HasValue)
  403. {
  404. var val = query.IsRecording.Value;
  405. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  406. }
  407. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  408. entities = entities.OrderByDescending(i => i.RecordingInfo.StartDate);
  409. if (user != null)
  410. {
  411. var currentUser = user;
  412. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  413. }
  414. if (query.StartIndex.HasValue)
  415. {
  416. entities = entities.Skip(query.StartIndex.Value);
  417. }
  418. if (query.Limit.HasValue)
  419. {
  420. entities = entities.Take(query.Limit.Value);
  421. }
  422. var returnArray = entities
  423. .Select(i =>
  424. {
  425. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  426. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  427. })
  428. .ToArray();
  429. return new QueryResult<RecordingInfoDto>
  430. {
  431. Items = returnArray,
  432. TotalRecordCount = returnArray.Length
  433. };
  434. }
  435. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  436. {
  437. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  438. return Task.WhenAll(tasks);
  439. }
  440. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  441. {
  442. IEnumerable<ILiveTvService> services = _services;
  443. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  444. {
  445. var channel = GetInternalChannel(channelId);
  446. if (channel != null)
  447. {
  448. serviceName = channel.ServiceName;
  449. }
  450. }
  451. if (!string.IsNullOrEmpty(serviceName))
  452. {
  453. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  454. }
  455. return services;
  456. }
  457. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  458. {
  459. var service = ActiveService;
  460. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  461. if (!string.IsNullOrEmpty(query.ChannelId))
  462. {
  463. var guid = new Guid(query.ChannelId);
  464. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  465. }
  466. var returnArray = timers
  467. .Select(i =>
  468. {
  469. var program = string.IsNullOrEmpty(i.ProgramId) ? null : GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"));
  470. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  471. return _tvDtoService.GetTimerInfoDto(i, service, program, channel);
  472. })
  473. .OrderBy(i => i.StartDate)
  474. .ToArray();
  475. return new QueryResult<TimerInfoDto>
  476. {
  477. Items = returnArray,
  478. TotalRecordCount = returnArray.Length
  479. };
  480. }
  481. public async Task DeleteRecording(string recordingId)
  482. {
  483. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  484. if (recording == null)
  485. {
  486. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  487. }
  488. var service = GetServices(recording.ServiceName, null)
  489. .First();
  490. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  491. }
  492. public async Task CancelTimer(string id)
  493. {
  494. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  495. if (timer == null)
  496. {
  497. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  498. }
  499. var service = GetServices(timer.ServiceName, null)
  500. .First();
  501. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  502. }
  503. public async Task CancelSeriesTimer(string id)
  504. {
  505. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  506. if (timer == null)
  507. {
  508. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  509. }
  510. var service = GetServices(timer.ServiceName, null)
  511. .First();
  512. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  513. }
  514. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  515. {
  516. var results = await GetRecordings(new RecordingQuery
  517. {
  518. UserId = user == null ? null : user.Id.ToString("N"),
  519. Id = id
  520. }, cancellationToken).ConfigureAwait(false);
  521. return results.Items.FirstOrDefault();
  522. }
  523. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  524. {
  525. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  526. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  527. }
  528. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  529. {
  530. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  531. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  532. }
  533. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  534. {
  535. var service = ActiveService;
  536. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  537. var returnArray = timers
  538. .Select(i =>
  539. {
  540. string channelName = null;
  541. if (!string.IsNullOrEmpty(i.ChannelId))
  542. {
  543. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  544. var channel = GetInternalChannel(internalChannelId);
  545. channelName = channel == null ? null : channel.ChannelInfo.Name;
  546. }
  547. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  548. })
  549. .OrderByDescending(i => i.StartDate)
  550. .ToArray();
  551. return new QueryResult<SeriesTimerInfoDto>
  552. {
  553. Items = returnArray,
  554. TotalRecordCount = returnArray.Length
  555. };
  556. }
  557. public Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  558. {
  559. var channel = GetInternalChannel(id);
  560. var dto = _tvDtoService.GetChannelInfoDto(channel, GetCurrentProgram(channel.ChannelInfo.Id), user);
  561. return Task.FromResult(dto);
  562. }
  563. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  564. {
  565. var now = DateTime.UtcNow;
  566. return _programs.Values
  567. .Where(i => string.Equals(externalChannelId, i.ProgramInfo.ChannelId, StringComparison.OrdinalIgnoreCase))
  568. .OrderBy(i => i.ProgramInfo.StartDate)
  569. .SkipWhile(i => now >= i.ProgramInfo.EndDate)
  570. .FirstOrDefault();
  571. }
  572. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  573. {
  574. var service = ActiveService;
  575. var info = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  576. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, service, null);
  577. obj.Id = obj.ExternalId = string.Empty;
  578. return obj;
  579. }
  580. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  581. {
  582. var info = await GetNewTimerDefaults(cancellationToken).ConfigureAwait(false);
  583. var program = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  584. info.Days = new List<DayOfWeek>
  585. {
  586. program.StartDate.ToLocalTime().DayOfWeek
  587. };
  588. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  589. info.Name = program.Name;
  590. info.ChannelId = program.ChannelId;
  591. info.ChannelName = program.ChannelName;
  592. info.EndDate = program.EndDate;
  593. info.StartDate = program.StartDate;
  594. info.Name = program.Name;
  595. info.Overview = program.Overview;
  596. info.ProgramId = program.Id;
  597. info.ExternalProgramId = program.ExternalId;
  598. return info;
  599. }
  600. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  601. {
  602. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  603. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  604. // Set priority from default values
  605. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  606. info.Priority = defaultValues.Priority;
  607. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  608. }
  609. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  610. {
  611. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  612. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  613. // Set priority from default values
  614. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  615. info.Priority = defaultValues.Priority;
  616. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  617. }
  618. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  619. {
  620. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  621. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  622. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  623. }
  624. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  625. {
  626. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  627. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  628. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  629. }
  630. private List<string> GetRecordingGroupNames(RecordingInfo recording)
  631. {
  632. var list = new List<string>();
  633. if (recording.IsSeries)
  634. {
  635. list.Add(recording.Name);
  636. }
  637. if (recording.IsKids)
  638. {
  639. list.Add("Kids");
  640. }
  641. if (recording.IsMovie)
  642. {
  643. list.Add("Movies");
  644. }
  645. if (recording.IsNews)
  646. {
  647. list.Add("News");
  648. }
  649. if (recording.IsPremiere)
  650. {
  651. list.Add("Sports");
  652. }
  653. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  654. {
  655. list.Add("Others");
  656. }
  657. return list;
  658. }
  659. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  660. {
  661. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  662. .GetMD5())
  663. .ToList();
  664. }
  665. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  666. {
  667. var recordingResult = await GetRecordings(new RecordingQuery
  668. {
  669. UserId = query.UserId
  670. }, cancellationToken).ConfigureAwait(false);
  671. var recordings = recordingResult.Items;
  672. var groups = new List<RecordingGroupDto>();
  673. var series = recordings
  674. .Where(i => i.IsSeries)
  675. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  676. .ToList();
  677. groups.AddRange(series.OrderBy(i => i.Key).Select(i => new RecordingGroupDto
  678. {
  679. Name = i.Key,
  680. RecordingCount = i.Count()
  681. }));
  682. groups.Add(new RecordingGroupDto
  683. {
  684. Name = "Kids",
  685. RecordingCount = recordings.Count(i => i.IsKids)
  686. });
  687. groups.Add(new RecordingGroupDto
  688. {
  689. Name = "Movies",
  690. RecordingCount = recordings.Count(i => i.IsMovie)
  691. });
  692. groups.Add(new RecordingGroupDto
  693. {
  694. Name = "News",
  695. RecordingCount = recordings.Count(i => i.IsNews)
  696. });
  697. groups.Add(new RecordingGroupDto
  698. {
  699. Name = "Sports",
  700. RecordingCount = recordings.Count(i => i.IsSports)
  701. });
  702. groups.Add(new RecordingGroupDto
  703. {
  704. Name = "Others",
  705. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  706. });
  707. groups = groups
  708. .Where(i => i.RecordingCount > 0)
  709. .ToList();
  710. foreach (var group in groups)
  711. {
  712. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  713. }
  714. return new QueryResult<RecordingGroupDto>
  715. {
  716. Items = groups.ToArray(),
  717. TotalRecordCount = groups.Count
  718. };
  719. }
  720. }
  721. }