LiveTvManager.cs 31 KB

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