LiveTvManager.cs 82 KB

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