LiveTvManager.cs 63 KB

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