LiveTvManager.cs 66 KB

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