LiveTvManager.cs 66 KB

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