LiveTvManager.cs 89 KB

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