LiveTvManager.cs 32 KB

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