LiveTvManager.cs 66 KB

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