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