LiveTvManager.cs 86 KB

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