LiveTvManager.cs 94 KB

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