LiveTvManager.cs 64 KB

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