LiveTvManager.cs 65 KB

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