LiveTvManager.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Controller.Sorting;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.LiveTv;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Querying;
  17. using System;
  18. using System.Collections.Concurrent;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Server.Implementations.LiveTv
  25. {
  26. /// <summary>
  27. /// Class LiveTvManager
  28. /// </summary>
  29. public class LiveTvManager : ILiveTvManager, IDisposable
  30. {
  31. private readonly IServerConfigurationManager _config;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly ILogger _logger;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IUserManager _userManager;
  36. private readonly IUserDataManager _userDataManager;
  37. private readonly ILibraryManager _libraryManager;
  38. private readonly ITaskManager _taskManager;
  39. private readonly LiveTvDtoService _tvDtoService;
  40. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  41. private readonly ConcurrentDictionary<string, LiveStreamInfo> _openStreams =
  42. new ConcurrentDictionary<string, LiveStreamInfo>();
  43. private List<Guid> _channelIdList = new List<Guid>();
  44. private Dictionary<Guid, LiveTvProgram> _programs = new Dictionary<Guid, LiveTvProgram>();
  45. private readonly ConcurrentDictionary<Guid, bool> _refreshedPrograms = new ConcurrentDictionary<Guid, bool>();
  46. private readonly SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(1, 1);
  47. public LiveTvManager(IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager)
  48. {
  49. _config = config;
  50. _fileSystem = fileSystem;
  51. _logger = logger;
  52. _itemRepo = itemRepo;
  53. _userManager = userManager;
  54. _libraryManager = libraryManager;
  55. _taskManager = taskManager;
  56. _userDataManager = userDataManager;
  57. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, _itemRepo);
  58. }
  59. /// <summary>
  60. /// Gets the services.
  61. /// </summary>
  62. /// <value>The services.</value>
  63. public IReadOnlyList<ILiveTvService> Services
  64. {
  65. get { return _services; }
  66. }
  67. public ILiveTvService ActiveService { get; private set; }
  68. /// <summary>
  69. /// Adds the parts.
  70. /// </summary>
  71. /// <param name="services">The services.</param>
  72. public void AddParts(IEnumerable<ILiveTvService> services)
  73. {
  74. _services.AddRange(services);
  75. SetActiveService(_config.Configuration.LiveTvOptions.ActiveService);
  76. }
  77. private void SetActiveService(string name)
  78. {
  79. var service = _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  80. _services.FirstOrDefault();
  81. SetActiveService(service);
  82. }
  83. private void SetActiveService(ILiveTvService service)
  84. {
  85. if (ActiveService != null)
  86. {
  87. ActiveService.DataSourceChanged -= service_DataSourceChanged;
  88. }
  89. ActiveService = service;
  90. if (service != null)
  91. {
  92. service.DataSourceChanged += service_DataSourceChanged;
  93. }
  94. }
  95. void service_DataSourceChanged(object sender, EventArgs e)
  96. {
  97. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  98. }
  99. public async Task<QueryResult<ChannelInfoDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
  100. {
  101. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  102. var channels = _channelIdList.Select(_libraryManager.GetItemById)
  103. .Where(i => i != null)
  104. .OfType<LiveTvChannel>();
  105. if (user != null)
  106. {
  107. // Avoid implicitly captured closure
  108. var currentUser = user;
  109. channels = channels
  110. .Where(i => i.IsParentalAllowed(currentUser))
  111. .OrderBy(i =>
  112. {
  113. double number = 0;
  114. if (!string.IsNullOrEmpty(i.Number))
  115. {
  116. double.TryParse(i.Number, out number);
  117. }
  118. return number;
  119. });
  120. if (query.IsFavorite.HasValue)
  121. {
  122. var val = query.IsFavorite.Value;
  123. channels = channels
  124. .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
  125. }
  126. }
  127. channels = channels.OrderBy(i =>
  128. {
  129. double number = 0;
  130. if (!string.IsNullOrEmpty(i.Number))
  131. {
  132. double.TryParse(i.Number, out number);
  133. }
  134. return number;
  135. }).ThenBy(i => i.Name);
  136. var allChannels = channels.ToList();
  137. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  138. if (query.StartIndex.HasValue)
  139. {
  140. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  141. }
  142. if (query.Limit.HasValue)
  143. {
  144. allEnumerable = allEnumerable.Take(query.Limit.Value);
  145. }
  146. var returnList = new List<ChannelInfoDto>();
  147. foreach (var channel in allEnumerable)
  148. {
  149. var currentProgram = await GetCurrentProgram(channel.ExternalId, cancellationToken).ConfigureAwait(false);
  150. returnList.Add(_tvDtoService.GetChannelInfoDto(channel, currentProgram, user));
  151. }
  152. var result = new QueryResult<ChannelInfoDto>
  153. {
  154. Items = returnList.ToArray(),
  155. TotalRecordCount = allChannels.Count
  156. };
  157. return result;
  158. }
  159. public LiveTvChannel GetInternalChannel(string id)
  160. {
  161. return GetInternalChannel(new Guid(id));
  162. }
  163. private LiveTvChannel GetInternalChannel(Guid id)
  164. {
  165. return _libraryManager.GetItemById(id) as LiveTvChannel;
  166. }
  167. public async Task<LiveTvProgram> GetInternalProgram(string id, CancellationToken cancellationToken)
  168. {
  169. var guid = new Guid(id);
  170. LiveTvProgram obj = null;
  171. _programs.TryGetValue(guid, out obj);
  172. if (obj != null)
  173. {
  174. await RefreshIfNeeded(obj, cancellationToken).ConfigureAwait(false);
  175. }
  176. return obj;
  177. }
  178. private async Task RefreshIfNeeded(IEnumerable<LiveTvProgram> programs, CancellationToken cancellationToken)
  179. {
  180. foreach (var program in programs)
  181. {
  182. await RefreshIfNeeded(program, cancellationToken).ConfigureAwait(false);
  183. }
  184. }
  185. private async Task RefreshIfNeeded(LiveTvProgram program, CancellationToken cancellationToken)
  186. {
  187. if (_refreshedPrograms.ContainsKey(program.Id))
  188. {
  189. return;
  190. }
  191. await program.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  192. _refreshedPrograms.TryAdd(program.Id, true);
  193. }
  194. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  195. {
  196. var service = ActiveService;
  197. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  198. var recording = recordings.FirstOrDefault(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  199. return await GetRecording(recording, service.Name, cancellationToken).ConfigureAwait(false);
  200. }
  201. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  202. public async Task<LiveStreamInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  203. {
  204. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  205. try
  206. {
  207. var service = ActiveService;
  208. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  209. var recording = recordings.First(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  210. var result = await service.GetRecordingStream(recording.Id, cancellationToken).ConfigureAwait(false);
  211. if (!string.IsNullOrEmpty(result.Id))
  212. {
  213. _openStreams.AddOrUpdate(result.Id, result, (key, info) => result);
  214. }
  215. return result;
  216. }
  217. catch (Exception ex)
  218. {
  219. _logger.ErrorException("Error getting recording stream", ex);
  220. throw;
  221. }
  222. finally
  223. {
  224. _liveStreamSemaphore.Release();
  225. }
  226. }
  227. public async Task<LiveStreamInfo> GetChannelStream(string id, CancellationToken cancellationToken)
  228. {
  229. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  230. try
  231. {
  232. var service = ActiveService;
  233. var channel = GetInternalChannel(id);
  234. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  235. var result = await service.GetChannelStream(channel.ExternalId, cancellationToken).ConfigureAwait(false);
  236. if (!string.IsNullOrEmpty(result.Id))
  237. {
  238. _openStreams.AddOrUpdate(result.Id, result, (key, info) => result);
  239. }
  240. return result;
  241. }
  242. catch (Exception ex)
  243. {
  244. _logger.ErrorException("Error getting channel stream", ex);
  245. throw;
  246. }
  247. finally
  248. {
  249. _liveStreamSemaphore.Release();
  250. }
  251. }
  252. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  253. {
  254. var path = Path.Combine(_config.ApplicationPaths.ItemsByNamePath, "tvchannels", _fileSystem.GetValidFilename(channelInfo.Name));
  255. var fileInfo = new DirectoryInfo(path);
  256. var isNew = false;
  257. if (!fileInfo.Exists)
  258. {
  259. _logger.Debug("Creating directory {0}", path);
  260. Directory.CreateDirectory(path);
  261. fileInfo = new DirectoryInfo(path);
  262. if (!fileInfo.Exists)
  263. {
  264. throw new IOException("Path not created: " + path);
  265. }
  266. isNew = true;
  267. }
  268. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  269. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  270. if (item == null)
  271. {
  272. item = new LiveTvChannel
  273. {
  274. Name = channelInfo.Name,
  275. Id = id,
  276. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  277. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  278. Path = path
  279. };
  280. isNew = true;
  281. }
  282. item.ChannelType = channelInfo.ChannelType;
  283. item.ProviderImageUrl = channelInfo.ImageUrl;
  284. item.HasProviderImage = channelInfo.HasImage;
  285. item.ProviderImagePath = channelInfo.ImagePath;
  286. item.ExternalId = channelInfo.Id;
  287. item.ServiceName = serviceName;
  288. item.Number = channelInfo.Number;
  289. if (string.IsNullOrEmpty(item.Name))
  290. {
  291. item.Name = channelInfo.Name;
  292. }
  293. await item.RefreshMetadata(new MetadataRefreshOptions
  294. {
  295. ForceSave = isNew
  296. }, cancellationToken);
  297. return item;
  298. }
  299. private LiveTvProgram GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  300. {
  301. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  302. var item = _itemRepo.RetrieveItem(id) as LiveTvProgram;
  303. if (item == null)
  304. {
  305. item = new LiveTvProgram
  306. {
  307. Name = info.Name,
  308. Id = id,
  309. DateCreated = DateTime.UtcNow,
  310. DateModified = DateTime.UtcNow
  311. };
  312. }
  313. item.ChannelType = channelType;
  314. item.ServiceName = serviceName;
  315. item.Audio = info.Audio;
  316. item.ExternalChannelId = info.ChannelId;
  317. item.CommunityRating = info.CommunityRating;
  318. item.EndDate = info.EndDate;
  319. item.EpisodeTitle = info.EpisodeTitle;
  320. item.ExternalId = info.Id;
  321. item.Genres = info.Genres;
  322. item.HasProviderImage = info.HasImage;
  323. item.IsHD = info.IsHD;
  324. item.IsKids = info.IsKids;
  325. item.IsLive = info.IsLive;
  326. item.IsMovie = info.IsMovie;
  327. item.IsNews = info.IsNews;
  328. item.IsPremiere = info.IsPremiere;
  329. item.IsRepeat = info.IsRepeat;
  330. item.IsSeries = info.IsSeries;
  331. item.IsSports = info.IsSports;
  332. item.Name = info.Name;
  333. item.OfficialRating = info.OfficialRating;
  334. item.Overview = info.Overview;
  335. item.PremiereDate = info.OriginalAirDate;
  336. item.ProviderImagePath = info.ImagePath;
  337. item.ProviderImageUrl = info.ImageUrl;
  338. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  339. item.StartDate = info.StartDate;
  340. return item;
  341. }
  342. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  343. {
  344. var isNew = false;
  345. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  346. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  347. if (item == null)
  348. {
  349. if (info.ChannelType == ChannelType.TV)
  350. {
  351. item = new LiveTvVideoRecording
  352. {
  353. Name = info.Name,
  354. Id = id,
  355. DateCreated = DateTime.UtcNow,
  356. DateModified = DateTime.UtcNow,
  357. VideoType = VideoType.VideoFile
  358. };
  359. }
  360. else
  361. {
  362. item = new LiveTvAudioRecording
  363. {
  364. Name = info.Name,
  365. Id = id,
  366. DateCreated = DateTime.UtcNow,
  367. DateModified = DateTime.UtcNow
  368. };
  369. }
  370. if (!string.IsNullOrEmpty(info.Path))
  371. {
  372. item.Path = info.Path;
  373. }
  374. else if (!string.IsNullOrEmpty(info.Url))
  375. {
  376. item.Path = info.Url;
  377. }
  378. isNew = true;
  379. }
  380. item.RecordingInfo = info;
  381. item.ServiceName = serviceName;
  382. await item.RefreshMetadata(new MetadataRefreshOptions
  383. {
  384. ForceSave = isNew
  385. }, cancellationToken);
  386. _libraryManager.RegisterItem((BaseItem)item);
  387. return item;
  388. }
  389. private LiveTvChannel GetChannel(LiveTvProgram program)
  390. {
  391. var programChannelId = program.ExternalChannelId;
  392. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  393. return GetInternalChannel(internalProgramChannelId);
  394. }
  395. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  396. {
  397. var program = await GetInternalProgram(id, cancellationToken).ConfigureAwait(false);
  398. var channel = GetChannel(program);
  399. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  400. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  401. return dto;
  402. }
  403. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  404. {
  405. IEnumerable<LiveTvProgram> programs = _programs.Values;
  406. if (query.MinEndDate.HasValue)
  407. {
  408. var val = query.MinEndDate.Value;
  409. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  410. }
  411. if (query.MinStartDate.HasValue)
  412. {
  413. var val = query.MinStartDate.Value;
  414. programs = programs.Where(i => i.StartDate >= val);
  415. }
  416. if (query.MaxEndDate.HasValue)
  417. {
  418. var val = query.MaxEndDate.Value;
  419. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  420. }
  421. if (query.MaxStartDate.HasValue)
  422. {
  423. var val = query.MaxStartDate.Value;
  424. programs = programs.Where(i => i.StartDate <= val);
  425. }
  426. if (query.ChannelIdList.Length > 0)
  427. {
  428. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  429. var serviceName = ActiveService.Name;
  430. programs = programs.Where(i =>
  431. {
  432. var programChannelId = i.ExternalChannelId;
  433. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
  434. return guids.Contains(internalProgramChannelId);
  435. });
  436. }
  437. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  438. if (user != null)
  439. {
  440. // Avoid implicitly captured closure
  441. var currentUser = user;
  442. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  443. }
  444. var programList = programs.ToList();
  445. var returnArray = programList
  446. .Select(i =>
  447. {
  448. var channel = GetChannel(i);
  449. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  450. })
  451. .ToArray();
  452. await RefreshIfNeeded(programList, cancellationToken).ConfigureAwait(false);
  453. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  454. var result = new QueryResult<ProgramInfoDto>
  455. {
  456. Items = returnArray,
  457. TotalRecordCount = returnArray.Length
  458. };
  459. return result;
  460. }
  461. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  462. {
  463. IEnumerable<LiveTvProgram> programs = _programs.Values;
  464. var user = _userManager.GetUserById(new Guid(query.UserId));
  465. // Avoid implicitly captured closure
  466. var currentUser = user;
  467. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  468. if (query.IsAiring.HasValue)
  469. {
  470. var val = query.IsAiring.Value;
  471. programs = programs.Where(i => i.IsAiring == val);
  472. }
  473. if (query.HasAired.HasValue)
  474. {
  475. var val = query.HasAired.Value;
  476. programs = programs.Where(i => i.HasAired == val);
  477. }
  478. var serviceName = ActiveService.Name;
  479. var programList = programs.ToList();
  480. var genres = programList.SelectMany(i => i.Genres)
  481. .Distinct(StringComparer.OrdinalIgnoreCase)
  482. .Select(i => _libraryManager.GetGenre(i))
  483. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  484. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  485. .ThenByDescending(i => GetRecommendationScore(i, user.Id, serviceName, genres))
  486. .ThenBy(i => i.StartDate);
  487. if (query.Limit.HasValue)
  488. {
  489. programs = programs.Take(query.Limit.Value)
  490. .OrderBy(i => i.StartDate);
  491. }
  492. programList = programs.ToList();
  493. await RefreshIfNeeded(programList, cancellationToken).ConfigureAwait(false);
  494. var returnArray = programList
  495. .Select(i =>
  496. {
  497. var channel = GetChannel(i);
  498. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  499. })
  500. .ToArray();
  501. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  502. var result = new QueryResult<ProgramInfoDto>
  503. {
  504. Items = returnArray,
  505. TotalRecordCount = returnArray.Length
  506. };
  507. return result;
  508. }
  509. private int GetRecommendationScore(LiveTvProgram program, Guid userId, string serviceName, Dictionary<string, Genre> genres)
  510. {
  511. var score = 0;
  512. if (program.IsLive)
  513. {
  514. score++;
  515. }
  516. if (program.IsSeries && !program.IsRepeat)
  517. {
  518. score++;
  519. }
  520. var internalChannelId = _tvDtoService.GetInternalChannelId(serviceName, program.ExternalChannelId);
  521. var channel = GetInternalChannel(internalChannelId);
  522. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  523. if ((channelUserdata.Likes ?? false))
  524. {
  525. score += 2;
  526. }
  527. else if (!(channelUserdata.Likes ?? true))
  528. {
  529. score -= 2;
  530. }
  531. if (channelUserdata.IsFavorite)
  532. {
  533. score += 3;
  534. }
  535. score += GetGenreScore(program.Genres, userId, genres);
  536. return score;
  537. }
  538. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  539. {
  540. return programGenres.Select(i =>
  541. {
  542. var score = 0;
  543. Genre genre;
  544. if (genres.TryGetValue(i, out genre))
  545. {
  546. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  547. if ((genreUserdata.Likes ?? false))
  548. {
  549. score++;
  550. }
  551. else if (!(genreUserdata.Likes ?? true))
  552. {
  553. score--;
  554. }
  555. if (genreUserdata.IsFavorite)
  556. {
  557. score += 2;
  558. }
  559. }
  560. return score;
  561. }).Sum();
  562. }
  563. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  564. {
  565. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  566. var timerList = timers.ToList();
  567. foreach (var program in programs)
  568. {
  569. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  570. if (timer != null)
  571. {
  572. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  573. .ToString("N");
  574. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  575. {
  576. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  577. .ToString("N");
  578. }
  579. }
  580. }
  581. }
  582. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  583. {
  584. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  585. try
  586. {
  587. await RefreshChannelsInternal(progress, cancellationToken).ConfigureAwait(false);
  588. }
  589. finally
  590. {
  591. _refreshSemaphore.Release();
  592. }
  593. }
  594. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  595. {
  596. // Avoid implicitly captured closure
  597. var service = ActiveService;
  598. if (service == null)
  599. {
  600. progress.Report(100);
  601. return;
  602. }
  603. progress.Report(10);
  604. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  605. var allChannelsList = allChannels.ToList();
  606. var list = new List<LiveTvChannel>();
  607. var numComplete = 0;
  608. foreach (var channelInfo in allChannelsList)
  609. {
  610. cancellationToken.ThrowIfCancellationRequested();
  611. try
  612. {
  613. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  614. list.Add(item);
  615. _libraryManager.RegisterItem(item);
  616. }
  617. catch (OperationCanceledException)
  618. {
  619. throw;
  620. }
  621. catch (Exception ex)
  622. {
  623. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  624. }
  625. numComplete++;
  626. double percent = numComplete;
  627. percent /= allChannelsList.Count;
  628. progress.Report(5 * percent + 10);
  629. }
  630. _channelIdList = list.Select(i => i.Id).ToList();
  631. progress.Report(15);
  632. numComplete = 0;
  633. var programs = new List<LiveTvProgram>();
  634. var guideDays = GetGuideDays(list.Count);
  635. cancellationToken.ThrowIfCancellationRequested();
  636. foreach (var item in list)
  637. {
  638. cancellationToken.ThrowIfCancellationRequested();
  639. // Avoid implicitly captured closure
  640. var currentChannel = item;
  641. try
  642. {
  643. var start = DateTime.UtcNow.AddHours(-1);
  644. var end = start.AddDays(guideDays);
  645. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  646. var programEntities = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken));
  647. programs.AddRange(programEntities);
  648. }
  649. catch (OperationCanceledException)
  650. {
  651. throw;
  652. }
  653. catch (Exception ex)
  654. {
  655. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  656. }
  657. numComplete++;
  658. double percent = numComplete;
  659. percent /= allChannelsList.Count;
  660. progress.Report(80 * percent + 10);
  661. }
  662. _programs = programs.ToDictionary(i => i.Id);
  663. _refreshedPrograms.Clear();
  664. progress.Report(90);
  665. // Load these now which will prefetch metadata
  666. await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  667. progress.Report(100);
  668. }
  669. public async Task CleanDatabase(IProgress<double> progress, CancellationToken cancellationToken)
  670. {
  671. var service = ActiveService;
  672. if (service == null)
  673. {
  674. progress.Report(100);
  675. return;
  676. }
  677. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  678. try
  679. {
  680. await DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken).ConfigureAwait(false);
  681. }
  682. finally
  683. {
  684. _refreshSemaphore.Release();
  685. }
  686. }
  687. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  688. {
  689. var list = _itemRepo.GetItemsOfType(typeof(LiveTvProgram)).ToList();
  690. var numComplete = 0;
  691. foreach (var program in list)
  692. {
  693. cancellationToken.ThrowIfCancellationRequested();
  694. if (!currentIdList.Contains(program.Id))
  695. {
  696. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  697. }
  698. numComplete++;
  699. double percent = numComplete;
  700. percent /= list.Count;
  701. progress.Report(100 * percent);
  702. }
  703. }
  704. private double GetGuideDays(int channelCount)
  705. {
  706. if (_config.Configuration.LiveTvOptions.GuideDays.HasValue)
  707. {
  708. return _config.Configuration.LiveTvOptions.GuideDays.Value;
  709. }
  710. var programsPerDay = channelCount * 48;
  711. const int maxPrograms = 24000;
  712. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  713. // No less than 2, no more than 7
  714. return Math.Max(2, Math.Min(days, 7));
  715. }
  716. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  717. {
  718. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  719. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  720. }
  721. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  722. {
  723. var service = ActiveService;
  724. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  725. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  726. if (!string.IsNullOrEmpty(query.ChannelId))
  727. {
  728. var guid = new Guid(query.ChannelId);
  729. var currentServiceName = service.Name;
  730. recordings = recordings
  731. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  732. }
  733. if (!string.IsNullOrEmpty(query.Id))
  734. {
  735. var guid = new Guid(query.Id);
  736. var currentServiceName = service.Name;
  737. recordings = recordings
  738. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  739. }
  740. if (!string.IsNullOrEmpty(query.GroupId))
  741. {
  742. var guid = new Guid(query.GroupId);
  743. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  744. }
  745. if (query.IsInProgress.HasValue)
  746. {
  747. var val = query.IsInProgress.Value;
  748. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  749. }
  750. if (query.Status.HasValue)
  751. {
  752. var val = query.Status.Value;
  753. recordings = recordings.Where(i => (i.Status == val));
  754. }
  755. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  756. {
  757. var guid = new Guid(query.SeriesTimerId);
  758. var currentServiceName = service.Name;
  759. recordings = recordings
  760. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  761. }
  762. recordings = recordings.OrderByDescending(i => i.StartDate);
  763. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  764. if (user != null)
  765. {
  766. var currentUser = user;
  767. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  768. }
  769. var entityList = entities.ToList();
  770. entities = entityList;
  771. if (query.StartIndex.HasValue)
  772. {
  773. entities = entities.Skip(query.StartIndex.Value);
  774. }
  775. if (query.Limit.HasValue)
  776. {
  777. entities = entities.Take(query.Limit.Value);
  778. }
  779. var returnArray = entities
  780. .Select(i =>
  781. {
  782. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  783. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  784. })
  785. .ToArray();
  786. return new QueryResult<RecordingInfoDto>
  787. {
  788. Items = returnArray,
  789. TotalRecordCount = entityList.Count
  790. };
  791. }
  792. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  793. {
  794. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  795. return Task.WhenAll(tasks);
  796. }
  797. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  798. {
  799. IEnumerable<ILiveTvService> services = _services;
  800. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  801. {
  802. var channel = GetInternalChannel(channelId);
  803. if (channel != null)
  804. {
  805. serviceName = channel.ServiceName;
  806. }
  807. }
  808. if (!string.IsNullOrEmpty(serviceName))
  809. {
  810. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  811. }
  812. return services;
  813. }
  814. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  815. {
  816. var service = ActiveService;
  817. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  818. if (!string.IsNullOrEmpty(query.ChannelId))
  819. {
  820. var guid = new Guid(query.ChannelId);
  821. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  822. }
  823. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  824. {
  825. var guid = new Guid(query.SeriesTimerId);
  826. var currentServiceName = service.Name;
  827. timers = timers
  828. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  829. }
  830. var returnList = new List<TimerInfoDto>();
  831. foreach (var i in timers)
  832. {
  833. var program = string.IsNullOrEmpty(i.ProgramId) ?
  834. null :
  835. await GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"), cancellationToken).ConfigureAwait(false);
  836. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  837. returnList.Add(_tvDtoService.GetTimerInfoDto(i, service, program, channel));
  838. }
  839. var returnArray = returnList
  840. .OrderBy(i => i.StartDate)
  841. .ToArray();
  842. return new QueryResult<TimerInfoDto>
  843. {
  844. Items = returnArray,
  845. TotalRecordCount = returnArray.Length
  846. };
  847. }
  848. public async Task DeleteRecording(string recordingId)
  849. {
  850. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  851. if (recording == null)
  852. {
  853. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  854. }
  855. var service = GetServices(recording.ServiceName, null)
  856. .First();
  857. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  858. }
  859. public async Task CancelTimer(string id)
  860. {
  861. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  862. if (timer == null)
  863. {
  864. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  865. }
  866. var service = GetServices(timer.ServiceName, null)
  867. .First();
  868. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  869. }
  870. public async Task CancelSeriesTimer(string id)
  871. {
  872. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  873. if (timer == null)
  874. {
  875. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  876. }
  877. var service = GetServices(timer.ServiceName, null)
  878. .First();
  879. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  880. }
  881. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  882. {
  883. var results = await GetRecordings(new RecordingQuery
  884. {
  885. UserId = user == null ? null : user.Id.ToString("N"),
  886. Id = id
  887. }, cancellationToken).ConfigureAwait(false);
  888. return results.Items.FirstOrDefault();
  889. }
  890. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  891. {
  892. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  893. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  894. }
  895. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  896. {
  897. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  898. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  899. }
  900. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  901. {
  902. var service = ActiveService;
  903. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  904. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  905. {
  906. timers = query.SortOrder == SortOrder.Descending ?
  907. timers.OrderBy(i => i.Priority).ThenByStringDescending(i => i.Name) :
  908. timers.OrderByDescending(i => i.Priority).ThenByString(i => i.Name);
  909. }
  910. else
  911. {
  912. timers = query.SortOrder == SortOrder.Descending ?
  913. timers.OrderByStringDescending(i => i.Name) :
  914. timers.OrderByString(i => i.Name);
  915. }
  916. var returnArray = timers
  917. .Select(i =>
  918. {
  919. string channelName = null;
  920. if (!string.IsNullOrEmpty(i.ChannelId))
  921. {
  922. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  923. var channel = GetInternalChannel(internalChannelId);
  924. channelName = channel == null ? null : channel.Name;
  925. }
  926. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  927. })
  928. .ToArray();
  929. return new QueryResult<SeriesTimerInfoDto>
  930. {
  931. Items = returnArray,
  932. TotalRecordCount = returnArray.Length
  933. };
  934. }
  935. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  936. {
  937. var channel = GetInternalChannel(id);
  938. var currentProgram = await GetCurrentProgram(channel.ExternalId, cancellationToken).ConfigureAwait(false);
  939. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  940. return dto;
  941. }
  942. private async Task<LiveTvProgram> GetCurrentProgram(string externalChannelId, CancellationToken cancellationToken)
  943. {
  944. var now = DateTime.UtcNow;
  945. var program = _programs.Values
  946. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  947. .OrderBy(i => i.StartDate)
  948. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  949. .FirstOrDefault();
  950. if (program != null)
  951. {
  952. await RefreshIfNeeded(program, cancellationToken).ConfigureAwait(false);
  953. }
  954. return program;
  955. }
  956. private async Task<SeriesTimerInfo> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  957. {
  958. ProgramInfo programInfo = null;
  959. if (program != null)
  960. {
  961. programInfo = new ProgramInfo
  962. {
  963. Audio = program.Audio,
  964. ChannelId = program.ExternalChannelId,
  965. CommunityRating = program.CommunityRating,
  966. EndDate = program.EndDate ?? DateTime.MinValue,
  967. EpisodeTitle = program.EpisodeTitle,
  968. Genres = program.Genres,
  969. HasImage = program.HasProviderImage,
  970. Id = program.ExternalId,
  971. IsHD = program.IsHD,
  972. IsKids = program.IsKids,
  973. IsLive = program.IsLive,
  974. IsMovie = program.IsMovie,
  975. IsNews = program.IsNews,
  976. IsPremiere = program.IsPremiere,
  977. IsRepeat = program.IsRepeat,
  978. IsSeries = program.IsSeries,
  979. IsSports = program.IsSports,
  980. OriginalAirDate = program.PremiereDate,
  981. Overview = program.Overview,
  982. StartDate = program.StartDate,
  983. ImagePath = program.ProviderImagePath,
  984. ImageUrl = program.ProviderImageUrl,
  985. Name = program.Name,
  986. OfficialRating = program.OfficialRating
  987. };
  988. }
  989. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  990. info.Id = null;
  991. return info;
  992. }
  993. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  994. {
  995. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  996. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService, null);
  997. return obj;
  998. }
  999. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1000. {
  1001. var program = await GetInternalProgram(programId, cancellationToken).ConfigureAwait(false);
  1002. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1003. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1004. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults, ActiveService, null);
  1005. info.Days = new List<DayOfWeek>
  1006. {
  1007. program.StartDate.ToLocalTime().DayOfWeek
  1008. };
  1009. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1010. info.Name = program.Name;
  1011. info.ChannelId = programDto.ChannelId;
  1012. info.ChannelName = programDto.ChannelName;
  1013. info.StartDate = program.StartDate;
  1014. info.Name = program.Name;
  1015. info.Overview = program.Overview;
  1016. info.ProgramId = programDto.Id;
  1017. info.ExternalProgramId = programDto.ExternalId;
  1018. if (program.EndDate.HasValue)
  1019. {
  1020. info.EndDate = program.EndDate.Value;
  1021. }
  1022. return info;
  1023. }
  1024. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1025. {
  1026. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1027. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1028. // Set priority from default values
  1029. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1030. info.Priority = defaultValues.Priority;
  1031. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1032. }
  1033. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1034. {
  1035. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1036. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1037. // Set priority from default values
  1038. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1039. info.Priority = defaultValues.Priority;
  1040. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1041. }
  1042. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1043. {
  1044. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1045. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1046. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1047. }
  1048. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1049. {
  1050. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1051. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1052. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1053. }
  1054. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1055. {
  1056. var list = new List<string>();
  1057. if (recording.IsSeries)
  1058. {
  1059. list.Add(recording.Name);
  1060. }
  1061. if (recording.IsKids)
  1062. {
  1063. list.Add("Kids");
  1064. }
  1065. if (recording.IsMovie)
  1066. {
  1067. list.Add("Movies");
  1068. }
  1069. if (recording.IsNews)
  1070. {
  1071. list.Add("News");
  1072. }
  1073. if (recording.IsSports)
  1074. {
  1075. list.Add("Sports");
  1076. }
  1077. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1078. {
  1079. list.Add("Others");
  1080. }
  1081. return list;
  1082. }
  1083. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1084. {
  1085. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1086. .GetMD5())
  1087. .ToList();
  1088. }
  1089. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1090. {
  1091. var recordingResult = await GetRecordings(new RecordingQuery
  1092. {
  1093. UserId = query.UserId
  1094. }, cancellationToken).ConfigureAwait(false);
  1095. var recordings = recordingResult.Items;
  1096. var groups = new List<RecordingGroupDto>();
  1097. var series = recordings
  1098. .Where(i => i.IsSeries)
  1099. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1100. .ToList();
  1101. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1102. {
  1103. Name = i.Key,
  1104. RecordingCount = i.Count()
  1105. }));
  1106. groups.Add(new RecordingGroupDto
  1107. {
  1108. Name = "Kids",
  1109. RecordingCount = recordings.Count(i => i.IsKids)
  1110. });
  1111. groups.Add(new RecordingGroupDto
  1112. {
  1113. Name = "Movies",
  1114. RecordingCount = recordings.Count(i => i.IsMovie)
  1115. });
  1116. groups.Add(new RecordingGroupDto
  1117. {
  1118. Name = "News",
  1119. RecordingCount = recordings.Count(i => i.IsNews)
  1120. });
  1121. groups.Add(new RecordingGroupDto
  1122. {
  1123. Name = "Sports",
  1124. RecordingCount = recordings.Count(i => i.IsSports)
  1125. });
  1126. groups.Add(new RecordingGroupDto
  1127. {
  1128. Name = "Others",
  1129. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1130. });
  1131. groups = groups
  1132. .Where(i => i.RecordingCount > 0)
  1133. .ToList();
  1134. foreach (var group in groups)
  1135. {
  1136. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1137. }
  1138. return new QueryResult<RecordingGroupDto>
  1139. {
  1140. Items = groups.ToArray(),
  1141. TotalRecordCount = groups.Count
  1142. };
  1143. }
  1144. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1145. {
  1146. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1147. var service = ActiveService;
  1148. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1149. try
  1150. {
  1151. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1152. }
  1153. catch (Exception ex)
  1154. {
  1155. _logger.ErrorException("Error closing live stream", ex);
  1156. throw;
  1157. }
  1158. finally
  1159. {
  1160. _liveStreamSemaphore.Release();
  1161. }
  1162. }
  1163. public GuideInfo GetGuideInfo()
  1164. {
  1165. var programs = _programs.ToList();
  1166. var startDate = _programs.Count == 0 ? DateTime.MinValue :
  1167. programs.Select(i => i.Value.StartDate).Min();
  1168. var endDate = programs.Count == 0 ? DateTime.MinValue :
  1169. programs.Select(i => i.Value.StartDate).Max();
  1170. return new GuideInfo
  1171. {
  1172. StartDate = startDate,
  1173. EndDate = endDate
  1174. };
  1175. }
  1176. /// <summary>
  1177. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1178. /// </summary>
  1179. public void Dispose()
  1180. {
  1181. Dispose(true);
  1182. }
  1183. private readonly object _disposeLock = new object();
  1184. /// <summary>
  1185. /// Releases unmanaged and - optionally - managed resources.
  1186. /// </summary>
  1187. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1188. protected virtual void Dispose(bool dispose)
  1189. {
  1190. if (dispose)
  1191. {
  1192. lock (_disposeLock)
  1193. {
  1194. foreach (var stream in _openStreams.Values.ToList())
  1195. {
  1196. var task = CloseLiveStream(stream.Id, CancellationToken.None);
  1197. Task.WaitAll(task);
  1198. }
  1199. _openStreams.Clear();
  1200. }
  1201. }
  1202. }
  1203. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1204. {
  1205. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1206. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1207. }
  1208. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1209. {
  1210. var info = new LiveTvServiceInfo
  1211. {
  1212. Name = service.Name
  1213. };
  1214. try
  1215. {
  1216. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1217. info.Status = statusInfo.Status;
  1218. info.StatusMessage = statusInfo.StatusMessage;
  1219. info.Version = statusInfo.Version;
  1220. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1221. info.HomePageUrl = service.HomePageUrl;
  1222. info.Tuners = statusInfo.Tuners.Select(i =>
  1223. {
  1224. string channelName = null;
  1225. if (!string.IsNullOrEmpty(i.ChannelId))
  1226. {
  1227. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1228. var channel = GetInternalChannel(internalChannelId);
  1229. channelName = channel == null ? null : channel.Name;
  1230. }
  1231. return _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1232. }).ToList();
  1233. }
  1234. catch (Exception ex)
  1235. {
  1236. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name);
  1237. info.Status = LiveTvServiceStatus.Unavailable;
  1238. info.StatusMessage = ex.Message;
  1239. }
  1240. return info;
  1241. }
  1242. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1243. {
  1244. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1245. var servicesList = services.ToList();
  1246. var activeServiceInfo = ActiveService == null ? null :
  1247. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1248. var info = new LiveTvInfo
  1249. {
  1250. Services = servicesList.ToList(),
  1251. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1252. IsEnabled = ActiveService != null,
  1253. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1254. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1255. };
  1256. info.EnabledUsers = _userManager.Users
  1257. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1258. .Select(i => i.Id.ToString("N"))
  1259. .ToList();
  1260. return info;
  1261. }
  1262. /// <summary>
  1263. /// Resets the tuner.
  1264. /// </summary>
  1265. /// <param name="id">The identifier.</param>
  1266. /// <param name="cancellationToken">The cancellation token.</param>
  1267. /// <returns>Task.</returns>
  1268. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1269. {
  1270. return ActiveService.ResetTuner(id, cancellationToken);
  1271. }
  1272. }
  1273. }