LiveTvManager.cs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Common.ScheduledTasks;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.LiveTv;
  12. using MediaBrowser.Controller.Localization;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Sorting;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.LiveTv;
  20. using MediaBrowser.Model.Logging;
  21. using MediaBrowser.Model.Querying;
  22. using MediaBrowser.Model.Serialization;
  23. using MoreLinq;
  24. using System;
  25. using System.Collections.Concurrent;
  26. using System.Collections.Generic;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. namespace MediaBrowser.Server.Implementations.LiveTv
  31. {
  32. /// <summary>
  33. /// Class LiveTvManager
  34. /// </summary>
  35. public class LiveTvManager : ILiveTvManager, IDisposable
  36. {
  37. private readonly IServerConfigurationManager _config;
  38. private readonly ILogger _logger;
  39. private readonly IItemRepository _itemRepo;
  40. private readonly IUserManager _userManager;
  41. private readonly IUserDataManager _userDataManager;
  42. private readonly ILibraryManager _libraryManager;
  43. private readonly ITaskManager _taskManager;
  44. private readonly IJsonSerializer _jsonSerializer;
  45. private readonly IProviderManager _providerManager;
  46. private readonly IDtoService _dtoService;
  47. private readonly ILocalizationManager _localization;
  48. private readonly LiveTvDtoService _tvDtoService;
  49. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  50. private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
  51. new ConcurrentDictionary<string, LiveStreamData>();
  52. private readonly SemaphoreSlim _refreshRecordingsLock = new SemaphoreSlim(1, 1);
  53. private readonly ConcurrentDictionary<Guid, Guid> _refreshedPrograms = new ConcurrentDictionary<Guid, Guid>();
  54. private readonly List<ITunerHost> _tunerHosts = new List<ITunerHost>();
  55. private readonly List<IListingsProvider> _listingProviders = new List<IListingsProvider>();
  56. public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager)
  57. {
  58. _config = config;
  59. _logger = logger;
  60. _itemRepo = itemRepo;
  61. _userManager = userManager;
  62. _libraryManager = libraryManager;
  63. _taskManager = taskManager;
  64. _localization = localization;
  65. _jsonSerializer = jsonSerializer;
  66. _providerManager = providerManager;
  67. _dtoService = dtoService;
  68. _userDataManager = userDataManager;
  69. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost);
  70. }
  71. /// <summary>
  72. /// Gets the services.
  73. /// </summary>
  74. /// <value>The services.</value>
  75. public IReadOnlyList<ILiveTvService> Services
  76. {
  77. get { return _services; }
  78. }
  79. private LiveTvOptions GetConfiguration()
  80. {
  81. return _config.GetConfiguration<LiveTvOptions>("livetv");
  82. }
  83. /// <summary>
  84. /// Adds the parts.
  85. /// </summary>
  86. /// <param name="services">The services.</param>
  87. /// <param name="tunerHosts">The tuner hosts.</param>
  88. /// <param name="listingProviders">The listing providers.</param>
  89. public void AddParts(IEnumerable<ILiveTvService> services, IEnumerable<ITunerHost> tunerHosts, IEnumerable<IListingsProvider> listingProviders)
  90. {
  91. _services.AddRange(services);
  92. _tunerHosts.AddRange(tunerHosts);
  93. _listingProviders.AddRange(listingProviders);
  94. foreach (var service in _services)
  95. {
  96. service.DataSourceChanged += service_DataSourceChanged;
  97. }
  98. }
  99. public List<ITunerHost> TunerHosts
  100. {
  101. get { return _tunerHosts; }
  102. }
  103. public List<IListingsProvider> ListingProviders
  104. {
  105. get { return _listingProviders; }
  106. }
  107. void service_DataSourceChanged(object sender, EventArgs e)
  108. {
  109. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  110. }
  111. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  112. {
  113. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  114. var channels = _libraryManager.GetItems(new InternalItemsQuery
  115. {
  116. IncludeItemTypes = new[] { typeof(LiveTvChannel).Name }
  117. }).Items.Cast<LiveTvChannel>();
  118. if (user != null)
  119. {
  120. // Avoid implicitly captured closure
  121. var currentUser = user;
  122. channels = channels
  123. .Where(i => i.IsVisible(currentUser))
  124. .OrderBy(i =>
  125. {
  126. double number = 0;
  127. if (!string.IsNullOrEmpty(i.Number))
  128. {
  129. double.TryParse(i.Number, out number);
  130. }
  131. return number;
  132. });
  133. if (query.IsFavorite.HasValue)
  134. {
  135. var val = query.IsFavorite.Value;
  136. channels = channels
  137. .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
  138. }
  139. if (query.IsLiked.HasValue)
  140. {
  141. var val = query.IsLiked.Value;
  142. channels = channels
  143. .Where(i =>
  144. {
  145. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  146. return likes.HasValue && likes.Value == val;
  147. });
  148. }
  149. if (query.IsDisliked.HasValue)
  150. {
  151. var val = query.IsDisliked.Value;
  152. channels = channels
  153. .Where(i =>
  154. {
  155. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  156. return likes.HasValue && likes.Value != val;
  157. });
  158. }
  159. }
  160. var enableFavoriteSorting = query.EnableFavoriteSorting;
  161. channels = channels.OrderBy(i =>
  162. {
  163. if (enableFavoriteSorting)
  164. {
  165. var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey());
  166. if (userData.IsFavorite)
  167. {
  168. return 0;
  169. }
  170. if (userData.Likes.HasValue)
  171. {
  172. if (!userData.Likes.Value)
  173. {
  174. return 3;
  175. }
  176. return 1;
  177. }
  178. }
  179. return 2;
  180. });
  181. var allChannels = channels.ToList();
  182. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  183. if (query.StartIndex.HasValue)
  184. {
  185. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  186. }
  187. if (query.Limit.HasValue)
  188. {
  189. allEnumerable = allEnumerable.Take(query.Limit.Value);
  190. }
  191. var result = new QueryResult<LiveTvChannel>
  192. {
  193. Items = allEnumerable.ToArray(),
  194. TotalRecordCount = allChannels.Count
  195. };
  196. return result;
  197. }
  198. public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, DtoOptions options, CancellationToken cancellationToken)
  199. {
  200. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  201. var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);
  202. var returnList = new List<ChannelInfoDto>();
  203. var now = DateTime.UtcNow;
  204. var programs = _libraryManager.GetItems(new InternalItemsQuery
  205. {
  206. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  207. MaxStartDate = now,
  208. MinEndDate = now
  209. }).Items.Cast<LiveTvProgram>().OrderBy(i => i.StartDate).ToList();
  210. foreach (var channel in internalResult.Items)
  211. {
  212. var channelIdString = channel.Id.ToString("N");
  213. var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString, StringComparison.OrdinalIgnoreCase));
  214. returnList.Add(_tvDtoService.GetChannelInfoDto(channel, options, currentProgram, user));
  215. }
  216. var result = new QueryResult<ChannelInfoDto>
  217. {
  218. Items = returnList.ToArray(),
  219. TotalRecordCount = internalResult.TotalRecordCount
  220. };
  221. return result;
  222. }
  223. public LiveTvChannel GetInternalChannel(string id)
  224. {
  225. return GetInternalChannel(new Guid(id));
  226. }
  227. private LiveTvChannel GetInternalChannel(Guid id)
  228. {
  229. return _libraryManager.GetItemById(id) as LiveTvChannel;
  230. }
  231. internal LiveTvProgram GetInternalProgram(string id)
  232. {
  233. return _libraryManager.GetItemById(id) as LiveTvProgram;
  234. }
  235. internal LiveTvProgram GetInternalProgram(Guid id)
  236. {
  237. return _libraryManager.GetItemById(id) as LiveTvProgram;
  238. }
  239. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  240. {
  241. var result = await GetInternalRecordings(new RecordingQuery
  242. {
  243. Id = id
  244. }, cancellationToken).ConfigureAwait(false);
  245. return result.Items.FirstOrDefault() as ILiveTvRecording;
  246. }
  247. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  248. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  249. {
  250. return await GetLiveStream(id, null, false, cancellationToken).ConfigureAwait(false);
  251. }
  252. public async Task<MediaSourceInfo> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken)
  253. {
  254. return await GetLiveStream(id, mediaSourceId, true, cancellationToken).ConfigureAwait(false);
  255. }
  256. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  257. {
  258. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  259. var service = GetService(item);
  260. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  261. }
  262. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  263. {
  264. var item = GetInternalChannel(id);
  265. var service = GetService(item);
  266. var sources = await service.GetChannelStreamMediaSources(item.ExternalId, cancellationToken).ConfigureAwait(false);
  267. var list = sources.ToList();
  268. foreach (var source in list)
  269. {
  270. Normalize(source, item.ChannelType == ChannelType.TV);
  271. }
  272. return list;
  273. }
  274. private ILiveTvService GetService(ILiveTvItem item)
  275. {
  276. return GetService(item.ServiceName);
  277. }
  278. private ILiveTvService GetService(string name)
  279. {
  280. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  281. }
  282. private async Task<MediaSourceInfo> GetLiveStream(string id, string mediaSourceId, bool isChannel, CancellationToken cancellationToken)
  283. {
  284. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  285. try
  286. {
  287. MediaSourceInfo info;
  288. bool isVideo;
  289. if (isChannel)
  290. {
  291. var channel = GetInternalChannel(id);
  292. isVideo = channel.ChannelType == ChannelType.TV;
  293. var service = GetService(channel);
  294. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  295. info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false);
  296. info.RequiresClosing = true;
  297. if (info.RequiresClosing)
  298. {
  299. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  300. info.LiveStreamId = idPrefix + info.Id;
  301. }
  302. }
  303. else
  304. {
  305. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  306. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  307. var service = GetService(recording);
  308. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.ExternalId);
  309. info = await service.GetRecordingStream(recording.ExternalId, null, cancellationToken).ConfigureAwait(false);
  310. info.RequiresClosing = true;
  311. if (info.RequiresClosing)
  312. {
  313. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  314. info.LiveStreamId = idPrefix + info.Id;
  315. }
  316. }
  317. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  318. Normalize(info, isVideo);
  319. var data = new LiveStreamData
  320. {
  321. Info = info,
  322. IsChannel = isChannel,
  323. ItemId = id
  324. };
  325. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  326. return info;
  327. }
  328. catch (Exception ex)
  329. {
  330. _logger.ErrorException("Error getting channel stream", ex);
  331. throw;
  332. }
  333. finally
  334. {
  335. _liveStreamSemaphore.Release();
  336. }
  337. }
  338. private void Normalize(MediaSourceInfo mediaSource, bool isVideo)
  339. {
  340. if (mediaSource.MediaStreams.Count == 0)
  341. {
  342. if (isVideo)
  343. {
  344. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  345. {
  346. new MediaStream
  347. {
  348. Type = MediaStreamType.Video,
  349. // Set the index to -1 because we don't know the exact index of the video stream within the container
  350. Index = -1,
  351. // Set to true if unknown to enable deinterlacing
  352. IsInterlaced = true
  353. },
  354. new MediaStream
  355. {
  356. Type = MediaStreamType.Audio,
  357. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  358. Index = -1
  359. }
  360. });
  361. }
  362. else
  363. {
  364. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  365. {
  366. new MediaStream
  367. {
  368. Type = MediaStreamType.Audio,
  369. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  370. Index = -1
  371. }
  372. });
  373. }
  374. }
  375. // Clean some bad data coming from providers
  376. foreach (var stream in mediaSource.MediaStreams)
  377. {
  378. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  379. {
  380. stream.BitRate = null;
  381. }
  382. if (stream.Channels.HasValue && stream.Channels <= 0)
  383. {
  384. stream.Channels = null;
  385. }
  386. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  387. {
  388. stream.AverageFrameRate = null;
  389. }
  390. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  391. {
  392. stream.RealFrameRate = null;
  393. }
  394. if (stream.Width.HasValue && stream.Width <= 0)
  395. {
  396. stream.Width = null;
  397. }
  398. if (stream.Height.HasValue && stream.Height <= 0)
  399. {
  400. stream.Height = null;
  401. }
  402. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  403. {
  404. stream.SampleRate = null;
  405. }
  406. if (stream.Level.HasValue && stream.Level <= 0)
  407. {
  408. stream.Level = null;
  409. }
  410. }
  411. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  412. // If there are duplicate stream indexes, set them all to unknown
  413. if (indexes.Count != mediaSource.MediaStreams.Count)
  414. {
  415. foreach (var stream in mediaSource.MediaStreams)
  416. {
  417. stream.Index = -1;
  418. }
  419. }
  420. // Set the total bitrate if not already supplied
  421. if (!mediaSource.Bitrate.HasValue)
  422. {
  423. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  424. if (total > 0)
  425. {
  426. mediaSource.Bitrate = total;
  427. }
  428. }
  429. }
  430. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  431. {
  432. var isNew = false;
  433. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  434. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  435. if (item == null)
  436. {
  437. item = new LiveTvChannel
  438. {
  439. Name = channelInfo.Name,
  440. Id = id,
  441. DateCreated = DateTime.UtcNow,
  442. };
  443. isNew = true;
  444. }
  445. item.ChannelType = channelInfo.ChannelType;
  446. item.ExternalId = channelInfo.Id;
  447. item.ServiceName = serviceName;
  448. item.Number = channelInfo.Number;
  449. var replaceImages = new List<ImageType>();
  450. //if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  451. //{
  452. // isNew = true;
  453. // replaceImages.Add(ImageType.Primary);
  454. //}
  455. //if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  456. //{
  457. // isNew = true;
  458. // replaceImages.Add(ImageType.Primary);
  459. //}
  460. item.ProviderImageUrl = channelInfo.ImageUrl;
  461. item.HasProviderImage = channelInfo.HasImage;
  462. item.ProviderImagePath = channelInfo.ImagePath;
  463. if (string.IsNullOrEmpty(item.Name))
  464. {
  465. item.Name = channelInfo.Name;
  466. }
  467. await item.RefreshMetadata(new MetadataRefreshOptions
  468. {
  469. ForceSave = isNew,
  470. ReplaceImages = replaceImages.Distinct().ToList()
  471. }, cancellationToken);
  472. return item;
  473. }
  474. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, string channelId, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  475. {
  476. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  477. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  478. var isNew = false;
  479. if (item == null)
  480. {
  481. isNew = true;
  482. item = new LiveTvProgram
  483. {
  484. Name = info.Name,
  485. Id = id,
  486. DateCreated = DateTime.UtcNow,
  487. DateModified = DateTime.UtcNow
  488. };
  489. }
  490. item.ChannelType = channelType;
  491. item.ServiceName = serviceName;
  492. item.Audio = info.Audio;
  493. item.ChannelId = channelId;
  494. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  495. item.EndDate = info.EndDate;
  496. item.EpisodeTitle = info.EpisodeTitle;
  497. item.ExternalId = info.Id;
  498. item.Genres = info.Genres;
  499. item.HasProviderImage = info.HasImage;
  500. item.IsHD = info.IsHD;
  501. item.IsKids = info.IsKids;
  502. item.IsLive = info.IsLive;
  503. item.IsMovie = info.IsMovie;
  504. item.IsNews = info.IsNews;
  505. item.IsPremiere = info.IsPremiere;
  506. item.IsRepeat = info.IsRepeat;
  507. item.IsSeries = info.IsSeries;
  508. item.IsSports = info.IsSports;
  509. item.Name = info.Name;
  510. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  511. item.Overview = item.Overview ?? info.Overview;
  512. item.OriginalAirDate = info.OriginalAirDate;
  513. item.ProviderImagePath = info.ImagePath;
  514. item.ProviderImageUrl = info.ImageUrl;
  515. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  516. item.StartDate = info.StartDate;
  517. item.HomePageUrl = info.HomePageUrl;
  518. item.ProductionYear = info.ProductionYear;
  519. item.PremiereDate = item.PremiereDate ?? info.OriginalAirDate;
  520. if (isNew)
  521. {
  522. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  523. }
  524. else
  525. {
  526. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  527. }
  528. var maxStartDate = DateTime.UtcNow.AddDays(3);
  529. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions
  530. {
  531. ImageRefreshMode = info.StartDate <= maxStartDate ? ImageRefreshMode.Default : ImageRefreshMode.ValidationOnly
  532. });
  533. return item;
  534. }
  535. private void RefreshIfNeeded(LiveTvProgram program)
  536. {
  537. if (_refreshedPrograms.TryAdd(program.Id, program.Id))
  538. {
  539. _providerManager.QueueRefresh(program.Id, new MetadataRefreshOptions());
  540. }
  541. }
  542. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  543. {
  544. var isNew = false;
  545. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  546. var item = _itemRepo.RetrieveItem(id);
  547. if (item == null)
  548. {
  549. if (info.ChannelType == ChannelType.TV)
  550. {
  551. item = new LiveTvVideoRecording
  552. {
  553. Name = info.Name,
  554. Id = id,
  555. DateCreated = DateTime.UtcNow,
  556. DateModified = DateTime.UtcNow,
  557. VideoType = VideoType.VideoFile
  558. };
  559. }
  560. else
  561. {
  562. item = new LiveTvAudioRecording
  563. {
  564. Name = info.Name,
  565. Id = id,
  566. DateCreated = DateTime.UtcNow,
  567. DateModified = DateTime.UtcNow
  568. };
  569. }
  570. isNew = true;
  571. }
  572. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  573. item.CommunityRating = info.CommunityRating;
  574. item.OfficialRating = info.OfficialRating;
  575. item.Overview = info.Overview;
  576. item.EndDate = info.EndDate;
  577. item.Genres = info.Genres;
  578. var recording = (ILiveTvRecording)item;
  579. recording.ExternalId = info.Id;
  580. recording.ProgramId = _tvDtoService.GetInternalProgramId(serviceName, info.ProgramId).ToString("N");
  581. recording.Audio = info.Audio;
  582. recording.ChannelType = info.ChannelType;
  583. recording.EndDate = info.EndDate;
  584. recording.EpisodeTitle = info.EpisodeTitle;
  585. recording.ProviderImagePath = info.ImagePath;
  586. recording.ProviderImageUrl = info.ImageUrl;
  587. recording.IsHD = info.IsHD;
  588. recording.IsKids = info.IsKids;
  589. recording.IsLive = info.IsLive;
  590. recording.IsMovie = info.IsMovie;
  591. recording.IsNews = info.IsNews;
  592. recording.IsPremiere = info.IsPremiere;
  593. recording.IsRepeat = info.IsRepeat;
  594. recording.IsSeries = info.IsSeries;
  595. recording.IsSports = info.IsSports;
  596. recording.OriginalAirDate = info.OriginalAirDate;
  597. recording.SeriesTimerId = info.SeriesTimerId;
  598. recording.StartDate = info.StartDate;
  599. recording.Status = info.Status;
  600. recording.ServiceName = serviceName;
  601. var originalPath = item.Path;
  602. if (!string.IsNullOrEmpty(info.Path))
  603. {
  604. item.Path = info.Path;
  605. }
  606. else if (!string.IsNullOrEmpty(info.Url))
  607. {
  608. item.Path = info.Url;
  609. }
  610. var pathChanged = !string.Equals(originalPath, item.Path);
  611. if (isNew)
  612. {
  613. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  614. }
  615. else if (pathChanged)
  616. {
  617. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  618. }
  619. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions());
  620. return item.Id;
  621. }
  622. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  623. {
  624. var program = GetInternalProgram(id);
  625. RefreshIfNeeded(program);
  626. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  627. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  628. return dto;
  629. }
  630. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  631. {
  632. var internalQuery = new InternalItemsQuery
  633. {
  634. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  635. MinEndDate = query.MinEndDate,
  636. MinStartDate = query.MinStartDate,
  637. MaxEndDate = query.MaxEndDate,
  638. MaxStartDate = query.MaxStartDate,
  639. ChannelIds = query.ChannelIds,
  640. IsMovie = query.IsMovie,
  641. IsSports = query.IsSports,
  642. IsKids = query.IsKids,
  643. Genres = query.Genres
  644. };
  645. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  646. if (user != null)
  647. {
  648. internalQuery.MaxParentalRating = user.Policy.MaxParentalRating;
  649. if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram))
  650. {
  651. internalQuery.HasParentalRating = true;
  652. }
  653. }
  654. if (query.HasAired.HasValue)
  655. {
  656. if (query.HasAired.Value)
  657. {
  658. internalQuery.MaxEndDate = DateTime.UtcNow;
  659. }
  660. else
  661. {
  662. internalQuery.MinEndDate = DateTime.UtcNow;
  663. }
  664. }
  665. IEnumerable<LiveTvProgram> programs = _libraryManager.GetItems(internalQuery).Items.Cast<LiveTvProgram>();
  666. programs = _libraryManager.Sort(programs, user, query.SortBy, query.SortOrder ?? SortOrder.Ascending)
  667. .Cast<LiveTvProgram>();
  668. var programList = programs.ToList();
  669. IEnumerable<LiveTvProgram> returnPrograms = programList;
  670. if (query.StartIndex.HasValue)
  671. {
  672. returnPrograms = returnPrograms.Skip(query.StartIndex.Value);
  673. }
  674. if (query.Limit.HasValue)
  675. {
  676. returnPrograms = returnPrograms.Take(query.Limit.Value);
  677. }
  678. var returnArray = returnPrograms
  679. .Select(i =>
  680. {
  681. RefreshIfNeeded(i);
  682. return _dtoService.GetBaseItemDto(i, options, user);
  683. })
  684. .ToArray();
  685. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  686. var result = new QueryResult<BaseItemDto>
  687. {
  688. Items = returnArray,
  689. TotalRecordCount = programList.Count
  690. };
  691. return result;
  692. }
  693. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  694. {
  695. var internalQuery = new InternalItemsQuery
  696. {
  697. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  698. IsAiring = query.IsAiring,
  699. IsMovie = query.IsMovie,
  700. IsSports = query.IsSports,
  701. IsKids = query.IsKids
  702. };
  703. if (query.HasAired.HasValue)
  704. {
  705. if (query.HasAired.Value)
  706. {
  707. internalQuery.MaxEndDate = DateTime.UtcNow;
  708. }
  709. else
  710. {
  711. internalQuery.MinEndDate = DateTime.UtcNow;
  712. }
  713. }
  714. var user = _userManager.GetUserById(query.UserId);
  715. if (user != null)
  716. {
  717. internalQuery.MaxParentalRating = user.Policy.MaxParentalRating;
  718. if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram))
  719. {
  720. internalQuery.HasParentalRating = true;
  721. }
  722. }
  723. IEnumerable<LiveTvProgram> programs = _libraryManager.GetItems(internalQuery).Items.Cast<LiveTvProgram>();
  724. var programList = programs.ToList();
  725. var genres = programList.SelectMany(i => i.Genres)
  726. .Where(i => !string.IsNullOrWhiteSpace(i))
  727. .DistinctNames()
  728. .Select(i => _libraryManager.GetGenre(i))
  729. .DistinctBy(i => i.Id)
  730. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  731. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  732. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  733. .ThenBy(i => i.StartDate);
  734. if (query.Limit.HasValue)
  735. {
  736. programs = programs.Take(query.Limit.Value)
  737. .OrderBy(i => i.StartDate);
  738. }
  739. programList = programs.ToList();
  740. var returnArray = programList.ToArray();
  741. foreach (var program in returnArray)
  742. {
  743. RefreshIfNeeded(program);
  744. }
  745. var result = new QueryResult<LiveTvProgram>
  746. {
  747. Items = returnArray,
  748. TotalRecordCount = returnArray.Length
  749. };
  750. return result;
  751. }
  752. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  753. {
  754. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  755. var user = _userManager.GetUserById(query.UserId);
  756. var returnArray = internalResult.Items
  757. .Select(i => _dtoService.GetBaseItemDto(i, options, user))
  758. .ToArray();
  759. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  760. var result = new QueryResult<BaseItemDto>
  761. {
  762. Items = returnArray,
  763. TotalRecordCount = internalResult.TotalRecordCount
  764. };
  765. return result;
  766. }
  767. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  768. {
  769. var score = 0;
  770. if (program.IsLive)
  771. {
  772. score++;
  773. }
  774. if (program.IsSeries && !program.IsRepeat)
  775. {
  776. score++;
  777. }
  778. var channel = GetInternalChannel(program.ChannelId);
  779. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  780. if ((channelUserdata.Likes ?? false))
  781. {
  782. score += 2;
  783. }
  784. else if (!(channelUserdata.Likes ?? true))
  785. {
  786. score -= 2;
  787. }
  788. if (channelUserdata.IsFavorite)
  789. {
  790. score += 3;
  791. }
  792. score += GetGenreScore(program.Genres, userId, genres);
  793. return score;
  794. }
  795. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  796. {
  797. return programGenres.Select(i =>
  798. {
  799. var score = 0;
  800. Genre genre;
  801. if (genres.TryGetValue(i, out genre))
  802. {
  803. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  804. if ((genreUserdata.Likes ?? false))
  805. {
  806. score++;
  807. }
  808. else if (!(genreUserdata.Likes ?? true))
  809. {
  810. score--;
  811. }
  812. if (genreUserdata.IsFavorite)
  813. {
  814. score += 2;
  815. }
  816. }
  817. return score;
  818. }).Sum();
  819. }
  820. private async Task AddRecordingInfo(IEnumerable<BaseItemDto> programs, CancellationToken cancellationToken)
  821. {
  822. var timers = new Dictionary<string, List<TimerInfo>>();
  823. foreach (var program in programs)
  824. {
  825. var internalProgram = GetInternalProgram(program.Id);
  826. List<TimerInfo> timerList;
  827. if (!timers.TryGetValue(internalProgram.ServiceName, out timerList))
  828. {
  829. try
  830. {
  831. var tempTimers = await GetService(internalProgram.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  832. timers[internalProgram.ServiceName] = timerList = tempTimers.ToList();
  833. }
  834. catch (Exception ex)
  835. {
  836. _logger.ErrorException("Error getting timer infos", ex);
  837. timers[internalProgram.ServiceName] = timerList = new List<TimerInfo>();
  838. }
  839. }
  840. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, internalProgram.ExternalId, StringComparison.OrdinalIgnoreCase));
  841. if (timer != null)
  842. {
  843. program.TimerId = _tvDtoService.GetInternalTimerId(internalProgram.ServiceName, timer.Id)
  844. .ToString("N");
  845. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  846. {
  847. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(internalProgram.ServiceName, timer.SeriesTimerId)
  848. .ToString("N");
  849. }
  850. }
  851. }
  852. }
  853. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  854. {
  855. return RefreshChannelsInternal(progress, cancellationToken);
  856. }
  857. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  858. {
  859. var numComplete = 0;
  860. double progressPerService = _services.Count == 0
  861. ? 0
  862. : 1 / _services.Count;
  863. var newChannelIdList = new List<Guid>();
  864. var newProgramIdList = new List<Guid>();
  865. foreach (var service in _services)
  866. {
  867. cancellationToken.ThrowIfCancellationRequested();
  868. try
  869. {
  870. var innerProgress = new ActionableProgress<double>();
  871. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  872. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  873. newChannelIdList.AddRange(idList.Item1);
  874. newProgramIdList.AddRange(idList.Item2);
  875. }
  876. catch (OperationCanceledException)
  877. {
  878. throw;
  879. }
  880. catch (Exception ex)
  881. {
  882. _logger.ErrorException("Error refreshing channels for service", ex);
  883. }
  884. numComplete++;
  885. double percent = numComplete;
  886. percent /= _services.Count;
  887. progress.Report(100 * percent);
  888. }
  889. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  890. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  891. _refreshedPrograms.Clear();
  892. // Load these now which will prefetch metadata
  893. var dtoOptions = new DtoOptions();
  894. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  895. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  896. progress.Report(100);
  897. }
  898. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  899. {
  900. progress.Report(10);
  901. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  902. var allChannelsList = allChannels.ToList();
  903. var list = new List<LiveTvChannel>();
  904. var numComplete = 0;
  905. foreach (var channelInfo in allChannelsList)
  906. {
  907. cancellationToken.ThrowIfCancellationRequested();
  908. try
  909. {
  910. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  911. list.Add(item);
  912. _libraryManager.RegisterItem(item);
  913. }
  914. catch (OperationCanceledException)
  915. {
  916. throw;
  917. }
  918. catch (Exception ex)
  919. {
  920. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  921. }
  922. numComplete++;
  923. double percent = numComplete;
  924. percent /= allChannelsList.Count;
  925. progress.Report(5 * percent + 10);
  926. }
  927. progress.Report(15);
  928. numComplete = 0;
  929. var programs = new List<Guid>();
  930. var channels = new List<Guid>();
  931. var guideDays = GetGuideDays(list.Count);
  932. cancellationToken.ThrowIfCancellationRequested();
  933. foreach (var currentChannel in list)
  934. {
  935. channels.Add(currentChannel.Id);
  936. cancellationToken.ThrowIfCancellationRequested();
  937. try
  938. {
  939. var start = DateTime.UtcNow.AddHours(-1);
  940. var end = start.AddDays(guideDays);
  941. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  942. var channelId = currentChannel.Id.ToString("N");
  943. foreach (var program in channelPrograms)
  944. {
  945. var programItem = await GetProgram(program, channelId, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  946. programs.Add(programItem.Id);
  947. }
  948. }
  949. catch (OperationCanceledException)
  950. {
  951. throw;
  952. }
  953. catch (Exception ex)
  954. {
  955. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  956. }
  957. numComplete++;
  958. double percent = numComplete;
  959. percent /= allChannelsList.Count;
  960. progress.Report(80 * percent + 10);
  961. }
  962. progress.Report(100);
  963. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  964. }
  965. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  966. {
  967. var list = _itemRepo.GetItemIds(new InternalItemsQuery
  968. {
  969. IncludeItemTypes = validTypes
  970. }).Items.ToList();
  971. var numComplete = 0;
  972. foreach (var itemId in list)
  973. {
  974. cancellationToken.ThrowIfCancellationRequested();
  975. if (!currentIdList.Contains(itemId))
  976. {
  977. var item = _libraryManager.GetItemById(itemId);
  978. if (item != null)
  979. {
  980. await _libraryManager.DeleteItem(item, new DeleteOptions
  981. {
  982. DeleteFileLocation = false
  983. }).ConfigureAwait(false);
  984. }
  985. }
  986. numComplete++;
  987. double percent = numComplete;
  988. percent /= list.Count;
  989. progress.Report(100 * percent);
  990. }
  991. }
  992. private double GetGuideDays(int channelCount)
  993. {
  994. var config = GetConfiguration();
  995. if (config.GuideDays.HasValue)
  996. {
  997. return config.GuideDays.Value;
  998. }
  999. var programsPerDay = channelCount * 48;
  1000. const int maxPrograms = 24000;
  1001. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  1002. return Math.Max(3, Math.Min(days, 14));
  1003. }
  1004. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  1005. {
  1006. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  1007. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  1008. }
  1009. private DateTime _lastRecordingRefreshTime;
  1010. private async Task RefreshRecordings(CancellationToken cancellationToken)
  1011. {
  1012. const int cacheMinutes = 5;
  1013. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1014. {
  1015. return;
  1016. }
  1017. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1018. try
  1019. {
  1020. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1021. {
  1022. return;
  1023. }
  1024. var tasks = _services.Select(async i =>
  1025. {
  1026. try
  1027. {
  1028. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  1029. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  1030. }
  1031. catch (Exception ex)
  1032. {
  1033. _logger.ErrorException("Error getting recordings", ex);
  1034. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  1035. }
  1036. });
  1037. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1038. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, cancellationToken));
  1039. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  1040. CleanDatabaseInternal(idList.ToList(), new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  1041. _lastRecordingRefreshTime = DateTime.UtcNow;
  1042. }
  1043. finally
  1044. {
  1045. _refreshRecordingsLock.Release();
  1046. }
  1047. }
  1048. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1049. {
  1050. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1051. if (user != null && !IsLiveTvEnabled(user))
  1052. {
  1053. return new QueryResult<BaseItem>();
  1054. }
  1055. await RefreshRecordings(cancellationToken).ConfigureAwait(false);
  1056. var internalQuery = new InternalItemsQuery
  1057. {
  1058. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }
  1059. };
  1060. if (!string.IsNullOrEmpty(query.ChannelId))
  1061. {
  1062. internalQuery.ChannelIds = new[] { query.ChannelId };
  1063. }
  1064. var queryResult = _libraryManager.GetItems(internalQuery);
  1065. IEnumerable<ILiveTvRecording> recordings = queryResult.Items.Cast<ILiveTvRecording>();
  1066. if (!string.IsNullOrEmpty(query.Id))
  1067. {
  1068. var guid = new Guid(query.Id);
  1069. recordings = recordings
  1070. .Where(i => i.Id == guid);
  1071. }
  1072. if (!string.IsNullOrEmpty(query.GroupId))
  1073. {
  1074. var guid = new Guid(query.GroupId);
  1075. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1076. }
  1077. if (query.IsInProgress.HasValue)
  1078. {
  1079. var val = query.IsInProgress.Value;
  1080. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  1081. }
  1082. if (query.Status.HasValue)
  1083. {
  1084. var val = query.Status.Value;
  1085. recordings = recordings.Where(i => (i.Status == val));
  1086. }
  1087. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1088. {
  1089. var guid = new Guid(query.SeriesTimerId);
  1090. recordings = recordings
  1091. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1092. }
  1093. if (user != null)
  1094. {
  1095. var currentUser = user;
  1096. recordings = recordings.Where(i => i.IsParentalAllowed(currentUser));
  1097. }
  1098. recordings = recordings.OrderByDescending(i => i.StartDate);
  1099. var entityList = recordings.ToList();
  1100. IEnumerable<ILiveTvRecording> entities = entityList;
  1101. if (query.StartIndex.HasValue)
  1102. {
  1103. entities = entities.Skip(query.StartIndex.Value);
  1104. }
  1105. if (query.Limit.HasValue)
  1106. {
  1107. entities = entities.Take(query.Limit.Value);
  1108. }
  1109. return new QueryResult<BaseItem>
  1110. {
  1111. Items = entities.Cast<BaseItem>().ToArray(),
  1112. TotalRecordCount = entityList.Count
  1113. };
  1114. }
  1115. public void AddInfoToProgramDto(BaseItem item, BaseItemDto dto, User user = null)
  1116. {
  1117. var program = (LiveTvProgram)item;
  1118. var service = GetService(program);
  1119. var channel = GetInternalChannel(program.ChannelId);
  1120. dto.Id = _tvDtoService.GetInternalProgramId(service.Name, program.ExternalId).ToString("N");
  1121. dto.ChannelId = item.ChannelId;
  1122. dto.StartDate = program.StartDate;
  1123. dto.IsRepeat = program.IsRepeat;
  1124. dto.EpisodeTitle = program.EpisodeTitle;
  1125. dto.ChannelType = program.ChannelType;
  1126. dto.Audio = program.Audio;
  1127. if (program.IsHD.HasValue && program.IsHD.Value)
  1128. {
  1129. dto.IsHD = program.IsHD;
  1130. }
  1131. if (program.IsMovie)
  1132. {
  1133. dto.IsMovie = program.IsMovie;
  1134. }
  1135. if (program.IsSeries)
  1136. {
  1137. dto.IsSeries = program.IsSeries;
  1138. }
  1139. if (program.IsSports)
  1140. {
  1141. dto.IsSports = program.IsSports;
  1142. }
  1143. if (program.IsLive)
  1144. {
  1145. dto.IsLive = program.IsLive;
  1146. }
  1147. if (program.IsNews)
  1148. {
  1149. dto.IsNews = program.IsNews;
  1150. }
  1151. if (program.IsKids)
  1152. {
  1153. dto.IsKids = program.IsKids;
  1154. }
  1155. if (program.IsPremiere)
  1156. {
  1157. dto.IsPremiere = program.IsPremiere;
  1158. }
  1159. dto.OriginalAirDate = program.OriginalAirDate;
  1160. if (channel != null)
  1161. {
  1162. dto.ChannelName = channel.Name;
  1163. if (!string.IsNullOrEmpty(channel.PrimaryImagePath))
  1164. {
  1165. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1166. }
  1167. }
  1168. }
  1169. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1170. {
  1171. var recording = (ILiveTvRecording)item;
  1172. var service = GetService(recording);
  1173. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1174. var info = recording;
  1175. dto.Id = item.Id.ToString("N");
  1176. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1177. ? null
  1178. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1179. dto.ChannelId = item.ChannelId;
  1180. dto.StartDate = info.StartDate;
  1181. dto.RecordingStatus = info.Status;
  1182. dto.IsRepeat = info.IsRepeat;
  1183. dto.EpisodeTitle = info.EpisodeTitle;
  1184. dto.ChannelType = info.ChannelType;
  1185. dto.Audio = info.Audio;
  1186. dto.IsHD = info.IsHD;
  1187. dto.IsMovie = info.IsMovie;
  1188. dto.IsSeries = info.IsSeries;
  1189. dto.IsSports = info.IsSports;
  1190. dto.IsLive = info.IsLive;
  1191. dto.IsNews = info.IsNews;
  1192. dto.IsKids = info.IsKids;
  1193. dto.IsPremiere = info.IsPremiere;
  1194. dto.OriginalAirDate = info.OriginalAirDate;
  1195. dto.CanDelete = user == null
  1196. ? recording.CanDelete()
  1197. : recording.CanDelete(user);
  1198. if (dto.MediaSources == null)
  1199. {
  1200. dto.MediaSources = recording.GetMediaSources(true).ToList();
  1201. }
  1202. if (dto.MediaStreams == null)
  1203. {
  1204. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToList();
  1205. }
  1206. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1207. {
  1208. var now = DateTime.UtcNow.Ticks;
  1209. var start = info.StartDate.Ticks;
  1210. var end = info.EndDate.Value.Ticks;
  1211. var pct = now - start;
  1212. pct /= end;
  1213. pct *= 100;
  1214. dto.CompletionPercentage = pct;
  1215. }
  1216. dto.ProgramId = info.ProgramId;
  1217. if (channel != null)
  1218. {
  1219. dto.ChannelName = channel.Name;
  1220. if (!string.IsNullOrEmpty(channel.PrimaryImagePath))
  1221. {
  1222. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1223. }
  1224. }
  1225. }
  1226. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1227. {
  1228. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1229. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1230. var returnArray = internalResult.Items
  1231. .Select(i => _dtoService.GetBaseItemDto(i, options, user))
  1232. .ToArray();
  1233. if (user != null)
  1234. {
  1235. _dtoService.FillSyncInfo(returnArray, new DtoOptions(), user);
  1236. }
  1237. return new QueryResult<BaseItemDto>
  1238. {
  1239. Items = returnArray,
  1240. TotalRecordCount = internalResult.TotalRecordCount
  1241. };
  1242. }
  1243. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1244. {
  1245. var tasks = _services.Select(async i =>
  1246. {
  1247. try
  1248. {
  1249. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1250. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1251. }
  1252. catch (Exception ex)
  1253. {
  1254. _logger.ErrorException("Error getting recordings", ex);
  1255. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1256. }
  1257. });
  1258. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1259. var timers = results.SelectMany(i => i.ToList());
  1260. if (!string.IsNullOrEmpty(query.ChannelId))
  1261. {
  1262. var guid = new Guid(query.ChannelId);
  1263. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1264. }
  1265. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1266. {
  1267. var guid = new Guid(query.SeriesTimerId);
  1268. timers = timers
  1269. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1270. }
  1271. var returnList = new List<TimerInfoDto>();
  1272. foreach (var i in timers)
  1273. {
  1274. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1275. null :
  1276. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1277. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1278. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1279. }
  1280. var returnArray = returnList
  1281. .OrderBy(i => i.StartDate)
  1282. .ToArray();
  1283. return new QueryResult<TimerInfoDto>
  1284. {
  1285. Items = returnArray,
  1286. TotalRecordCount = returnArray.Length
  1287. };
  1288. }
  1289. public async Task DeleteRecording(string recordingId)
  1290. {
  1291. var recording = await GetInternalRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1292. if (recording == null)
  1293. {
  1294. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1295. }
  1296. var service = GetService(recording.ServiceName);
  1297. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1298. _lastRecordingRefreshTime = DateTime.MinValue;
  1299. }
  1300. public async Task CancelTimer(string id)
  1301. {
  1302. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1303. if (timer == null)
  1304. {
  1305. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1306. }
  1307. var service = GetService(timer.ServiceName);
  1308. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1309. _lastRecordingRefreshTime = DateTime.MinValue;
  1310. }
  1311. public async Task CancelSeriesTimer(string id)
  1312. {
  1313. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1314. if (timer == null)
  1315. {
  1316. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1317. }
  1318. var service = GetService(timer.ServiceName);
  1319. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1320. _lastRecordingRefreshTime = DateTime.MinValue;
  1321. }
  1322. public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1323. {
  1324. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  1325. if (item == null)
  1326. {
  1327. return null;
  1328. }
  1329. return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
  1330. }
  1331. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1332. {
  1333. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1334. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1335. }
  1336. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1337. {
  1338. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1339. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1340. }
  1341. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1342. {
  1343. var tasks = _services.Select(async i =>
  1344. {
  1345. try
  1346. {
  1347. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1348. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1349. }
  1350. catch (Exception ex)
  1351. {
  1352. _logger.ErrorException("Error getting recordings", ex);
  1353. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1354. }
  1355. });
  1356. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1357. var timers = results.SelectMany(i => i.ToList());
  1358. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1359. {
  1360. timers = query.SortOrder == SortOrder.Descending ?
  1361. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1362. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1363. }
  1364. else
  1365. {
  1366. timers = query.SortOrder == SortOrder.Descending ?
  1367. timers.OrderByStringDescending(i => i.Item1.Name) :
  1368. timers.OrderByString(i => i.Item1.Name);
  1369. }
  1370. var returnArray = timers
  1371. .Select(i =>
  1372. {
  1373. string channelName = null;
  1374. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1375. {
  1376. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1377. var channel = GetInternalChannel(internalChannelId);
  1378. channelName = channel == null ? null : channel.Name;
  1379. }
  1380. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1381. })
  1382. .ToArray();
  1383. return new QueryResult<SeriesTimerInfoDto>
  1384. {
  1385. Items = returnArray,
  1386. TotalRecordCount = returnArray.Length
  1387. };
  1388. }
  1389. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1390. {
  1391. var channel = GetInternalChannel(id);
  1392. var now = DateTime.UtcNow;
  1393. var programs = _libraryManager.GetItems(new InternalItemsQuery
  1394. {
  1395. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1396. ChannelIds = new[] { id },
  1397. MaxStartDate = now,
  1398. MinEndDate = now,
  1399. Limit = 1
  1400. }).Items.Cast<LiveTvProgram>();
  1401. var currentProgram = programs
  1402. .OrderBy(i => i.StartDate)
  1403. .FirstOrDefault();
  1404. var dto = _tvDtoService.GetChannelInfoDto(channel, new DtoOptions(), currentProgram, user);
  1405. return dto;
  1406. }
  1407. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1408. {
  1409. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1410. GetService(program) :
  1411. _services.FirstOrDefault();
  1412. ProgramInfo programInfo = null;
  1413. if (program != null)
  1414. {
  1415. var channel = GetInternalChannel(program.ChannelId);
  1416. programInfo = new ProgramInfo
  1417. {
  1418. Audio = program.Audio,
  1419. ChannelId = channel.ExternalId,
  1420. CommunityRating = program.CommunityRating,
  1421. EndDate = program.EndDate ?? DateTime.MinValue,
  1422. EpisodeTitle = program.EpisodeTitle,
  1423. Genres = program.Genres,
  1424. HasImage = program.HasProviderImage,
  1425. Id = program.ExternalId,
  1426. IsHD = program.IsHD,
  1427. IsKids = program.IsKids,
  1428. IsLive = program.IsLive,
  1429. IsMovie = program.IsMovie,
  1430. IsNews = program.IsNews,
  1431. IsPremiere = program.IsPremiere,
  1432. IsRepeat = program.IsRepeat,
  1433. IsSeries = program.IsSeries,
  1434. IsSports = program.IsSports,
  1435. OriginalAirDate = program.PremiereDate,
  1436. Overview = program.Overview,
  1437. StartDate = program.StartDate,
  1438. ImagePath = program.ProviderImagePath,
  1439. ImageUrl = program.ProviderImageUrl,
  1440. Name = program.Name,
  1441. OfficialRating = program.OfficialRating
  1442. };
  1443. }
  1444. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1445. info.Id = null;
  1446. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1447. }
  1448. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1449. {
  1450. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1451. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1452. return obj;
  1453. }
  1454. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1455. {
  1456. var program = GetInternalProgram(programId);
  1457. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1458. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1459. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1460. info.Days = new List<DayOfWeek>
  1461. {
  1462. program.StartDate.ToLocalTime().DayOfWeek
  1463. };
  1464. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1465. info.Name = program.Name;
  1466. info.ChannelId = programDto.ChannelId;
  1467. info.ChannelName = programDto.ChannelName;
  1468. info.StartDate = program.StartDate;
  1469. info.Name = program.Name;
  1470. info.Overview = program.Overview;
  1471. info.ProgramId = programDto.Id;
  1472. info.ExternalProgramId = program.ExternalId;
  1473. if (program.EndDate.HasValue)
  1474. {
  1475. info.EndDate = program.EndDate.Value;
  1476. }
  1477. return info;
  1478. }
  1479. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1480. {
  1481. var service = GetService(timer.ServiceName);
  1482. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1483. // Set priority from default values
  1484. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1485. info.Priority = defaultValues.Priority;
  1486. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1487. _lastRecordingRefreshTime = DateTime.MinValue;
  1488. }
  1489. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1490. {
  1491. var service = GetService(timer.ServiceName);
  1492. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1493. // Set priority from default values
  1494. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1495. info.Priority = defaultValues.Priority;
  1496. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1497. _lastRecordingRefreshTime = DateTime.MinValue;
  1498. }
  1499. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1500. {
  1501. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1502. var service = GetService(timer.ServiceName);
  1503. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1504. _lastRecordingRefreshTime = DateTime.MinValue;
  1505. }
  1506. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1507. {
  1508. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1509. var service = GetService(timer.ServiceName);
  1510. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1511. _lastRecordingRefreshTime = DateTime.MinValue;
  1512. }
  1513. private IEnumerable<string> GetRecordingGroupNames(ILiveTvRecording recording)
  1514. {
  1515. var list = new List<string>();
  1516. if (recording.IsSeries)
  1517. {
  1518. list.Add(recording.Name);
  1519. }
  1520. if (recording.IsKids)
  1521. {
  1522. list.Add("Kids");
  1523. }
  1524. if (recording.IsMovie)
  1525. {
  1526. list.Add("Movies");
  1527. }
  1528. if (recording.IsNews)
  1529. {
  1530. list.Add("News");
  1531. }
  1532. if (recording.IsSports)
  1533. {
  1534. list.Add("Sports");
  1535. }
  1536. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1537. {
  1538. list.Add("Others");
  1539. }
  1540. return list;
  1541. }
  1542. private List<Guid> GetRecordingGroupIds(ILiveTvRecording recording)
  1543. {
  1544. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1545. .GetMD5())
  1546. .ToList();
  1547. }
  1548. public async Task<QueryResult<BaseItemDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1549. {
  1550. var recordingResult = await GetInternalRecordings(new RecordingQuery
  1551. {
  1552. UserId = query.UserId
  1553. }, cancellationToken).ConfigureAwait(false);
  1554. var recordings = recordingResult.Items.Cast<ILiveTvRecording>().ToList();
  1555. var groups = new List<BaseItemDto>();
  1556. var series = recordings
  1557. .Where(i => i.IsSeries)
  1558. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1559. .ToList();
  1560. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  1561. {
  1562. Name = i.Key,
  1563. RecordingCount = i.Count()
  1564. }));
  1565. groups.Add(new BaseItemDto
  1566. {
  1567. Name = "Kids",
  1568. RecordingCount = recordings.Count(i => i.IsKids)
  1569. });
  1570. groups.Add(new BaseItemDto
  1571. {
  1572. Name = "Movies",
  1573. RecordingCount = recordings.Count(i => i.IsMovie)
  1574. });
  1575. groups.Add(new BaseItemDto
  1576. {
  1577. Name = "News",
  1578. RecordingCount = recordings.Count(i => i.IsNews)
  1579. });
  1580. groups.Add(new BaseItemDto
  1581. {
  1582. Name = "Sports",
  1583. RecordingCount = recordings.Count(i => i.IsSports)
  1584. });
  1585. groups.Add(new BaseItemDto
  1586. {
  1587. Name = "Others",
  1588. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1589. });
  1590. groups = groups
  1591. .Where(i => i.RecordingCount > 0)
  1592. .ToList();
  1593. foreach (var group in groups)
  1594. {
  1595. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1596. }
  1597. return new QueryResult<BaseItemDto>
  1598. {
  1599. Items = groups.ToArray(),
  1600. TotalRecordCount = groups.Count
  1601. };
  1602. }
  1603. class LiveStreamData
  1604. {
  1605. internal MediaSourceInfo Info;
  1606. internal string ItemId;
  1607. internal bool IsChannel;
  1608. }
  1609. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1610. {
  1611. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1612. try
  1613. {
  1614. var parts = id.Split(new[] { '_' }, 2);
  1615. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1616. if (service == null)
  1617. {
  1618. throw new ArgumentException("Service not found.");
  1619. }
  1620. id = parts[1];
  1621. LiveStreamData data;
  1622. _openStreams.TryRemove(id, out data);
  1623. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1624. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1625. }
  1626. catch (Exception ex)
  1627. {
  1628. _logger.ErrorException("Error closing live stream", ex);
  1629. throw;
  1630. }
  1631. finally
  1632. {
  1633. _liveStreamSemaphore.Release();
  1634. }
  1635. }
  1636. public GuideInfo GetGuideInfo()
  1637. {
  1638. var startDate = DateTime.UtcNow;
  1639. var endDate = startDate.AddDays(14);
  1640. return new GuideInfo
  1641. {
  1642. StartDate = startDate,
  1643. EndDate = endDate
  1644. };
  1645. }
  1646. /// <summary>
  1647. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1648. /// </summary>
  1649. public void Dispose()
  1650. {
  1651. Dispose(true);
  1652. }
  1653. private readonly object _disposeLock = new object();
  1654. /// <summary>
  1655. /// Releases unmanaged and - optionally - managed resources.
  1656. /// </summary>
  1657. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1658. protected virtual void Dispose(bool dispose)
  1659. {
  1660. if (dispose)
  1661. {
  1662. lock (_disposeLock)
  1663. {
  1664. foreach (var stream in _openStreams.Values.ToList())
  1665. {
  1666. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1667. Task.WaitAll(task);
  1668. }
  1669. _openStreams.Clear();
  1670. }
  1671. }
  1672. }
  1673. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1674. {
  1675. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1676. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1677. }
  1678. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1679. {
  1680. var info = new LiveTvServiceInfo
  1681. {
  1682. Name = service.Name
  1683. };
  1684. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1685. try
  1686. {
  1687. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1688. info.Status = statusInfo.Status;
  1689. info.StatusMessage = statusInfo.StatusMessage;
  1690. info.Version = statusInfo.Version;
  1691. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1692. info.HomePageUrl = service.HomePageUrl;
  1693. info.IsVisible = statusInfo.IsVisible;
  1694. info.Tuners = statusInfo.Tuners.Select(i =>
  1695. {
  1696. string channelName = null;
  1697. if (!string.IsNullOrEmpty(i.ChannelId))
  1698. {
  1699. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1700. var channel = GetInternalChannel(internalChannelId);
  1701. channelName = channel == null ? null : channel.Name;
  1702. }
  1703. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1704. dto.Id = tunerIdPrefix + dto.Id;
  1705. return dto;
  1706. }).ToList();
  1707. }
  1708. catch (Exception ex)
  1709. {
  1710. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1711. info.Status = LiveTvServiceStatus.Unavailable;
  1712. info.StatusMessage = ex.Message;
  1713. }
  1714. return info;
  1715. }
  1716. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1717. {
  1718. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1719. var servicesList = services.ToList();
  1720. var info = new LiveTvInfo
  1721. {
  1722. Services = servicesList.ToList(),
  1723. IsEnabled = servicesList.Count > 0
  1724. };
  1725. info.EnabledUsers = _userManager.Users
  1726. .Where(IsLiveTvEnabled)
  1727. .Select(i => i.Id.ToString("N"))
  1728. .ToList();
  1729. return info;
  1730. }
  1731. private bool IsLiveTvEnabled(User user)
  1732. {
  1733. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Count(i => i.IsEnabled) > 0);
  1734. }
  1735. public IEnumerable<User> GetEnabledUsers()
  1736. {
  1737. return _userManager.Users
  1738. .Where(IsLiveTvEnabled);
  1739. }
  1740. /// <summary>
  1741. /// Resets the tuner.
  1742. /// </summary>
  1743. /// <param name="id">The identifier.</param>
  1744. /// <param name="cancellationToken">The cancellation token.</param>
  1745. /// <returns>Task.</returns>
  1746. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1747. {
  1748. var parts = id.Split(new[] { '_' }, 2);
  1749. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1750. if (service == null)
  1751. {
  1752. throw new ArgumentException("Service not found.");
  1753. }
  1754. return service.ResetTuner(parts[1], cancellationToken);
  1755. }
  1756. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1757. {
  1758. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1759. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1760. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1761. }
  1762. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1763. {
  1764. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1765. var user = _userManager.GetUserById(userId);
  1766. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1767. }
  1768. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info)
  1769. {
  1770. info = (TunerHostInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(TunerHostInfo));
  1771. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1772. if (provider == null)
  1773. {
  1774. throw new ResourceNotFoundException();
  1775. }
  1776. await provider.Validate(info).ConfigureAwait(false);
  1777. var config = GetConfiguration();
  1778. var index = config.TunerHosts.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1779. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1780. {
  1781. info.Id = Guid.NewGuid().ToString("N");
  1782. config.TunerHosts.Add(info);
  1783. }
  1784. else
  1785. {
  1786. config.TunerHosts[index] = info;
  1787. }
  1788. _config.SaveConfiguration("livetv", config);
  1789. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1790. return info;
  1791. }
  1792. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  1793. {
  1794. info = (ListingsProviderInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(ListingsProviderInfo));
  1795. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1796. if (provider == null)
  1797. {
  1798. throw new ResourceNotFoundException();
  1799. }
  1800. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  1801. var config = GetConfiguration();
  1802. var index = config.ListingProviders.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1803. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1804. {
  1805. info.Id = Guid.NewGuid().ToString("N");
  1806. config.ListingProviders.Add(info);
  1807. }
  1808. else
  1809. {
  1810. config.ListingProviders[index] = info;
  1811. }
  1812. _config.SaveConfiguration("livetv", config);
  1813. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1814. return info;
  1815. }
  1816. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  1817. {
  1818. var config = GetConfiguration();
  1819. if (string.IsNullOrWhiteSpace(providerId))
  1820. {
  1821. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  1822. if (provider == null)
  1823. {
  1824. throw new ResourceNotFoundException();
  1825. }
  1826. return provider.GetLineups(null, country, location);
  1827. }
  1828. else
  1829. {
  1830. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  1831. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1832. if (provider == null)
  1833. {
  1834. throw new ResourceNotFoundException();
  1835. }
  1836. return provider.GetLineups(info, country, location);
  1837. }
  1838. }
  1839. }
  1840. }