LiveTvManager.cs 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  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 = queryResult.Items
  776. .Cast<LiveTvProgram>()
  777. .Select(i => new Tuple<BaseItemDto, string, string>(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId))
  778. .ToArray();
  779. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  780. var result = new QueryResult<BaseItemDto>
  781. {
  782. Items = returnArray.Select(i => i.Item1).ToArray(),
  783. TotalRecordCount = queryResult.TotalRecordCount
  784. };
  785. return result;
  786. }
  787. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  788. {
  789. var user = _userManager.GetUserById(query.UserId);
  790. var internalQuery = new InternalItemsQuery(user)
  791. {
  792. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  793. IsAiring = query.IsAiring,
  794. IsMovie = query.IsMovie,
  795. IsSports = query.IsSports,
  796. IsKids = query.IsKids
  797. };
  798. if (query.HasAired.HasValue)
  799. {
  800. if (query.HasAired.Value)
  801. {
  802. internalQuery.MaxEndDate = DateTime.UtcNow;
  803. }
  804. else
  805. {
  806. internalQuery.MinEndDate = DateTime.UtcNow;
  807. }
  808. }
  809. IEnumerable<LiveTvProgram> programs = _libraryManager.QueryItems(internalQuery).Items.Cast<LiveTvProgram>();
  810. var programList = programs.ToList();
  811. var genres = programList.SelectMany(i => i.Genres)
  812. .Where(i => !string.IsNullOrWhiteSpace(i))
  813. .DistinctNames()
  814. .Select(i => _libraryManager.GetGenre(i))
  815. .DistinctBy(i => i.Id)
  816. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  817. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  818. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  819. .ThenBy(i => i.StartDate);
  820. if (query.Limit.HasValue)
  821. {
  822. programs = programs.Take(query.Limit.Value);
  823. }
  824. programList = programs.ToList();
  825. var returnArray = programList.ToArray();
  826. var result = new QueryResult<LiveTvProgram>
  827. {
  828. Items = returnArray,
  829. TotalRecordCount = returnArray.Length
  830. };
  831. return result;
  832. }
  833. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  834. {
  835. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  836. var user = _userManager.GetUserById(query.UserId);
  837. var returnArray = internalResult.Items
  838. .Select(i => new Tuple<BaseItemDto, string, string>(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId))
  839. .ToArray();
  840. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  841. var result = new QueryResult<BaseItemDto>
  842. {
  843. Items = returnArray.Select(i => i.Item1).ToArray(),
  844. TotalRecordCount = internalResult.TotalRecordCount
  845. };
  846. return result;
  847. }
  848. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  849. {
  850. var score = 0;
  851. if (program.IsLive)
  852. {
  853. score++;
  854. }
  855. if (program.IsSeries && !program.IsRepeat)
  856. {
  857. score++;
  858. }
  859. var channel = GetInternalChannel(program.ChannelId);
  860. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  861. if ((channelUserdata.Likes ?? false))
  862. {
  863. score += 2;
  864. }
  865. else if (!(channelUserdata.Likes ?? true))
  866. {
  867. score -= 2;
  868. }
  869. if (channelUserdata.IsFavorite)
  870. {
  871. score += 3;
  872. }
  873. score += GetGenreScore(program.Genres, userId, genres);
  874. return score;
  875. }
  876. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  877. {
  878. return programGenres.Select(i =>
  879. {
  880. var score = 0;
  881. Genre genre;
  882. if (genres.TryGetValue(i, out genre))
  883. {
  884. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  885. if ((genreUserdata.Likes ?? false))
  886. {
  887. score++;
  888. }
  889. else if (!(genreUserdata.Likes ?? true))
  890. {
  891. score--;
  892. }
  893. if (genreUserdata.IsFavorite)
  894. {
  895. score += 2;
  896. }
  897. }
  898. return score;
  899. }).Sum();
  900. }
  901. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
  902. {
  903. var timers = new Dictionary<string, List<TimerInfo>>();
  904. foreach (var programTuple in programs)
  905. {
  906. var program = programTuple.Item1;
  907. var serviceName = programTuple.Item2;
  908. var externalProgramId = programTuple.Item3;
  909. if (string.IsNullOrWhiteSpace(serviceName))
  910. {
  911. continue;
  912. }
  913. List<TimerInfo> timerList;
  914. if (!timers.TryGetValue(serviceName, out timerList))
  915. {
  916. try
  917. {
  918. var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  919. timers[serviceName] = timerList = tempTimers.ToList();
  920. }
  921. catch (Exception ex)
  922. {
  923. _logger.ErrorException("Error getting timer infos", ex);
  924. timers[serviceName] = timerList = new List<TimerInfo>();
  925. }
  926. }
  927. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  928. if (timer != null)
  929. {
  930. program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id)
  931. .ToString("N");
  932. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  933. {
  934. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
  935. .ToString("N");
  936. }
  937. }
  938. }
  939. }
  940. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  941. {
  942. return RefreshChannelsInternal(progress, cancellationToken);
  943. }
  944. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  945. {
  946. var numComplete = 0;
  947. double progressPerService = _services.Count == 0
  948. ? 0
  949. : 1 / _services.Count;
  950. var newChannelIdList = new List<Guid>();
  951. var newProgramIdList = new List<Guid>();
  952. foreach (var service in _services)
  953. {
  954. cancellationToken.ThrowIfCancellationRequested();
  955. _logger.Debug("Refreshing guide from {0}", service.Name);
  956. try
  957. {
  958. var innerProgress = new ActionableProgress<double>();
  959. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  960. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  961. newChannelIdList.AddRange(idList.Item1);
  962. newProgramIdList.AddRange(idList.Item2);
  963. }
  964. catch (OperationCanceledException)
  965. {
  966. throw;
  967. }
  968. catch (Exception ex)
  969. {
  970. _logger.ErrorException("Error refreshing channels for service", ex);
  971. }
  972. numComplete++;
  973. double percent = numComplete;
  974. percent /= _services.Count;
  975. progress.Report(100 * percent);
  976. }
  977. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  978. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  979. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  980. if (coreService != null)
  981. {
  982. await coreService.RefreshSeriesTimers(cancellationToken, new Progress<double>()).ConfigureAwait(false);
  983. }
  984. // Load these now which will prefetch metadata
  985. var dtoOptions = new DtoOptions();
  986. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  987. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  988. progress.Report(100);
  989. }
  990. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  991. {
  992. progress.Report(10);
  993. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  994. var allChannelsList = allChannels.ToList();
  995. var list = new List<LiveTvChannel>();
  996. var numComplete = 0;
  997. var parentFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  998. var parentFolderId = parentFolder.Id;
  999. foreach (var channelInfo in allChannelsList)
  1000. {
  1001. cancellationToken.ThrowIfCancellationRequested();
  1002. try
  1003. {
  1004. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolderId, cancellationToken).ConfigureAwait(false);
  1005. list.Add(item);
  1006. _libraryManager.RegisterItem(item);
  1007. }
  1008. catch (OperationCanceledException)
  1009. {
  1010. throw;
  1011. }
  1012. catch (Exception ex)
  1013. {
  1014. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  1015. }
  1016. numComplete++;
  1017. double percent = numComplete;
  1018. percent /= allChannelsList.Count;
  1019. progress.Report(5 * percent + 10);
  1020. }
  1021. progress.Report(15);
  1022. numComplete = 0;
  1023. var programs = new List<Guid>();
  1024. var channels = new List<Guid>();
  1025. var guideDays = GetGuideDays(list.Count);
  1026. _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
  1027. cancellationToken.ThrowIfCancellationRequested();
  1028. foreach (var currentChannel in list)
  1029. {
  1030. channels.Add(currentChannel.Id);
  1031. cancellationToken.ThrowIfCancellationRequested();
  1032. try
  1033. {
  1034. var start = DateTime.UtcNow.AddHours(-1);
  1035. var end = start.AddDays(guideDays);
  1036. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  1037. foreach (var program in channelPrograms)
  1038. {
  1039. var programItem = await GetProgram(program, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  1040. programs.Add(programItem.Id);
  1041. }
  1042. }
  1043. catch (OperationCanceledException)
  1044. {
  1045. throw;
  1046. }
  1047. catch (Exception ex)
  1048. {
  1049. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  1050. }
  1051. numComplete++;
  1052. double percent = numComplete;
  1053. percent /= allChannelsList.Count;
  1054. progress.Report(80 * percent + 10);
  1055. }
  1056. progress.Report(100);
  1057. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1058. }
  1059. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1060. {
  1061. var list = _itemRepo.GetItemIds(new InternalItemsQuery
  1062. {
  1063. IncludeItemTypes = validTypes
  1064. }).Items.ToList();
  1065. var numComplete = 0;
  1066. foreach (var itemId in list)
  1067. {
  1068. cancellationToken.ThrowIfCancellationRequested();
  1069. if (itemId == Guid.Empty)
  1070. {
  1071. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1072. continue;
  1073. }
  1074. if (!currentIdList.Contains(itemId))
  1075. {
  1076. var item = _libraryManager.GetItemById(itemId);
  1077. if (item != null)
  1078. {
  1079. await _libraryManager.DeleteItem(item, new DeleteOptions
  1080. {
  1081. DeleteFileLocation = false
  1082. }).ConfigureAwait(false);
  1083. }
  1084. }
  1085. numComplete++;
  1086. double percent = numComplete;
  1087. percent /= list.Count;
  1088. progress.Report(100 * percent);
  1089. }
  1090. }
  1091. private const int MaxGuideDays = 14;
  1092. private double GetGuideDays(int channelCount)
  1093. {
  1094. var config = GetConfiguration();
  1095. if (config.GuideDays.HasValue)
  1096. {
  1097. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1098. }
  1099. var programsPerDay = channelCount * 48;
  1100. const int maxPrograms = 24000;
  1101. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  1102. return Math.Max(3, Math.Min(days, MaxGuideDays));
  1103. }
  1104. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  1105. {
  1106. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  1107. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  1108. }
  1109. private DateTime _lastRecordingRefreshTime;
  1110. private async Task RefreshRecordings(CancellationToken cancellationToken)
  1111. {
  1112. const int cacheMinutes = 5;
  1113. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1114. {
  1115. return;
  1116. }
  1117. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1118. try
  1119. {
  1120. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1121. {
  1122. return;
  1123. }
  1124. var tasks = _services.Select(async i =>
  1125. {
  1126. try
  1127. {
  1128. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  1129. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  1130. }
  1131. catch (Exception ex)
  1132. {
  1133. _logger.ErrorException("Error getting recordings", ex);
  1134. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  1135. }
  1136. });
  1137. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1138. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1139. var parentFolderId = folder.Id;
  1140. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, parentFolderId, cancellationToken));
  1141. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  1142. await CleanDatabaseInternal(idList.ToList(), new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  1143. _lastRecordingRefreshTime = DateTime.UtcNow;
  1144. }
  1145. finally
  1146. {
  1147. _refreshRecordingsLock.Release();
  1148. }
  1149. }
  1150. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1151. {
  1152. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1153. if (user != null && !IsLiveTvEnabled(user))
  1154. {
  1155. return new QueryResult<BaseItem>();
  1156. }
  1157. await RefreshRecordings(cancellationToken).ConfigureAwait(false);
  1158. var internalQuery = new InternalItemsQuery(user)
  1159. {
  1160. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }
  1161. };
  1162. if (!string.IsNullOrEmpty(query.ChannelId))
  1163. {
  1164. internalQuery.ChannelIds = new[] { query.ChannelId };
  1165. }
  1166. var queryResult = _libraryManager.GetItems(internalQuery, new string[] { });
  1167. IEnumerable<ILiveTvRecording> recordings = queryResult.Cast<ILiveTvRecording>();
  1168. if (!string.IsNullOrWhiteSpace(query.Id))
  1169. {
  1170. var guid = new Guid(query.Id);
  1171. recordings = recordings
  1172. .Where(i => i.Id == guid);
  1173. }
  1174. if (!string.IsNullOrWhiteSpace(query.GroupId))
  1175. {
  1176. var guid = new Guid(query.GroupId);
  1177. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1178. }
  1179. if (query.IsInProgress.HasValue)
  1180. {
  1181. var val = query.IsInProgress.Value;
  1182. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  1183. }
  1184. if (query.Status.HasValue)
  1185. {
  1186. var val = query.Status.Value;
  1187. recordings = recordings.Where(i => (i.Status == val));
  1188. }
  1189. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1190. {
  1191. var guid = new Guid(query.SeriesTimerId);
  1192. recordings = recordings
  1193. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1194. }
  1195. recordings = recordings.OrderByDescending(i => i.StartDate);
  1196. var entityList = recordings.ToList();
  1197. IEnumerable<ILiveTvRecording> entities = entityList;
  1198. if (query.StartIndex.HasValue)
  1199. {
  1200. entities = entities.Skip(query.StartIndex.Value);
  1201. }
  1202. if (query.Limit.HasValue)
  1203. {
  1204. entities = entities.Take(query.Limit.Value);
  1205. }
  1206. return new QueryResult<BaseItem>
  1207. {
  1208. Items = entities.Cast<BaseItem>().ToArray(),
  1209. TotalRecordCount = entityList.Count
  1210. };
  1211. }
  1212. public async Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, List<ItemFields> fields, User user = null)
  1213. {
  1214. var recordingTuples = new List<Tuple<BaseItemDto, string, string>>();
  1215. foreach (var tuple in tuples)
  1216. {
  1217. var program = (LiveTvProgram)tuple.Item1;
  1218. var dto = tuple.Item2;
  1219. dto.StartDate = program.StartDate;
  1220. dto.EpisodeTitle = program.EpisodeTitle;
  1221. if (program.IsRepeat)
  1222. {
  1223. dto.IsRepeat = program.IsRepeat;
  1224. }
  1225. if (program.IsMovie)
  1226. {
  1227. dto.IsMovie = program.IsMovie;
  1228. }
  1229. if (program.IsSeries)
  1230. {
  1231. dto.IsSeries = program.IsSeries;
  1232. }
  1233. if (program.IsSports)
  1234. {
  1235. dto.IsSports = program.IsSports;
  1236. }
  1237. if (program.IsLive)
  1238. {
  1239. dto.IsLive = program.IsLive;
  1240. }
  1241. if (program.IsNews)
  1242. {
  1243. dto.IsNews = program.IsNews;
  1244. }
  1245. if (program.IsKids)
  1246. {
  1247. dto.IsKids = program.IsKids;
  1248. }
  1249. if (program.IsPremiere)
  1250. {
  1251. dto.IsPremiere = program.IsPremiere;
  1252. }
  1253. if (fields.Contains(ItemFields.ChannelInfo))
  1254. {
  1255. var channel = GetInternalChannel(program.ChannelId);
  1256. if (channel != null)
  1257. {
  1258. dto.ChannelName = channel.Name;
  1259. dto.MediaType = channel.MediaType;
  1260. if (channel.HasImage(ImageType.Primary))
  1261. {
  1262. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1263. }
  1264. }
  1265. }
  1266. var service = GetService(program);
  1267. var serviceName = service == null ? null : service.Name;
  1268. if (fields.Contains(ItemFields.ServiceName))
  1269. {
  1270. dto.ServiceName = serviceName;
  1271. }
  1272. recordingTuples.Add(new Tuple<BaseItemDto, string, string>(dto, serviceName, program.ExternalId));
  1273. }
  1274. await AddRecordingInfo(recordingTuples, CancellationToken.None).ConfigureAwait(false);
  1275. }
  1276. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1277. {
  1278. var recording = (ILiveTvRecording)item;
  1279. var service = GetService(recording);
  1280. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1281. var info = recording;
  1282. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1283. ? null
  1284. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1285. dto.StartDate = info.StartDate;
  1286. dto.RecordingStatus = info.Status;
  1287. dto.IsRepeat = info.IsRepeat;
  1288. dto.EpisodeTitle = info.EpisodeTitle;
  1289. dto.IsMovie = info.IsMovie;
  1290. dto.IsSeries = info.IsSeries;
  1291. dto.IsSports = info.IsSports;
  1292. dto.IsLive = info.IsLive;
  1293. dto.IsNews = info.IsNews;
  1294. dto.IsKids = info.IsKids;
  1295. dto.IsPremiere = info.IsPremiere;
  1296. dto.CanDelete = user == null
  1297. ? recording.CanDelete()
  1298. : recording.CanDelete(user);
  1299. if (dto.MediaSources == null)
  1300. {
  1301. dto.MediaSources = recording.GetMediaSources(true).ToList();
  1302. }
  1303. if (dto.MediaStreams == null)
  1304. {
  1305. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToList();
  1306. }
  1307. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1308. {
  1309. var now = DateTime.UtcNow.Ticks;
  1310. var start = info.StartDate.Ticks;
  1311. var end = info.EndDate.Value.Ticks;
  1312. var pct = now - start;
  1313. pct /= end;
  1314. pct *= 100;
  1315. dto.CompletionPercentage = pct;
  1316. }
  1317. if (channel != null)
  1318. {
  1319. dto.ChannelName = channel.Name;
  1320. if (channel.HasImage(ImageType.Primary))
  1321. {
  1322. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1323. }
  1324. }
  1325. }
  1326. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1327. {
  1328. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1329. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1330. var tuples = internalResult.Items
  1331. .Select(i => new Tuple<BaseItem, BaseItemDto>(i, _dtoService.GetBaseItemDto(i, options, user)))
  1332. .ToArray();
  1333. if (user != null)
  1334. {
  1335. _dtoService.FillSyncInfo(tuples, new DtoOptions(), user);
  1336. }
  1337. return new QueryResult<BaseItemDto>
  1338. {
  1339. Items = tuples.Select(i => i.Item2).ToArray(),
  1340. TotalRecordCount = internalResult.TotalRecordCount
  1341. };
  1342. }
  1343. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1344. {
  1345. var tasks = _services.Select(async i =>
  1346. {
  1347. try
  1348. {
  1349. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1350. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1351. }
  1352. catch (Exception ex)
  1353. {
  1354. _logger.ErrorException("Error getting recordings", ex);
  1355. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1356. }
  1357. });
  1358. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1359. var timers = results.SelectMany(i => i.ToList());
  1360. if (!string.IsNullOrEmpty(query.ChannelId))
  1361. {
  1362. var guid = new Guid(query.ChannelId);
  1363. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1364. }
  1365. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1366. {
  1367. var guid = new Guid(query.SeriesTimerId);
  1368. timers = timers
  1369. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1370. }
  1371. var returnList = new List<TimerInfoDto>();
  1372. foreach (var i in timers)
  1373. {
  1374. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1375. null :
  1376. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1377. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1378. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1379. }
  1380. var returnArray = returnList
  1381. .OrderBy(i => i.StartDate)
  1382. .ToArray();
  1383. return new QueryResult<TimerInfoDto>
  1384. {
  1385. Items = returnArray,
  1386. TotalRecordCount = returnArray.Length
  1387. };
  1388. }
  1389. public async Task DeleteRecording(string recordingId)
  1390. {
  1391. var recording = await GetInternalRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1392. if (recording == null)
  1393. {
  1394. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1395. }
  1396. await DeleteRecording(recording).ConfigureAwait(false);
  1397. }
  1398. public async Task DeleteRecording(ILiveTvRecording recording)
  1399. {
  1400. var service = GetService(recording.ServiceName);
  1401. try
  1402. {
  1403. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1404. }
  1405. catch (ResourceNotFoundException)
  1406. {
  1407. }
  1408. _lastRecordingRefreshTime = DateTime.MinValue;
  1409. // This is the responsibility of the live tv service
  1410. await _libraryManager.DeleteItem((BaseItem)recording, new DeleteOptions
  1411. {
  1412. DeleteFileLocation = false
  1413. }).ConfigureAwait(false);
  1414. _lastRecordingRefreshTime = DateTime.MinValue;
  1415. }
  1416. public async Task CancelTimer(string id)
  1417. {
  1418. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1419. if (timer == null)
  1420. {
  1421. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1422. }
  1423. var service = GetService(timer.ServiceName);
  1424. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1425. _lastRecordingRefreshTime = DateTime.MinValue;
  1426. }
  1427. public async Task CancelSeriesTimer(string id)
  1428. {
  1429. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1430. if (timer == null)
  1431. {
  1432. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1433. }
  1434. var service = GetService(timer.ServiceName);
  1435. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1436. _lastRecordingRefreshTime = DateTime.MinValue;
  1437. }
  1438. public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1439. {
  1440. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  1441. if (item == null)
  1442. {
  1443. return null;
  1444. }
  1445. return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
  1446. }
  1447. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1448. {
  1449. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1450. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1451. }
  1452. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1453. {
  1454. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1455. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1456. }
  1457. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1458. {
  1459. var tasks = _services.Select(async i =>
  1460. {
  1461. try
  1462. {
  1463. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1464. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1465. }
  1466. catch (Exception ex)
  1467. {
  1468. _logger.ErrorException("Error getting recordings", ex);
  1469. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1470. }
  1471. });
  1472. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1473. var timers = results.SelectMany(i => i.ToList());
  1474. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1475. {
  1476. timers = query.SortOrder == SortOrder.Descending ?
  1477. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1478. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1479. }
  1480. else
  1481. {
  1482. timers = query.SortOrder == SortOrder.Descending ?
  1483. timers.OrderByStringDescending(i => i.Item1.Name) :
  1484. timers.OrderByString(i => i.Item1.Name);
  1485. }
  1486. var returnArray = timers
  1487. .Select(i =>
  1488. {
  1489. string channelName = null;
  1490. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1491. {
  1492. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1493. var channel = GetInternalChannel(internalChannelId);
  1494. channelName = channel == null ? null : channel.Name;
  1495. }
  1496. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1497. })
  1498. .ToArray();
  1499. return new QueryResult<SeriesTimerInfoDto>
  1500. {
  1501. Items = returnArray,
  1502. TotalRecordCount = returnArray.Length
  1503. };
  1504. }
  1505. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1506. {
  1507. var channel = GetInternalChannel(id);
  1508. var now = DateTime.UtcNow;
  1509. var programs = _libraryManager.GetItems(new InternalItemsQuery(user)
  1510. {
  1511. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1512. ChannelIds = new[] { id },
  1513. MaxStartDate = now,
  1514. MinEndDate = now,
  1515. Limit = 1,
  1516. SortBy = new[] { "StartDate" }
  1517. }, new string[] { }).Cast<LiveTvProgram>();
  1518. var currentProgram = programs.FirstOrDefault();
  1519. var dto = _tvDtoService.GetChannelInfoDto(channel, new DtoOptions(), currentProgram, user);
  1520. return dto;
  1521. }
  1522. public void AddChannelInfo(BaseItemDto dto, LiveTvChannel channel, DtoOptions options, User user)
  1523. {
  1524. dto.MediaSources = channel.GetMediaSources(true).ToList();
  1525. var now = DateTime.UtcNow;
  1526. var programs = _libraryManager.GetItems(new InternalItemsQuery(user)
  1527. {
  1528. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1529. ChannelIds = new[] { channel.Id.ToString("N") },
  1530. MaxStartDate = now,
  1531. MinEndDate = now,
  1532. Limit = 1,
  1533. SortBy = new[] { "StartDate" }
  1534. }, new string[] { }).Cast<LiveTvProgram>();
  1535. var currentProgram = programs.FirstOrDefault();
  1536. if (currentProgram != null)
  1537. {
  1538. dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
  1539. }
  1540. }
  1541. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1542. {
  1543. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1544. GetService(program) :
  1545. _services.FirstOrDefault();
  1546. ProgramInfo programInfo = null;
  1547. if (program != null)
  1548. {
  1549. var channel = GetInternalChannel(program.ChannelId);
  1550. programInfo = new ProgramInfo
  1551. {
  1552. Audio = program.Audio,
  1553. ChannelId = channel.ExternalId,
  1554. CommunityRating = program.CommunityRating,
  1555. EndDate = program.EndDate ?? DateTime.MinValue,
  1556. EpisodeTitle = program.EpisodeTitle,
  1557. Genres = program.Genres,
  1558. Id = program.ExternalId,
  1559. IsHD = program.IsHD,
  1560. IsKids = program.IsKids,
  1561. IsLive = program.IsLive,
  1562. IsMovie = program.IsMovie,
  1563. IsNews = program.IsNews,
  1564. IsPremiere = program.IsPremiere,
  1565. IsRepeat = program.IsRepeat,
  1566. IsSeries = program.IsSeries,
  1567. IsSports = program.IsSports,
  1568. OriginalAirDate = program.PremiereDate,
  1569. Overview = program.Overview,
  1570. StartDate = program.StartDate,
  1571. //ImagePath = program.ExternalImagePath,
  1572. Name = program.Name,
  1573. OfficialRating = program.OfficialRating
  1574. };
  1575. }
  1576. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1577. info.Id = null;
  1578. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1579. }
  1580. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1581. {
  1582. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1583. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1584. return obj;
  1585. }
  1586. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1587. {
  1588. var program = GetInternalProgram(programId);
  1589. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1590. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1591. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1592. info.Days = new List<DayOfWeek>
  1593. {
  1594. program.StartDate.ToLocalTime().DayOfWeek
  1595. };
  1596. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1597. info.Name = program.Name;
  1598. info.ChannelId = programDto.ChannelId;
  1599. info.ChannelName = programDto.ChannelName;
  1600. info.StartDate = program.StartDate;
  1601. info.Name = program.Name;
  1602. info.Overview = program.Overview;
  1603. info.ProgramId = programDto.Id;
  1604. info.ExternalProgramId = program.ExternalId;
  1605. if (program.EndDate.HasValue)
  1606. {
  1607. info.EndDate = program.EndDate.Value;
  1608. }
  1609. return info;
  1610. }
  1611. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1612. {
  1613. var service = GetService(timer.ServiceName);
  1614. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1615. // Set priority from default values
  1616. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1617. info.Priority = defaultValues.Priority;
  1618. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1619. _lastRecordingRefreshTime = DateTime.MinValue;
  1620. _logger.Info("New recording scheduled");
  1621. }
  1622. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1623. {
  1624. var service = GetService(timer.ServiceName);
  1625. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1626. // Set priority from default values
  1627. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1628. info.Priority = defaultValues.Priority;
  1629. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1630. _lastRecordingRefreshTime = DateTime.MinValue;
  1631. }
  1632. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1633. {
  1634. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1635. var service = GetService(timer.ServiceName);
  1636. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1637. _lastRecordingRefreshTime = DateTime.MinValue;
  1638. }
  1639. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1640. {
  1641. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1642. var service = GetService(timer.ServiceName);
  1643. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1644. _lastRecordingRefreshTime = DateTime.MinValue;
  1645. }
  1646. private IEnumerable<string> GetRecordingGroupNames(ILiveTvRecording recording)
  1647. {
  1648. var list = new List<string>();
  1649. if (recording.IsSeries)
  1650. {
  1651. list.Add(recording.Name);
  1652. }
  1653. if (recording.IsKids)
  1654. {
  1655. list.Add("Kids");
  1656. }
  1657. if (recording.IsMovie)
  1658. {
  1659. list.Add("Movies");
  1660. }
  1661. if (recording.IsNews)
  1662. {
  1663. list.Add("News");
  1664. }
  1665. if (recording.IsSports)
  1666. {
  1667. list.Add("Sports");
  1668. }
  1669. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1670. {
  1671. list.Add("Others");
  1672. }
  1673. return list;
  1674. }
  1675. private List<Guid> GetRecordingGroupIds(ILiveTvRecording recording)
  1676. {
  1677. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1678. .GetMD5())
  1679. .ToList();
  1680. }
  1681. public async Task<QueryResult<BaseItemDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1682. {
  1683. var recordingResult = await GetInternalRecordings(new RecordingQuery
  1684. {
  1685. UserId = query.UserId
  1686. }, cancellationToken).ConfigureAwait(false);
  1687. var recordings = recordingResult.Items.Cast<ILiveTvRecording>().ToList();
  1688. var groups = new List<BaseItemDto>();
  1689. var series = recordings
  1690. .Where(i => i.IsSeries)
  1691. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1692. .ToList();
  1693. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  1694. {
  1695. Name = i.Key,
  1696. RecordingCount = i.Count()
  1697. }));
  1698. groups.Add(new BaseItemDto
  1699. {
  1700. Name = "Kids",
  1701. RecordingCount = recordings.Count(i => i.IsKids)
  1702. });
  1703. groups.Add(new BaseItemDto
  1704. {
  1705. Name = "Movies",
  1706. RecordingCount = recordings.Count(i => i.IsMovie)
  1707. });
  1708. groups.Add(new BaseItemDto
  1709. {
  1710. Name = "News",
  1711. RecordingCount = recordings.Count(i => i.IsNews)
  1712. });
  1713. groups.Add(new BaseItemDto
  1714. {
  1715. Name = "Sports",
  1716. RecordingCount = recordings.Count(i => i.IsSports)
  1717. });
  1718. groups.Add(new BaseItemDto
  1719. {
  1720. Name = "Others",
  1721. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1722. });
  1723. groups = groups
  1724. .Where(i => i.RecordingCount > 0)
  1725. .ToList();
  1726. foreach (var group in groups)
  1727. {
  1728. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1729. }
  1730. return new QueryResult<BaseItemDto>
  1731. {
  1732. Items = groups.ToArray(),
  1733. TotalRecordCount = groups.Count
  1734. };
  1735. }
  1736. class LiveStreamData
  1737. {
  1738. internal MediaSourceInfo Info;
  1739. internal string ItemId;
  1740. internal bool IsChannel;
  1741. }
  1742. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1743. {
  1744. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1745. try
  1746. {
  1747. var parts = id.Split(new[] { '_' }, 2);
  1748. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1749. if (service == null)
  1750. {
  1751. throw new ArgumentException("Service not found.");
  1752. }
  1753. id = parts[1];
  1754. LiveStreamData data;
  1755. _openStreams.TryRemove(id, out data);
  1756. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1757. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1758. }
  1759. catch (Exception ex)
  1760. {
  1761. _logger.ErrorException("Error closing live stream", ex);
  1762. throw;
  1763. }
  1764. finally
  1765. {
  1766. _liveStreamSemaphore.Release();
  1767. }
  1768. }
  1769. public GuideInfo GetGuideInfo()
  1770. {
  1771. var startDate = DateTime.UtcNow;
  1772. var endDate = startDate.AddDays(14);
  1773. return new GuideInfo
  1774. {
  1775. StartDate = startDate,
  1776. EndDate = endDate
  1777. };
  1778. }
  1779. /// <summary>
  1780. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1781. /// </summary>
  1782. public void Dispose()
  1783. {
  1784. Dispose(true);
  1785. }
  1786. private readonly object _disposeLock = new object();
  1787. /// <summary>
  1788. /// Releases unmanaged and - optionally - managed resources.
  1789. /// </summary>
  1790. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1791. protected virtual void Dispose(bool dispose)
  1792. {
  1793. if (dispose)
  1794. {
  1795. lock (_disposeLock)
  1796. {
  1797. foreach (var stream in _openStreams.Values.ToList())
  1798. {
  1799. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1800. Task.WaitAll(task);
  1801. }
  1802. _openStreams.Clear();
  1803. }
  1804. }
  1805. }
  1806. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1807. {
  1808. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1809. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1810. }
  1811. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1812. {
  1813. var info = new LiveTvServiceInfo
  1814. {
  1815. Name = service.Name
  1816. };
  1817. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1818. try
  1819. {
  1820. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1821. info.Status = statusInfo.Status;
  1822. info.StatusMessage = statusInfo.StatusMessage;
  1823. info.Version = statusInfo.Version;
  1824. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1825. info.HomePageUrl = service.HomePageUrl;
  1826. info.IsVisible = statusInfo.IsVisible;
  1827. info.Tuners = statusInfo.Tuners.Select(i =>
  1828. {
  1829. string channelName = null;
  1830. if (!string.IsNullOrEmpty(i.ChannelId))
  1831. {
  1832. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1833. var channel = GetInternalChannel(internalChannelId);
  1834. channelName = channel == null ? null : channel.Name;
  1835. }
  1836. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1837. dto.Id = tunerIdPrefix + dto.Id;
  1838. return dto;
  1839. }).ToList();
  1840. }
  1841. catch (Exception ex)
  1842. {
  1843. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1844. info.Status = LiveTvServiceStatus.Unavailable;
  1845. info.StatusMessage = ex.Message;
  1846. }
  1847. return info;
  1848. }
  1849. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1850. {
  1851. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1852. var servicesList = services.ToList();
  1853. var info = new LiveTvInfo
  1854. {
  1855. Services = servicesList.ToList(),
  1856. IsEnabled = servicesList.Count > 0
  1857. };
  1858. info.EnabledUsers = _userManager.Users
  1859. .Where(IsLiveTvEnabled)
  1860. .Select(i => i.Id.ToString("N"))
  1861. .ToList();
  1862. return info;
  1863. }
  1864. private bool IsLiveTvEnabled(User user)
  1865. {
  1866. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Count(i => i.IsEnabled) > 0);
  1867. }
  1868. public IEnumerable<User> GetEnabledUsers()
  1869. {
  1870. return _userManager.Users
  1871. .Where(IsLiveTvEnabled);
  1872. }
  1873. /// <summary>
  1874. /// Resets the tuner.
  1875. /// </summary>
  1876. /// <param name="id">The identifier.</param>
  1877. /// <param name="cancellationToken">The cancellation token.</param>
  1878. /// <returns>Task.</returns>
  1879. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1880. {
  1881. var parts = id.Split(new[] { '_' }, 2);
  1882. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1883. if (service == null)
  1884. {
  1885. throw new ArgumentException("Service not found.");
  1886. }
  1887. return service.ResetTuner(parts[1], cancellationToken);
  1888. }
  1889. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1890. {
  1891. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1892. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1893. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1894. }
  1895. public async Task<Folder> GetInternalLiveTvFolder(CancellationToken cancellationToken)
  1896. {
  1897. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1898. return await _libraryManager.GetNamedView(name, CollectionType.LiveTv, name, cancellationToken).ConfigureAwait(false);
  1899. }
  1900. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info)
  1901. {
  1902. info = (TunerHostInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(TunerHostInfo));
  1903. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1904. if (provider == null)
  1905. {
  1906. throw new ResourceNotFoundException();
  1907. }
  1908. var configurable = provider as IConfigurableTunerHost;
  1909. if (configurable != null)
  1910. {
  1911. await configurable.Validate(info).ConfigureAwait(false);
  1912. }
  1913. var config = GetConfiguration();
  1914. var index = config.TunerHosts.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1915. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1916. {
  1917. info.Id = Guid.NewGuid().ToString("N");
  1918. config.TunerHosts.Add(info);
  1919. }
  1920. else
  1921. {
  1922. config.TunerHosts[index] = info;
  1923. }
  1924. _config.SaveConfiguration("livetv", config);
  1925. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1926. return info;
  1927. }
  1928. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  1929. {
  1930. info = (ListingsProviderInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(ListingsProviderInfo));
  1931. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1932. if (provider == null)
  1933. {
  1934. throw new ResourceNotFoundException();
  1935. }
  1936. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  1937. var config = GetConfiguration();
  1938. var index = config.ListingProviders.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1939. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1940. {
  1941. info.Id = Guid.NewGuid().ToString("N");
  1942. config.ListingProviders.Add(info);
  1943. }
  1944. else
  1945. {
  1946. config.ListingProviders[index] = info;
  1947. }
  1948. _config.SaveConfiguration("livetv", config);
  1949. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1950. return info;
  1951. }
  1952. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  1953. {
  1954. var config = GetConfiguration();
  1955. if (string.IsNullOrWhiteSpace(providerId))
  1956. {
  1957. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  1958. if (provider == null)
  1959. {
  1960. throw new ResourceNotFoundException();
  1961. }
  1962. return provider.GetLineups(null, country, location);
  1963. }
  1964. else
  1965. {
  1966. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  1967. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1968. if (provider == null)
  1969. {
  1970. throw new ResourceNotFoundException();
  1971. }
  1972. return provider.GetLineups(info, country, location);
  1973. }
  1974. }
  1975. public Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature)
  1976. {
  1977. ILiveTvService service;
  1978. if (string.IsNullOrWhiteSpace(programId))
  1979. {
  1980. var channel = GetInternalChannel(channelId);
  1981. service = GetService(channel);
  1982. }
  1983. else
  1984. {
  1985. var program = GetInternalProgram(programId);
  1986. service = GetService(program);
  1987. }
  1988. var hasRegistration = service as IHasRegistrationInfo;
  1989. if (hasRegistration != null)
  1990. {
  1991. return hasRegistration.GetRegistrationInfo(feature);
  1992. }
  1993. return Task.FromResult(new MBRegistrationRecord
  1994. {
  1995. IsValid = true,
  1996. IsRegistered = true
  1997. });
  1998. }
  1999. }
  2000. }