LiveTvManager.cs 99 KB

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