LiveTvManager.cs 89 KB

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