LiveTvManager.cs 98 KB

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