LiveTvManager.cs 87 KB

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