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. if (!_isDisposed)
  120. {
  121. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  122. }
  123. }
  124. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  125. {
  126. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  127. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  128. var channels = _libraryManager.GetItemList(new InternalItemsQuery
  129. {
  130. IncludeItemTypes = new[] { typeof(LiveTvChannel).Name },
  131. SortBy = new[] { ItemSortBy.SortName },
  132. TopParentIds = new[] { topFolder.Id.ToString("N") }
  133. }).Cast<LiveTvChannel>();
  134. if (user != null)
  135. {
  136. // Avoid implicitly captured closure
  137. var currentUser = user;
  138. channels = channels
  139. .Where(i => i.IsVisible(currentUser))
  140. .OrderBy(i =>
  141. {
  142. double number = 0;
  143. if (!string.IsNullOrEmpty(i.Number))
  144. {
  145. double.TryParse(i.Number, out number);
  146. }
  147. return number;
  148. });
  149. if (query.IsFavorite.HasValue)
  150. {
  151. var val = query.IsFavorite.Value;
  152. channels = channels
  153. .Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val);
  154. }
  155. if (query.IsLiked.HasValue)
  156. {
  157. var val = query.IsLiked.Value;
  158. channels = channels
  159. .Where(i =>
  160. {
  161. var likes = _userDataManager.GetUserData(user, i).Likes;
  162. return likes.HasValue && likes.Value == val;
  163. });
  164. }
  165. if (query.IsDisliked.HasValue)
  166. {
  167. var val = query.IsDisliked.Value;
  168. channels = channels
  169. .Where(i =>
  170. {
  171. var likes = _userDataManager.GetUserData(user, i).Likes;
  172. return likes.HasValue && likes.Value != val;
  173. });
  174. }
  175. }
  176. var enableFavoriteSorting = query.EnableFavoriteSorting;
  177. channels = channels.OrderBy(i =>
  178. {
  179. if (enableFavoriteSorting)
  180. {
  181. var userData = _userDataManager.GetUserData(user, i);
  182. if (userData.IsFavorite)
  183. {
  184. return 0;
  185. }
  186. if (userData.Likes.HasValue)
  187. {
  188. if (!userData.Likes.Value)
  189. {
  190. return 3;
  191. }
  192. return 1;
  193. }
  194. }
  195. return 2;
  196. });
  197. var allChannels = channels.ToList();
  198. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  199. if (query.StartIndex.HasValue)
  200. {
  201. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  202. }
  203. if (query.Limit.HasValue)
  204. {
  205. allEnumerable = allEnumerable.Take(query.Limit.Value);
  206. }
  207. var result = new QueryResult<LiveTvChannel>
  208. {
  209. Items = allEnumerable.ToArray(),
  210. TotalRecordCount = allChannels.Count
  211. };
  212. return result;
  213. }
  214. public LiveTvChannel GetInternalChannel(string id)
  215. {
  216. return GetInternalChannel(new Guid(id));
  217. }
  218. private LiveTvChannel GetInternalChannel(Guid id)
  219. {
  220. return _libraryManager.GetItemById(id) as LiveTvChannel;
  221. }
  222. internal LiveTvProgram GetInternalProgram(string id)
  223. {
  224. return _libraryManager.GetItemById(id) as LiveTvProgram;
  225. }
  226. internal LiveTvProgram GetInternalProgram(Guid id)
  227. {
  228. return _libraryManager.GetItemById(id) as LiveTvProgram;
  229. }
  230. public async Task<BaseItem> GetInternalRecording(string id, CancellationToken cancellationToken)
  231. {
  232. if (string.IsNullOrWhiteSpace(id))
  233. {
  234. throw new ArgumentNullException("id");
  235. }
  236. var result = await GetInternalRecordings(new RecordingQuery
  237. {
  238. Id = id
  239. }, cancellationToken).ConfigureAwait(false);
  240. return result.Items.FirstOrDefault();
  241. }
  242. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  243. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  244. {
  245. return await GetLiveStream(id, null, false, cancellationToken).ConfigureAwait(false);
  246. }
  247. public async Task<MediaSourceInfo> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken)
  248. {
  249. return await GetLiveStream(id, mediaSourceId, true, cancellationToken).ConfigureAwait(false);
  250. }
  251. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  252. {
  253. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  254. var service = GetService(item);
  255. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  256. }
  257. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  258. {
  259. var item = GetInternalChannel(id);
  260. var service = GetService(item);
  261. var sources = await service.GetChannelStreamMediaSources(item.ExternalId, cancellationToken).ConfigureAwait(false);
  262. if (sources.Count == 0)
  263. {
  264. throw new NotImplementedException();
  265. }
  266. var list = sources.ToList();
  267. foreach (var source in list)
  268. {
  269. Normalize(source, service, item.ChannelType == ChannelType.TV);
  270. }
  271. return list;
  272. }
  273. private ILiveTvService GetService(ILiveTvRecording item)
  274. {
  275. return GetService(item.ServiceName);
  276. }
  277. private ILiveTvService GetService(BaseItem item)
  278. {
  279. return GetService(item.ServiceName);
  280. }
  281. private ILiveTvService GetService(string name)
  282. {
  283. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  284. }
  285. private async Task<MediaSourceInfo> GetLiveStream(string id, string mediaSourceId, bool isChannel, CancellationToken cancellationToken)
  286. {
  287. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  288. if (string.Equals(id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  289. {
  290. mediaSourceId = null;
  291. }
  292. try
  293. {
  294. MediaSourceInfo info;
  295. bool isVideo;
  296. ILiveTvService service;
  297. if (isChannel)
  298. {
  299. var channel = GetInternalChannel(id);
  300. isVideo = channel.ChannelType == ChannelType.TV;
  301. service = GetService(channel);
  302. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  303. info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false);
  304. info.RequiresClosing = true;
  305. if (info.RequiresClosing)
  306. {
  307. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  308. info.LiveStreamId = idPrefix + info.Id;
  309. }
  310. }
  311. else
  312. {
  313. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  314. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  315. service = GetService(recording);
  316. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.ExternalId);
  317. info = await service.GetRecordingStream(recording.ExternalId, null, cancellationToken).ConfigureAwait(false);
  318. info.RequiresClosing = true;
  319. if (info.RequiresClosing)
  320. {
  321. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  322. info.LiveStreamId = idPrefix + info.Id;
  323. }
  324. }
  325. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  326. Normalize(info, service, isVideo);
  327. var data = new LiveStreamData
  328. {
  329. Info = info,
  330. IsChannel = isChannel,
  331. ItemId = id
  332. };
  333. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  334. return info;
  335. }
  336. catch (Exception ex)
  337. {
  338. _logger.ErrorException("Error getting channel stream", ex);
  339. throw;
  340. }
  341. finally
  342. {
  343. _liveStreamSemaphore.Release();
  344. }
  345. }
  346. private void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo)
  347. {
  348. if (mediaSource.MediaStreams.Count == 0)
  349. {
  350. if (isVideo)
  351. {
  352. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  353. {
  354. new MediaStream
  355. {
  356. Type = MediaStreamType.Video,
  357. // Set the index to -1 because we don't know the exact index of the video stream within the container
  358. Index = -1,
  359. // Set to true if unknown to enable deinterlacing
  360. IsInterlaced = true
  361. },
  362. new MediaStream
  363. {
  364. Type = MediaStreamType.Audio,
  365. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  366. Index = -1
  367. }
  368. });
  369. }
  370. else
  371. {
  372. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  373. {
  374. new MediaStream
  375. {
  376. Type = MediaStreamType.Audio,
  377. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  378. Index = -1
  379. }
  380. });
  381. }
  382. }
  383. // Clean some bad data coming from providers
  384. foreach (var stream in mediaSource.MediaStreams)
  385. {
  386. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  387. {
  388. stream.BitRate = null;
  389. }
  390. if (stream.Channels.HasValue && stream.Channels <= 0)
  391. {
  392. stream.Channels = null;
  393. }
  394. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  395. {
  396. stream.AverageFrameRate = null;
  397. }
  398. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  399. {
  400. stream.RealFrameRate = null;
  401. }
  402. if (stream.Width.HasValue && stream.Width <= 0)
  403. {
  404. stream.Width = null;
  405. }
  406. if (stream.Height.HasValue && stream.Height <= 0)
  407. {
  408. stream.Height = null;
  409. }
  410. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  411. {
  412. stream.SampleRate = null;
  413. }
  414. if (stream.Level.HasValue && stream.Level <= 0)
  415. {
  416. stream.Level = null;
  417. }
  418. }
  419. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  420. // If there are duplicate stream indexes, set them all to unknown
  421. if (indexes.Count != mediaSource.MediaStreams.Count)
  422. {
  423. foreach (var stream in mediaSource.MediaStreams)
  424. {
  425. stream.Index = -1;
  426. }
  427. }
  428. // Set the total bitrate if not already supplied
  429. if (!mediaSource.Bitrate.HasValue)
  430. {
  431. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  432. if (total > 0)
  433. {
  434. mediaSource.Bitrate = total;
  435. }
  436. }
  437. if (!(service is EmbyTV.EmbyTV))
  438. {
  439. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  440. mediaSource.SupportsDirectStream = false;
  441. mediaSource.SupportsTranscoding = true;
  442. foreach (var stream in mediaSource.MediaStreams)
  443. {
  444. if (stream.Type == MediaStreamType.Video && string.IsNullOrWhiteSpace(stream.NalLengthSize))
  445. {
  446. stream.NalLengthSize = "0";
  447. }
  448. }
  449. }
  450. }
  451. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  452. {
  453. var isNew = false;
  454. var forceUpdate = false;
  455. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  456. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  457. if (item == null)
  458. {
  459. item = new LiveTvChannel
  460. {
  461. Name = channelInfo.Name,
  462. Id = id,
  463. DateCreated = DateTime.UtcNow,
  464. };
  465. isNew = true;
  466. }
  467. if (!string.Equals(channelInfo.Id, item.ExternalId))
  468. {
  469. isNew = true;
  470. }
  471. item.ExternalId = channelInfo.Id;
  472. if (!item.ParentId.Equals(parentFolderId))
  473. {
  474. isNew = true;
  475. }
  476. item.ParentId = parentFolderId;
  477. item.ChannelType = channelInfo.ChannelType;
  478. item.ServiceName = serviceName;
  479. item.Number = channelInfo.Number;
  480. //if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  481. //{
  482. // isNew = true;
  483. // replaceImages.Add(ImageType.Primary);
  484. //}
  485. //if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  486. //{
  487. // isNew = true;
  488. // replaceImages.Add(ImageType.Primary);
  489. //}
  490. if (!item.HasImage(ImageType.Primary))
  491. {
  492. if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
  493. {
  494. item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
  495. forceUpdate = true;
  496. }
  497. else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
  498. {
  499. item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
  500. forceUpdate = true;
  501. }
  502. }
  503. if (string.IsNullOrEmpty(item.Name))
  504. {
  505. item.Name = channelInfo.Name;
  506. }
  507. if (isNew)
  508. {
  509. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  510. }
  511. else if (forceUpdate)
  512. {
  513. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  514. }
  515. await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  516. {
  517. ForceSave = isNew || forceUpdate
  518. }, cancellationToken);
  519. return item;
  520. }
  521. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, LiveTvChannel channel, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  522. {
  523. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  524. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  525. var isNew = false;
  526. var forceUpdate = false;
  527. if (item == null)
  528. {
  529. isNew = true;
  530. item = new LiveTvProgram
  531. {
  532. Name = info.Name,
  533. Id = id,
  534. DateCreated = DateTime.UtcNow,
  535. DateModified = DateTime.UtcNow,
  536. ExternalEtag = info.Etag
  537. };
  538. }
  539. if (!item.ParentId.Equals(channel.Id))
  540. {
  541. forceUpdate = true;
  542. }
  543. item.ParentId = channel.Id;
  544. //item.ChannelType = channelType;
  545. if (!string.Equals(item.ServiceName, serviceName, StringComparison.Ordinal))
  546. {
  547. forceUpdate = true;
  548. }
  549. item.ServiceName = serviceName;
  550. item.Audio = info.Audio;
  551. item.ChannelId = channel.Id.ToString("N");
  552. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  553. item.EpisodeTitle = info.EpisodeTitle;
  554. item.ExternalId = info.Id;
  555. item.Genres = info.Genres;
  556. item.IsHD = info.IsHD;
  557. item.IsKids = info.IsKids;
  558. item.IsLive = info.IsLive;
  559. item.IsMovie = info.IsMovie;
  560. item.IsNews = info.IsNews;
  561. item.IsPremiere = info.IsPremiere;
  562. item.IsRepeat = info.IsRepeat;
  563. item.IsSeries = info.IsSeries;
  564. item.IsSports = info.IsSports;
  565. item.Name = info.Name;
  566. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  567. item.Overview = item.Overview ?? info.Overview;
  568. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  569. if (item.StartDate != info.StartDate)
  570. {
  571. forceUpdate = true;
  572. }
  573. item.StartDate = info.StartDate;
  574. if (item.EndDate != info.EndDate)
  575. {
  576. forceUpdate = true;
  577. }
  578. item.EndDate = info.EndDate;
  579. item.HomePageUrl = info.HomePageUrl;
  580. item.ProductionYear = info.ProductionYear;
  581. item.PremiereDate = info.OriginalAirDate;
  582. item.IndexNumber = info.EpisodeNumber;
  583. item.ParentIndexNumber = info.SeasonNumber;
  584. if (!item.HasImage(ImageType.Primary))
  585. {
  586. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  587. {
  588. item.SetImage(new ItemImageInfo
  589. {
  590. Path = info.ImagePath,
  591. Type = ImageType.Primary,
  592. IsPlaceholder = true
  593. }, 0);
  594. }
  595. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  596. {
  597. item.SetImage(new ItemImageInfo
  598. {
  599. Path = info.ImageUrl,
  600. Type = ImageType.Primary,
  601. IsPlaceholder = true
  602. }, 0);
  603. }
  604. }
  605. if (isNew)
  606. {
  607. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  608. }
  609. else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
  610. {
  611. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  612. }
  613. else
  614. {
  615. // Increment this whenver some internal change deems it necessary
  616. var etag = info.Etag + "4";
  617. if (!string.Equals(etag, item.ExternalEtag, StringComparison.OrdinalIgnoreCase))
  618. {
  619. item.ExternalEtag = etag;
  620. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  621. }
  622. }
  623. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem));
  624. return item;
  625. }
  626. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  627. {
  628. var isNew = false;
  629. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  630. var item = _itemRepo.RetrieveItem(id);
  631. if (item == null)
  632. {
  633. if (info.ChannelType == ChannelType.TV)
  634. {
  635. item = new LiveTvVideoRecording
  636. {
  637. Name = info.Name,
  638. Id = id,
  639. DateCreated = DateTime.UtcNow,
  640. DateModified = DateTime.UtcNow,
  641. VideoType = VideoType.VideoFile
  642. };
  643. }
  644. else
  645. {
  646. item = new LiveTvAudioRecording
  647. {
  648. Name = info.Name,
  649. Id = id,
  650. DateCreated = DateTime.UtcNow,
  651. DateModified = DateTime.UtcNow
  652. };
  653. }
  654. isNew = true;
  655. }
  656. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  657. item.CommunityRating = info.CommunityRating;
  658. item.OfficialRating = info.OfficialRating;
  659. item.Overview = info.Overview;
  660. item.EndDate = info.EndDate;
  661. item.Genres = info.Genres;
  662. item.PremiereDate = info.OriginalAirDate;
  663. var recording = (ILiveTvRecording)item;
  664. recording.ExternalId = info.Id;
  665. var dataChanged = false;
  666. recording.Audio = info.Audio;
  667. recording.EndDate = info.EndDate;
  668. recording.EpisodeTitle = info.EpisodeTitle;
  669. recording.IsHD = info.IsHD;
  670. recording.IsKids = info.IsKids;
  671. recording.IsLive = info.IsLive;
  672. recording.IsMovie = info.IsMovie;
  673. recording.IsNews = info.IsNews;
  674. recording.IsPremiere = info.IsPremiere;
  675. recording.IsRepeat = info.IsRepeat;
  676. recording.IsSports = info.IsSports;
  677. recording.SeriesTimerId = info.SeriesTimerId;
  678. recording.StartDate = info.StartDate;
  679. if (!dataChanged)
  680. {
  681. dataChanged = recording.IsSeries != info.IsSeries;
  682. }
  683. recording.IsSeries = info.IsSeries;
  684. if (!item.ParentId.Equals(parentFolderId))
  685. {
  686. dataChanged = true;
  687. }
  688. item.ParentId = parentFolderId;
  689. if (!item.HasImage(ImageType.Primary))
  690. {
  691. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  692. {
  693. item.SetImage(new ItemImageInfo
  694. {
  695. Path = info.ImagePath,
  696. Type = ImageType.Primary,
  697. IsPlaceholder = true
  698. }, 0);
  699. }
  700. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  701. {
  702. item.SetImage(new ItemImageInfo
  703. {
  704. Path = info.ImageUrl,
  705. Type = ImageType.Primary,
  706. IsPlaceholder = true
  707. }, 0);
  708. }
  709. }
  710. var statusChanged = info.Status != recording.Status;
  711. recording.Status = info.Status;
  712. recording.ServiceName = serviceName;
  713. if (!string.IsNullOrEmpty(info.Path))
  714. {
  715. if (!dataChanged)
  716. {
  717. dataChanged = !string.Equals(item.Path, info.Path);
  718. }
  719. var fileInfo = _fileSystem.GetFileInfo(info.Path);
  720. recording.DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo);
  721. recording.DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo);
  722. item.Path = info.Path;
  723. }
  724. else if (!string.IsNullOrEmpty(info.Url))
  725. {
  726. if (!dataChanged)
  727. {
  728. dataChanged = !string.Equals(item.Path, info.Url);
  729. }
  730. item.Path = info.Url;
  731. }
  732. var metadataRefreshMode = MetadataRefreshMode.Default;
  733. if (isNew)
  734. {
  735. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  736. }
  737. else if (dataChanged || info.DateLastUpdated > recording.DateLastSaved || statusChanged)
  738. {
  739. metadataRefreshMode = MetadataRefreshMode.FullRefresh;
  740. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  741. }
  742. if (info.Status != RecordingStatus.InProgress)
  743. {
  744. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  745. {
  746. MetadataRefreshMode = metadataRefreshMode
  747. });
  748. }
  749. return item.Id;
  750. }
  751. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  752. {
  753. var program = GetInternalProgram(id);
  754. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  755. var list = new List<Tuple<BaseItemDto, string, string>>();
  756. list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ServiceName, program.ExternalId));
  757. await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
  758. return dto;
  759. }
  760. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  761. {
  762. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  763. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  764. if (query.SortBy.Length == 0)
  765. {
  766. // Unless something else was specified, order by start date to take advantage of a specialized index
  767. query.SortBy = new[] { ItemSortBy.StartDate };
  768. }
  769. var internalQuery = new InternalItemsQuery(user)
  770. {
  771. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  772. MinEndDate = query.MinEndDate,
  773. MinStartDate = query.MinStartDate,
  774. MaxEndDate = query.MaxEndDate,
  775. MaxStartDate = query.MaxStartDate,
  776. ChannelIds = query.ChannelIds,
  777. IsMovie = query.IsMovie,
  778. IsSports = query.IsSports,
  779. IsKids = query.IsKids,
  780. Genres = query.Genres,
  781. StartIndex = query.StartIndex,
  782. Limit = query.Limit,
  783. SortBy = query.SortBy,
  784. SortOrder = query.SortOrder ?? SortOrder.Ascending,
  785. EnableTotalRecordCount = query.EnableTotalRecordCount,
  786. TopParentIds = new[] { topFolder.Id.ToString("N") }
  787. };
  788. if (query.HasAired.HasValue)
  789. {
  790. if (query.HasAired.Value)
  791. {
  792. internalQuery.MaxEndDate = DateTime.UtcNow;
  793. }
  794. else
  795. {
  796. internalQuery.MinEndDate = DateTime.UtcNow;
  797. }
  798. }
  799. var queryResult = _libraryManager.QueryItems(internalQuery);
  800. var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ConfigureAwait(false)).ToArray();
  801. var result = new QueryResult<BaseItemDto>
  802. {
  803. Items = returnArray,
  804. TotalRecordCount = queryResult.TotalRecordCount
  805. };
  806. return result;
  807. }
  808. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  809. {
  810. var user = _userManager.GetUserById(query.UserId);
  811. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  812. var internalQuery = new InternalItemsQuery(user)
  813. {
  814. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  815. IsAiring = query.IsAiring,
  816. IsMovie = query.IsMovie,
  817. IsSports = query.IsSports,
  818. IsKids = query.IsKids,
  819. EnableTotalRecordCount = query.EnableTotalRecordCount,
  820. SortBy = new[] { ItemSortBy.StartDate },
  821. TopParentIds = new[] { topFolder.Id.ToString("N") }
  822. };
  823. if (query.Limit.HasValue)
  824. {
  825. internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
  826. }
  827. if (query.HasAired.HasValue)
  828. {
  829. if (query.HasAired.Value)
  830. {
  831. internalQuery.MaxEndDate = DateTime.UtcNow;
  832. }
  833. else
  834. {
  835. internalQuery.MinEndDate = DateTime.UtcNow;
  836. }
  837. }
  838. IEnumerable<LiveTvProgram> programs = _libraryManager.QueryItems(internalQuery).Items.Cast<LiveTvProgram>();
  839. var programList = programs.ToList();
  840. var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false);
  841. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  842. .ThenByDescending(i => GetRecommendationScore(i, user.Id, factorChannelWatchCount))
  843. .ThenBy(i => i.StartDate);
  844. if (query.Limit.HasValue)
  845. {
  846. programs = programs.Take(query.Limit.Value);
  847. }
  848. programList = programs.ToList();
  849. var returnArray = programList.ToArray();
  850. var result = new QueryResult<LiveTvProgram>
  851. {
  852. Items = returnArray,
  853. TotalRecordCount = returnArray.Length
  854. };
  855. return result;
  856. }
  857. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  858. {
  859. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  860. var user = _userManager.GetUserById(query.UserId);
  861. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
  862. var result = new QueryResult<BaseItemDto>
  863. {
  864. Items = returnArray,
  865. TotalRecordCount = internalResult.TotalRecordCount
  866. };
  867. return result;
  868. }
  869. private int GetRecommendationScore(LiveTvProgram program, Guid userId, bool factorChannelWatchCount)
  870. {
  871. var score = 0;
  872. if (program.IsLive)
  873. {
  874. score++;
  875. }
  876. if (program.IsSeries && !program.IsRepeat)
  877. {
  878. score++;
  879. }
  880. var channel = GetInternalChannel(program.ChannelId);
  881. var channelUserdata = _userDataManager.GetUserData(userId, channel);
  882. if (channelUserdata.Likes ?? false)
  883. {
  884. score += 2;
  885. }
  886. else if (!(channelUserdata.Likes ?? true))
  887. {
  888. score -= 2;
  889. }
  890. if (channelUserdata.IsFavorite)
  891. {
  892. score += 3;
  893. }
  894. if (factorChannelWatchCount)
  895. {
  896. score += channelUserdata.PlayCount;
  897. }
  898. return score;
  899. }
  900. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
  901. {
  902. var timers = new Dictionary<string, List<TimerInfo>>();
  903. foreach (var programTuple in programs)
  904. {
  905. var program = programTuple.Item1;
  906. var serviceName = programTuple.Item2;
  907. var externalProgramId = programTuple.Item3;
  908. if (string.IsNullOrWhiteSpace(serviceName))
  909. {
  910. continue;
  911. }
  912. List<TimerInfo> timerList;
  913. if (!timers.TryGetValue(serviceName, out timerList))
  914. {
  915. try
  916. {
  917. var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  918. timers[serviceName] = timerList = tempTimers.ToList();
  919. }
  920. catch (Exception ex)
  921. {
  922. _logger.ErrorException("Error getting timer infos", ex);
  923. timers[serviceName] = timerList = new List<TimerInfo>();
  924. }
  925. }
  926. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  927. if (timer != null)
  928. {
  929. program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id)
  930. .ToString("N");
  931. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  932. {
  933. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
  934. .ToString("N");
  935. }
  936. }
  937. }
  938. }
  939. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  940. {
  941. return RefreshChannelsInternal(progress, cancellationToken);
  942. }
  943. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  944. {
  945. EmbyTV.EmbyTV.Current.CreateRecordingFolders();
  946. var numComplete = 0;
  947. double progressPerService = _services.Count == 0
  948. ? 0
  949. : 1 / _services.Count;
  950. var newChannelIdList = new List<Guid>();
  951. var newProgramIdList = new List<Guid>();
  952. foreach (var service in _services)
  953. {
  954. cancellationToken.ThrowIfCancellationRequested();
  955. _logger.Debug("Refreshing guide from {0}", service.Name);
  956. try
  957. {
  958. var innerProgress = new ActionableProgress<double>();
  959. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  960. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  961. newChannelIdList.AddRange(idList.Item1);
  962. newProgramIdList.AddRange(idList.Item2);
  963. }
  964. catch (OperationCanceledException)
  965. {
  966. throw;
  967. }
  968. catch (Exception ex)
  969. {
  970. _logger.ErrorException("Error refreshing channels for service", ex);
  971. }
  972. numComplete++;
  973. double percent = numComplete;
  974. percent /= _services.Count;
  975. progress.Report(100 * percent);
  976. }
  977. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  978. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  979. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  980. if (coreService != null)
  981. {
  982. await coreService.RefreshSeriesTimers(cancellationToken, new Progress<double>()).ConfigureAwait(false);
  983. }
  984. // Load these now which will prefetch metadata
  985. var dtoOptions = new DtoOptions();
  986. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  987. dtoOptions.Fields.Remove(ItemFields.BasicSyncInfo);
  988. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  989. progress.Report(100);
  990. }
  991. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  992. {
  993. progress.Report(10);
  994. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  995. var allChannelsList = allChannels.ToList();
  996. var list = new List<LiveTvChannel>();
  997. var numComplete = 0;
  998. var parentFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  999. var parentFolderId = parentFolder.Id;
  1000. foreach (var channelInfo in allChannelsList)
  1001. {
  1002. cancellationToken.ThrowIfCancellationRequested();
  1003. try
  1004. {
  1005. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolderId, cancellationToken).ConfigureAwait(false);
  1006. list.Add(item);
  1007. }
  1008. catch (OperationCanceledException)
  1009. {
  1010. throw;
  1011. }
  1012. catch (Exception ex)
  1013. {
  1014. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  1015. }
  1016. numComplete++;
  1017. double percent = numComplete;
  1018. percent /= allChannelsList.Count;
  1019. progress.Report(5 * percent + 10);
  1020. }
  1021. progress.Report(15);
  1022. numComplete = 0;
  1023. var programs = new List<Guid>();
  1024. var channels = new List<Guid>();
  1025. var guideDays = GetGuideDays();
  1026. _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
  1027. cancellationToken.ThrowIfCancellationRequested();
  1028. foreach (var currentChannel in list)
  1029. {
  1030. channels.Add(currentChannel.Id);
  1031. cancellationToken.ThrowIfCancellationRequested();
  1032. try
  1033. {
  1034. var start = DateTime.UtcNow.AddHours(-1);
  1035. var end = start.AddDays(guideDays);
  1036. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  1037. foreach (var program in channelPrograms)
  1038. {
  1039. var programItem = await GetProgram(program, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  1040. programs.Add(programItem.Id);
  1041. }
  1042. }
  1043. catch (OperationCanceledException)
  1044. {
  1045. throw;
  1046. }
  1047. catch (Exception ex)
  1048. {
  1049. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  1050. }
  1051. numComplete++;
  1052. double percent = numComplete;
  1053. percent /= allChannelsList.Count;
  1054. progress.Report(80 * percent + 10);
  1055. }
  1056. progress.Report(100);
  1057. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1058. }
  1059. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1060. {
  1061. var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
  1062. {
  1063. IncludeItemTypes = validTypes
  1064. }).ToList();
  1065. var numComplete = 0;
  1066. foreach (var itemId in list)
  1067. {
  1068. cancellationToken.ThrowIfCancellationRequested();
  1069. if (itemId == Guid.Empty)
  1070. {
  1071. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1072. continue;
  1073. }
  1074. if (!currentIdList.Contains(itemId))
  1075. {
  1076. var item = _libraryManager.GetItemById(itemId);
  1077. if (item != null)
  1078. {
  1079. await _libraryManager.DeleteItem(item, new DeleteOptions
  1080. {
  1081. DeleteFileLocation = false
  1082. }).ConfigureAwait(false);
  1083. }
  1084. }
  1085. numComplete++;
  1086. double percent = numComplete;
  1087. percent /= list.Count;
  1088. progress.Report(100 * percent);
  1089. }
  1090. }
  1091. private const int MaxGuideDays = 14;
  1092. private double GetGuideDays()
  1093. {
  1094. var config = GetConfiguration();
  1095. if (config.GuideDays.HasValue)
  1096. {
  1097. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1098. }
  1099. return 7;
  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. private bool _isDisposed = false;
  1877. /// <summary>
  1878. /// Releases unmanaged and - optionally - managed resources.
  1879. /// </summary>
  1880. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1881. protected virtual void Dispose(bool dispose)
  1882. {
  1883. if (dispose)
  1884. {
  1885. _isDisposed = true;
  1886. lock (_disposeLock)
  1887. {
  1888. foreach (var stream in _openStreams.Values.ToList())
  1889. {
  1890. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1891. Task.WaitAll(task);
  1892. }
  1893. _openStreams.Clear();
  1894. }
  1895. }
  1896. }
  1897. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1898. {
  1899. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1900. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1901. }
  1902. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1903. {
  1904. var info = new LiveTvServiceInfo
  1905. {
  1906. Name = service.Name
  1907. };
  1908. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1909. try
  1910. {
  1911. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1912. info.Status = statusInfo.Status;
  1913. info.StatusMessage = statusInfo.StatusMessage;
  1914. info.Version = statusInfo.Version;
  1915. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1916. info.HomePageUrl = service.HomePageUrl;
  1917. info.IsVisible = statusInfo.IsVisible;
  1918. info.Tuners = statusInfo.Tuners.Select(i =>
  1919. {
  1920. string channelName = null;
  1921. if (!string.IsNullOrEmpty(i.ChannelId))
  1922. {
  1923. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1924. var channel = GetInternalChannel(internalChannelId);
  1925. channelName = channel == null ? null : channel.Name;
  1926. }
  1927. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1928. dto.Id = tunerIdPrefix + dto.Id;
  1929. return dto;
  1930. }).ToList();
  1931. }
  1932. catch (Exception ex)
  1933. {
  1934. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1935. info.Status = LiveTvServiceStatus.Unavailable;
  1936. info.StatusMessage = ex.Message;
  1937. }
  1938. return info;
  1939. }
  1940. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1941. {
  1942. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1943. var servicesList = services.ToList();
  1944. var info = new LiveTvInfo
  1945. {
  1946. Services = servicesList.ToList(),
  1947. IsEnabled = servicesList.Count > 0
  1948. };
  1949. info.EnabledUsers = _userManager.Users
  1950. .Where(IsLiveTvEnabled)
  1951. .Select(i => i.Id.ToString("N"))
  1952. .ToList();
  1953. return info;
  1954. }
  1955. private bool IsLiveTvEnabled(User user)
  1956. {
  1957. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Count(i => i.IsEnabled) > 0);
  1958. }
  1959. public IEnumerable<User> GetEnabledUsers()
  1960. {
  1961. return _userManager.Users
  1962. .Where(IsLiveTvEnabled);
  1963. }
  1964. /// <summary>
  1965. /// Resets the tuner.
  1966. /// </summary>
  1967. /// <param name="id">The identifier.</param>
  1968. /// <param name="cancellationToken">The cancellation token.</param>
  1969. /// <returns>Task.</returns>
  1970. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1971. {
  1972. var parts = id.Split(new[] { '_' }, 2);
  1973. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1974. if (service == null)
  1975. {
  1976. throw new ArgumentException("Service not found.");
  1977. }
  1978. return service.ResetTuner(parts[1], cancellationToken);
  1979. }
  1980. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1981. {
  1982. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1983. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1984. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1985. }
  1986. public async Task<Folder> GetInternalLiveTvFolder(CancellationToken cancellationToken)
  1987. {
  1988. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1989. return await _libraryManager.GetNamedView(name, CollectionType.LiveTv, name, cancellationToken).ConfigureAwait(false);
  1990. }
  1991. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info)
  1992. {
  1993. info = (TunerHostInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(TunerHostInfo));
  1994. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1995. if (provider == null)
  1996. {
  1997. throw new ResourceNotFoundException();
  1998. }
  1999. var configurable = provider as IConfigurableTunerHost;
  2000. if (configurable != null)
  2001. {
  2002. await configurable.Validate(info).ConfigureAwait(false);
  2003. }
  2004. var config = GetConfiguration();
  2005. var index = config.TunerHosts.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2006. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2007. {
  2008. info.Id = Guid.NewGuid().ToString("N");
  2009. config.TunerHosts.Add(info);
  2010. }
  2011. else
  2012. {
  2013. config.TunerHosts[index] = info;
  2014. }
  2015. _config.SaveConfiguration("livetv", config);
  2016. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2017. return info;
  2018. }
  2019. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  2020. {
  2021. info = (ListingsProviderInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(ListingsProviderInfo));
  2022. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2023. if (provider == null)
  2024. {
  2025. throw new ResourceNotFoundException();
  2026. }
  2027. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  2028. var config = GetConfiguration();
  2029. var index = config.ListingProviders.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2030. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2031. {
  2032. info.Id = Guid.NewGuid().ToString("N");
  2033. config.ListingProviders.Add(info);
  2034. }
  2035. else
  2036. {
  2037. config.ListingProviders[index] = info;
  2038. }
  2039. _config.SaveConfiguration("livetv", config);
  2040. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2041. return info;
  2042. }
  2043. public void DeleteListingsProvider(string id)
  2044. {
  2045. var config = GetConfiguration();
  2046. config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToList();
  2047. _config.SaveConfiguration("livetv", config);
  2048. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2049. }
  2050. public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
  2051. {
  2052. var config = GetConfiguration();
  2053. var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
  2054. listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
  2055. if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
  2056. {
  2057. var list = listingsProviderInfo.ChannelMappings.ToList();
  2058. list.Add(new NameValuePair
  2059. {
  2060. Name = tunerChannelNumber,
  2061. Value = providerChannelNumber
  2062. });
  2063. listingsProviderInfo.ChannelMappings = list.ToArray();
  2064. }
  2065. _config.SaveConfiguration("livetv", config);
  2066. var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
  2067. .ConfigureAwait(false);
  2068. var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
  2069. .ConfigureAwait(false);
  2070. var mappings = listingsProviderInfo.ChannelMappings.ToList();
  2071. var tunerChannelMappings =
  2072. tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
  2073. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2074. return tunerChannelMappings.First(i => string.Equals(i.Number, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2075. }
  2076. public TunerChannelMapping GetTunerChannelMapping(ChannelInfo channel, List<NameValuePair> mappings, List<ChannelInfo> providerChannels)
  2077. {
  2078. var result = new TunerChannelMapping
  2079. {
  2080. Name = channel.Number + " " + channel.Name,
  2081. Number = channel.Number
  2082. };
  2083. var mapping = mappings.FirstOrDefault(i => string.Equals(i.Name, channel.Number, StringComparison.OrdinalIgnoreCase));
  2084. var providerChannelNumber = channel.Number;
  2085. if (mapping != null)
  2086. {
  2087. providerChannelNumber = mapping.Value;
  2088. }
  2089. var providerChannel = providerChannels.FirstOrDefault(i => string.Equals(i.Number, providerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2090. if (providerChannel != null)
  2091. {
  2092. result.ProviderChannelNumber = providerChannel.Number;
  2093. result.ProviderChannelName = providerChannel.Name;
  2094. }
  2095. return result;
  2096. }
  2097. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  2098. {
  2099. var config = GetConfiguration();
  2100. if (string.IsNullOrWhiteSpace(providerId))
  2101. {
  2102. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  2103. if (provider == null)
  2104. {
  2105. throw new ResourceNotFoundException();
  2106. }
  2107. return provider.GetLineups(null, country, location);
  2108. }
  2109. else
  2110. {
  2111. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  2112. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2113. if (provider == null)
  2114. {
  2115. throw new ResourceNotFoundException();
  2116. }
  2117. return provider.GetLineups(info, country, location);
  2118. }
  2119. }
  2120. public Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature)
  2121. {
  2122. ILiveTvService service;
  2123. if (string.IsNullOrWhiteSpace(programId))
  2124. {
  2125. var channel = GetInternalChannel(channelId);
  2126. service = GetService(channel);
  2127. }
  2128. else
  2129. {
  2130. var program = GetInternalProgram(programId);
  2131. service = GetService(program);
  2132. }
  2133. var hasRegistration = service as IHasRegistrationInfo;
  2134. if (hasRegistration != null)
  2135. {
  2136. return hasRegistration.GetRegistrationInfo(feature);
  2137. }
  2138. return Task.FromResult(new MBRegistrationRecord
  2139. {
  2140. IsValid = true,
  2141. IsRegistered = true
  2142. });
  2143. }
  2144. public List<NameValuePair> GetSatIniMappings()
  2145. {
  2146. var names = GetType().Assembly.GetManifestResourceNames().Where(i => i.IndexOf("SatIp.ini", StringComparison.OrdinalIgnoreCase) != -1).ToList();
  2147. return names.Select(GetSatIniMappings).Where(i => i != null).DistinctBy(i => i.Value.Split('|')[0]).ToList();
  2148. }
  2149. public NameValuePair GetSatIniMappings(string resource)
  2150. {
  2151. using (var stream = GetType().Assembly.GetManifestResourceStream(resource))
  2152. {
  2153. using (var reader = new StreamReader(stream))
  2154. {
  2155. var parser = new StreamIniDataParser();
  2156. IniData data = parser.ReadData(reader);
  2157. var satType1 = data["SATTYPE"]["1"];
  2158. var satType2 = data["SATTYPE"]["2"];
  2159. if (string.IsNullOrWhiteSpace(satType2))
  2160. {
  2161. return null;
  2162. }
  2163. var srch = "SatIp.ini.";
  2164. var filename = Path.GetFileName(resource);
  2165. return new NameValuePair
  2166. {
  2167. Name = satType1 + " " + satType2,
  2168. Value = satType2 + "|" + filename.Substring(filename.IndexOf(srch) + srch.Length)
  2169. };
  2170. }
  2171. }
  2172. }
  2173. public Task<List<ChannelInfo>> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken)
  2174. {
  2175. return new TunerHosts.SatIp.ChannelScan(_logger).Scan(info, cancellationToken);
  2176. }
  2177. public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
  2178. {
  2179. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2180. return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
  2181. }
  2182. public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
  2183. {
  2184. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2185. var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
  2186. return provider.GetChannels(info, cancellationToken);
  2187. }
  2188. }
  2189. }