LiveTvManager.cs 84 KB

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