LiveTvManager.cs 90 KB

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