LiveTvManager.cs 98 KB

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