LiveTvManager.cs 65 KB

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