LiveTvManager.cs 89 KB

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