LiveTvManager.cs 88 KB

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