LiveTvManager.cs 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  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 System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. namespace MediaBrowser.Server.Implementations.LiveTv
  29. {
  30. /// <summary>
  31. /// Class LiveTvManager
  32. /// </summary>
  33. public class LiveTvManager : ILiveTvManager, IDisposable
  34. {
  35. private readonly IServerConfigurationManager _config;
  36. private readonly ILogger _logger;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IUserManager _userManager;
  39. private readonly IUserDataManager _userDataManager;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly ITaskManager _taskManager;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly IProviderManager _providerManager;
  44. private readonly IDtoService _dtoService;
  45. private readonly ILocalizationManager _localization;
  46. private readonly LiveTvDtoService _tvDtoService;
  47. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  48. private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
  49. new ConcurrentDictionary<string, LiveStreamData>();
  50. private readonly SemaphoreSlim _refreshRecordingsLock = new SemaphoreSlim(1, 1);
  51. 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)
  52. {
  53. _config = config;
  54. _logger = logger;
  55. _itemRepo = itemRepo;
  56. _userManager = userManager;
  57. _libraryManager = libraryManager;
  58. _taskManager = taskManager;
  59. _localization = localization;
  60. _jsonSerializer = jsonSerializer;
  61. _providerManager = providerManager;
  62. _dtoService = dtoService;
  63. _userDataManager = userDataManager;
  64. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost);
  65. }
  66. /// <summary>
  67. /// Gets the services.
  68. /// </summary>
  69. /// <value>The services.</value>
  70. public IReadOnlyList<ILiveTvService> Services
  71. {
  72. get { return _services; }
  73. }
  74. private LiveTvOptions GetConfiguration()
  75. {
  76. return _config.GetConfiguration<LiveTvOptions>("livetv");
  77. }
  78. /// <summary>
  79. /// Adds the parts.
  80. /// </summary>
  81. /// <param name="services">The services.</param>
  82. public void AddParts(IEnumerable<ILiveTvService> services)
  83. {
  84. _services.AddRange(services);
  85. foreach (var service in _services)
  86. {
  87. service.DataSourceChanged += service_DataSourceChanged;
  88. }
  89. }
  90. void service_DataSourceChanged(object sender, EventArgs e)
  91. {
  92. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  93. }
  94. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  95. {
  96. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  97. var channels = _libraryManager.GetItems(new InternalItemsQuery
  98. {
  99. IncludeItemTypes = new[] { typeof(LiveTvChannel).Name }
  100. }).Items.Cast<LiveTvChannel>();
  101. if (user != null)
  102. {
  103. // Avoid implicitly captured closure
  104. var currentUser = user;
  105. channels = channels
  106. .Where(i => i.IsVisible(currentUser))
  107. .OrderBy(i =>
  108. {
  109. double number = 0;
  110. if (!string.IsNullOrEmpty(i.Number))
  111. {
  112. double.TryParse(i.Number, out number);
  113. }
  114. return number;
  115. });
  116. if (query.IsFavorite.HasValue)
  117. {
  118. var val = query.IsFavorite.Value;
  119. channels = channels
  120. .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
  121. }
  122. if (query.IsLiked.HasValue)
  123. {
  124. var val = query.IsLiked.Value;
  125. channels = channels
  126. .Where(i =>
  127. {
  128. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  129. return likes.HasValue && likes.Value == val;
  130. });
  131. }
  132. if (query.IsDisliked.HasValue)
  133. {
  134. var val = query.IsDisliked.Value;
  135. channels = channels
  136. .Where(i =>
  137. {
  138. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  139. return likes.HasValue && likes.Value != val;
  140. });
  141. }
  142. }
  143. var enableFavoriteSorting = query.EnableFavoriteSorting;
  144. channels = channels.OrderBy(i =>
  145. {
  146. if (enableFavoriteSorting)
  147. {
  148. var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey());
  149. if (userData.IsFavorite)
  150. {
  151. return 0;
  152. }
  153. if (userData.Likes.HasValue)
  154. {
  155. if (!userData.Likes.Value)
  156. {
  157. return 3;
  158. }
  159. return 1;
  160. }
  161. }
  162. return 2;
  163. });
  164. var allChannels = channels.ToList();
  165. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  166. if (query.StartIndex.HasValue)
  167. {
  168. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  169. }
  170. if (query.Limit.HasValue)
  171. {
  172. allEnumerable = allEnumerable.Take(query.Limit.Value);
  173. }
  174. var result = new QueryResult<LiveTvChannel>
  175. {
  176. Items = allEnumerable.ToArray(),
  177. TotalRecordCount = allChannels.Count
  178. };
  179. return result;
  180. }
  181. public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  182. {
  183. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  184. var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);
  185. var returnList = new List<ChannelInfoDto>();
  186. var now = DateTime.UtcNow;
  187. var programs = _libraryManager.GetItems(new InternalItemsQuery
  188. {
  189. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  190. MaxStartDate = now,
  191. MinEndDate = now
  192. }).Items.Cast<LiveTvProgram>().OrderBy(i => i.StartDate).ToList();
  193. foreach (var channel in internalResult.Items)
  194. {
  195. var channelIdString = channel.Id.ToString("N");
  196. var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString, StringComparison.OrdinalIgnoreCase));
  197. returnList.Add(_tvDtoService.GetChannelInfoDto(channel, currentProgram, user));
  198. }
  199. var result = new QueryResult<ChannelInfoDto>
  200. {
  201. Items = returnList.ToArray(),
  202. TotalRecordCount = internalResult.TotalRecordCount
  203. };
  204. return result;
  205. }
  206. public LiveTvChannel GetInternalChannel(string id)
  207. {
  208. return GetInternalChannel(new Guid(id));
  209. }
  210. private LiveTvChannel GetInternalChannel(Guid id)
  211. {
  212. return _libraryManager.GetItemById(id) as LiveTvChannel;
  213. }
  214. internal LiveTvProgram GetInternalProgram(string id)
  215. {
  216. return _libraryManager.GetItemById(id) as LiveTvProgram;
  217. }
  218. internal LiveTvProgram GetInternalProgram(Guid id)
  219. {
  220. return _libraryManager.GetItemById(id) as LiveTvProgram;
  221. }
  222. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  223. {
  224. var result = await GetInternalRecordings(new RecordingQuery
  225. {
  226. Id = id
  227. }, cancellationToken).ConfigureAwait(false);
  228. return result.Items.FirstOrDefault() as ILiveTvRecording;
  229. }
  230. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  231. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  232. {
  233. return await GetLiveStream(id, null, false, cancellationToken).ConfigureAwait(false);
  234. }
  235. public async Task<MediaSourceInfo> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken)
  236. {
  237. return await GetLiveStream(id, mediaSourceId, true, cancellationToken).ConfigureAwait(false);
  238. }
  239. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  240. {
  241. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  242. var service = GetService(item);
  243. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  244. }
  245. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  246. {
  247. var item = GetInternalChannel(id);
  248. var service = GetService(item);
  249. var sources = await service.GetChannelStreamMediaSources(item.ExternalId, cancellationToken).ConfigureAwait(false);
  250. var list = sources.ToList();
  251. foreach (var source in list)
  252. {
  253. Normalize(source, item.ChannelType == ChannelType.TV);
  254. }
  255. return list;
  256. }
  257. private ILiveTvService GetService(ILiveTvItem item)
  258. {
  259. return GetService(item.ServiceName);
  260. }
  261. private ILiveTvService GetService(string name)
  262. {
  263. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  264. }
  265. private async Task<MediaSourceInfo> GetLiveStream(string id, string mediaSourceId, bool isChannel, CancellationToken cancellationToken)
  266. {
  267. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  268. try
  269. {
  270. MediaSourceInfo info;
  271. bool isVideo;
  272. if (isChannel)
  273. {
  274. var channel = GetInternalChannel(id);
  275. isVideo = channel.ChannelType == ChannelType.TV;
  276. var service = GetService(channel);
  277. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  278. info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false);
  279. info.RequiresClosing = true;
  280. if (info.RequiresClosing)
  281. {
  282. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  283. info.LiveStreamId = idPrefix + info.Id;
  284. }
  285. }
  286. else
  287. {
  288. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  289. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  290. var service = GetService(recording);
  291. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.ExternalId);
  292. info = await service.GetRecordingStream(recording.ExternalId, null, cancellationToken).ConfigureAwait(false);
  293. info.RequiresClosing = true;
  294. if (info.RequiresClosing)
  295. {
  296. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  297. info.LiveStreamId = idPrefix + info.Id;
  298. }
  299. }
  300. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  301. Normalize(info, isVideo);
  302. var data = new LiveStreamData
  303. {
  304. Info = info,
  305. IsChannel = isChannel,
  306. ItemId = id
  307. };
  308. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  309. return info;
  310. }
  311. catch (Exception ex)
  312. {
  313. _logger.ErrorException("Error getting channel stream", ex);
  314. throw;
  315. }
  316. finally
  317. {
  318. _liveStreamSemaphore.Release();
  319. }
  320. }
  321. private void Normalize(MediaSourceInfo mediaSource, bool isVideo)
  322. {
  323. if (mediaSource.MediaStreams.Count == 0)
  324. {
  325. if (isVideo)
  326. {
  327. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  328. {
  329. new MediaStream
  330. {
  331. Type = MediaStreamType.Video,
  332. // Set the index to -1 because we don't know the exact index of the video stream within the container
  333. Index = -1,
  334. // Set to true if unknown to enable deinterlacing
  335. IsInterlaced = true
  336. },
  337. new MediaStream
  338. {
  339. Type = MediaStreamType.Audio,
  340. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  341. Index = -1
  342. }
  343. });
  344. }
  345. else
  346. {
  347. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  348. {
  349. new MediaStream
  350. {
  351. Type = MediaStreamType.Audio,
  352. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  353. Index = -1
  354. }
  355. });
  356. }
  357. }
  358. // Clean some bad data coming from providers
  359. foreach (var stream in mediaSource.MediaStreams)
  360. {
  361. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  362. {
  363. stream.BitRate = null;
  364. }
  365. if (stream.Channels.HasValue && stream.Channels <= 0)
  366. {
  367. stream.Channels = null;
  368. }
  369. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  370. {
  371. stream.AverageFrameRate = null;
  372. }
  373. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  374. {
  375. stream.RealFrameRate = null;
  376. }
  377. if (stream.Width.HasValue && stream.Width <= 0)
  378. {
  379. stream.Width = null;
  380. }
  381. if (stream.Height.HasValue && stream.Height <= 0)
  382. {
  383. stream.Height = null;
  384. }
  385. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  386. {
  387. stream.SampleRate = null;
  388. }
  389. if (stream.Level.HasValue && stream.Level <= 0)
  390. {
  391. stream.Level = null;
  392. }
  393. }
  394. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  395. // If there are duplicate stream indexes, set them all to unknown
  396. if (indexes.Count != mediaSource.MediaStreams.Count)
  397. {
  398. foreach (var stream in mediaSource.MediaStreams)
  399. {
  400. stream.Index = -1;
  401. }
  402. }
  403. // Set the total bitrate if not already supplied
  404. if (!mediaSource.Bitrate.HasValue)
  405. {
  406. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  407. if (total > 0)
  408. {
  409. mediaSource.Bitrate = total;
  410. }
  411. }
  412. }
  413. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  414. {
  415. var isNew = false;
  416. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  417. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  418. if (item == null)
  419. {
  420. item = new LiveTvChannel
  421. {
  422. Name = channelInfo.Name,
  423. Id = id,
  424. DateCreated = DateTime.UtcNow,
  425. };
  426. isNew = true;
  427. }
  428. item.ChannelType = channelInfo.ChannelType;
  429. item.ExternalId = channelInfo.Id;
  430. item.ServiceName = serviceName;
  431. item.Number = channelInfo.Number;
  432. var replaceImages = new List<ImageType>();
  433. if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  434. {
  435. isNew = true;
  436. replaceImages.Add(ImageType.Primary);
  437. }
  438. if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  439. {
  440. isNew = true;
  441. replaceImages.Add(ImageType.Primary);
  442. }
  443. item.ProviderImageUrl = channelInfo.ImageUrl;
  444. item.HasProviderImage = channelInfo.HasImage;
  445. item.ProviderImagePath = channelInfo.ImagePath;
  446. if (string.IsNullOrEmpty(item.Name))
  447. {
  448. item.Name = channelInfo.Name;
  449. }
  450. await item.RefreshMetadata(new MetadataRefreshOptions
  451. {
  452. ForceSave = isNew,
  453. ReplaceImages = replaceImages.Distinct().ToList()
  454. }, cancellationToken);
  455. return item;
  456. }
  457. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, string channelId, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  458. {
  459. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  460. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  461. var isNew = false;
  462. if (item == null)
  463. {
  464. isNew = true;
  465. item = new LiveTvProgram
  466. {
  467. Name = info.Name,
  468. Id = id,
  469. DateCreated = DateTime.UtcNow,
  470. DateModified = DateTime.UtcNow
  471. };
  472. }
  473. item.ChannelType = channelType;
  474. item.ServiceName = serviceName;
  475. item.Audio = info.Audio;
  476. item.ChannelId = channelId;
  477. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  478. item.EndDate = info.EndDate;
  479. item.EpisodeTitle = info.EpisodeTitle;
  480. item.ExternalId = info.Id;
  481. item.Genres = info.Genres;
  482. item.HasProviderImage = info.HasImage;
  483. item.IsHD = info.IsHD;
  484. item.IsKids = info.IsKids;
  485. item.IsLive = info.IsLive;
  486. item.IsMovie = info.IsMovie;
  487. item.IsNews = info.IsNews;
  488. item.IsPremiere = info.IsPremiere;
  489. item.IsRepeat = info.IsRepeat;
  490. item.IsSeries = info.IsSeries;
  491. item.IsSports = info.IsSports;
  492. item.Name = info.Name;
  493. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  494. item.Overview = item.Overview ?? info.Overview;
  495. item.OriginalAirDate = info.OriginalAirDate;
  496. item.ProviderImagePath = info.ImagePath;
  497. item.ProviderImageUrl = info.ImageUrl;
  498. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  499. item.StartDate = info.StartDate;
  500. item.ProductionYear = info.ProductionYear;
  501. item.PremiereDate = item.PremiereDate ?? info.OriginalAirDate;
  502. if (isNew)
  503. {
  504. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  505. }
  506. else
  507. {
  508. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  509. }
  510. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions());
  511. return item;
  512. }
  513. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  514. {
  515. var isNew = false;
  516. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  517. var item = _itemRepo.RetrieveItem(id);
  518. if (item == null)
  519. {
  520. if (info.ChannelType == ChannelType.TV)
  521. {
  522. item = new LiveTvVideoRecording
  523. {
  524. Name = info.Name,
  525. Id = id,
  526. DateCreated = DateTime.UtcNow,
  527. DateModified = DateTime.UtcNow,
  528. VideoType = VideoType.VideoFile
  529. };
  530. }
  531. else
  532. {
  533. item = new LiveTvAudioRecording
  534. {
  535. Name = info.Name,
  536. Id = id,
  537. DateCreated = DateTime.UtcNow,
  538. DateModified = DateTime.UtcNow
  539. };
  540. }
  541. isNew = true;
  542. }
  543. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  544. item.CommunityRating = info.CommunityRating;
  545. item.OfficialRating = info.OfficialRating;
  546. item.Overview = info.Overview;
  547. item.EndDate = info.EndDate;
  548. item.Genres = info.Genres;
  549. var recording = (ILiveTvRecording)item;
  550. recording.ProgramId = _tvDtoService.GetInternalProgramId(serviceName, info.ProgramId).ToString("N");
  551. recording.Audio = info.Audio;
  552. recording.ChannelType = info.ChannelType;
  553. recording.EndDate = info.EndDate;
  554. recording.EpisodeTitle = info.EpisodeTitle;
  555. recording.ProviderImagePath = info.ImagePath;
  556. recording.ProviderImageUrl = info.ImageUrl;
  557. recording.IsHD = info.IsHD;
  558. recording.IsKids = info.IsKids;
  559. recording.IsLive = info.IsLive;
  560. recording.IsMovie = info.IsMovie;
  561. recording.IsNews = info.IsNews;
  562. recording.IsPremiere = info.IsPremiere;
  563. recording.IsRepeat = info.IsRepeat;
  564. recording.IsSeries = info.IsSeries;
  565. recording.IsSports = info.IsSports;
  566. recording.OriginalAirDate = info.OriginalAirDate;
  567. recording.SeriesTimerId = info.SeriesTimerId;
  568. recording.StartDate = info.StartDate;
  569. recording.Status = info.Status;
  570. recording.ServiceName = serviceName;
  571. var originalPath = item.Path;
  572. if (!string.IsNullOrEmpty(info.Path))
  573. {
  574. item.Path = info.Path;
  575. }
  576. else if (!string.IsNullOrEmpty(info.Url))
  577. {
  578. item.Path = info.Url;
  579. }
  580. var pathChanged = !string.Equals(originalPath, item.Path);
  581. if (isNew)
  582. {
  583. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  584. }
  585. else if (pathChanged)
  586. {
  587. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  588. }
  589. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions());
  590. return item.Id;
  591. }
  592. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  593. {
  594. var program = GetInternalProgram(id);
  595. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  596. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  597. return dto;
  598. }
  599. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  600. {
  601. var internalQuery = new InternalItemsQuery
  602. {
  603. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  604. MinEndDate = query.MinEndDate,
  605. MinStartDate = query.MinStartDate,
  606. MaxEndDate = query.MaxEndDate,
  607. MaxStartDate = query.MaxStartDate,
  608. ChannelIds = query.ChannelIds,
  609. IsMovie = query.IsMovie,
  610. IsSports = query.IsSports
  611. };
  612. if (query.HasAired.HasValue)
  613. {
  614. if (query.HasAired.Value)
  615. {
  616. internalQuery.MaxEndDate = DateTime.UtcNow;
  617. }
  618. else
  619. {
  620. internalQuery.MinEndDate = DateTime.UtcNow;
  621. }
  622. }
  623. IEnumerable<LiveTvProgram> programs = _libraryManager.GetItems(internalQuery).Items.Cast<LiveTvProgram>();
  624. // Apply genre filter
  625. if (query.Genres.Length > 0)
  626. {
  627. programs = programs.Where(p => p.Genres.Any(g => query.Genres.Contains(g, StringComparer.OrdinalIgnoreCase)));
  628. }
  629. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  630. if (user != null)
  631. {
  632. // Avoid implicitly captured closure
  633. var currentUser = user;
  634. programs = programs.Where(i => i.IsVisible(currentUser));
  635. }
  636. programs = _libraryManager.Sort(programs, user, query.SortBy, query.SortOrder ?? SortOrder.Ascending)
  637. .Cast<LiveTvProgram>();
  638. var programList = programs.ToList();
  639. IEnumerable<LiveTvProgram> returnPrograms = programList;
  640. if (query.StartIndex.HasValue)
  641. {
  642. returnPrograms = returnPrograms.Skip(query.StartIndex.Value);
  643. }
  644. if (query.Limit.HasValue)
  645. {
  646. returnPrograms = returnPrograms.Take(query.Limit.Value);
  647. }
  648. var returnArray = returnPrograms
  649. .Select(i => _dtoService.GetBaseItemDto(i, new DtoOptions(), user))
  650. .ToArray();
  651. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  652. var result = new QueryResult<BaseItemDto>
  653. {
  654. Items = returnArray,
  655. TotalRecordCount = programList.Count
  656. };
  657. return result;
  658. }
  659. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  660. {
  661. var internalQuery = new InternalItemsQuery
  662. {
  663. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  664. IsAiring = query.IsAiring,
  665. IsMovie = query.IsMovie,
  666. IsSports = query.IsSports
  667. };
  668. if (query.HasAired.HasValue)
  669. {
  670. if (query.HasAired.Value)
  671. {
  672. internalQuery.MaxEndDate = DateTime.UtcNow;
  673. }
  674. else
  675. {
  676. internalQuery.MinEndDate = DateTime.UtcNow;
  677. }
  678. }
  679. IEnumerable<LiveTvProgram> programs = _libraryManager.GetItems(internalQuery).Items.Cast<LiveTvProgram>();
  680. var user = _userManager.GetUserById(query.UserId);
  681. // Avoid implicitly captured closure
  682. var currentUser = user;
  683. programs = programs.Where(i => i.IsVisible(currentUser));
  684. var programList = programs.ToList();
  685. var genres = programList.SelectMany(i => i.Genres)
  686. .DistinctNames()
  687. .Select(i => _libraryManager.GetGenre(i))
  688. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  689. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  690. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  691. .ThenBy(i => i.StartDate);
  692. if (query.Limit.HasValue)
  693. {
  694. programs = programs.Take(query.Limit.Value)
  695. .OrderBy(i => i.StartDate);
  696. }
  697. programList = programs.ToList();
  698. var returnArray = programList.ToArray();
  699. var result = new QueryResult<LiveTvProgram>
  700. {
  701. Items = returnArray,
  702. TotalRecordCount = returnArray.Length
  703. };
  704. return result;
  705. }
  706. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  707. {
  708. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  709. var user = _userManager.GetUserById(query.UserId);
  710. var returnArray = internalResult.Items
  711. .Select(i => _dtoService.GetBaseItemDto(i, new DtoOptions(), user))
  712. .ToArray();
  713. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  714. var result = new QueryResult<BaseItemDto>
  715. {
  716. Items = returnArray,
  717. TotalRecordCount = internalResult.TotalRecordCount
  718. };
  719. return result;
  720. }
  721. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  722. {
  723. var score = 0;
  724. if (program.IsLive)
  725. {
  726. score++;
  727. }
  728. if (program.IsSeries && !program.IsRepeat)
  729. {
  730. score++;
  731. }
  732. var channel = GetInternalChannel(program.ChannelId);
  733. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  734. if ((channelUserdata.Likes ?? false))
  735. {
  736. score += 2;
  737. }
  738. else if (!(channelUserdata.Likes ?? true))
  739. {
  740. score -= 2;
  741. }
  742. if (channelUserdata.IsFavorite)
  743. {
  744. score += 3;
  745. }
  746. score += GetGenreScore(program.Genres, userId, genres);
  747. return score;
  748. }
  749. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  750. {
  751. return programGenres.Select(i =>
  752. {
  753. var score = 0;
  754. Genre genre;
  755. if (genres.TryGetValue(i, out genre))
  756. {
  757. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  758. if ((genreUserdata.Likes ?? false))
  759. {
  760. score++;
  761. }
  762. else if (!(genreUserdata.Likes ?? true))
  763. {
  764. score--;
  765. }
  766. if (genreUserdata.IsFavorite)
  767. {
  768. score += 2;
  769. }
  770. }
  771. return score;
  772. }).Sum();
  773. }
  774. private async Task AddRecordingInfo(IEnumerable<BaseItemDto> programs, CancellationToken cancellationToken)
  775. {
  776. var timers = new Dictionary<string, List<TimerInfo>>();
  777. foreach (var program in programs)
  778. {
  779. var internalProgram = GetInternalProgram(program.Id);
  780. List<TimerInfo> timerList;
  781. if (!timers.TryGetValue(internalProgram.ServiceName, out timerList))
  782. {
  783. try
  784. {
  785. var tempTimers = await GetService(internalProgram.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  786. timers[internalProgram.ServiceName] = timerList = tempTimers.ToList();
  787. }
  788. catch (Exception ex)
  789. {
  790. _logger.ErrorException("Error getting timer infos", ex);
  791. timers[internalProgram.ServiceName] = timerList = new List<TimerInfo>();
  792. }
  793. }
  794. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, internalProgram.ExternalId, StringComparison.OrdinalIgnoreCase));
  795. if (timer != null)
  796. {
  797. program.TimerId = _tvDtoService.GetInternalTimerId(internalProgram.ServiceName, timer.Id)
  798. .ToString("N");
  799. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  800. {
  801. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(internalProgram.ServiceName, timer.SeriesTimerId)
  802. .ToString("N");
  803. }
  804. }
  805. }
  806. }
  807. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  808. {
  809. return RefreshChannelsInternal(progress, cancellationToken);
  810. }
  811. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  812. {
  813. var numComplete = 0;
  814. double progressPerService = _services.Count == 0
  815. ? 0
  816. : 1 / _services.Count;
  817. var newChannelIdList = new List<Guid>();
  818. var newProgramIdList = new List<Guid>();
  819. foreach (var service in _services)
  820. {
  821. cancellationToken.ThrowIfCancellationRequested();
  822. try
  823. {
  824. var innerProgress = new ActionableProgress<double>();
  825. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  826. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  827. newChannelIdList.AddRange(idList.Item1);
  828. newProgramIdList.AddRange(idList.Item2);
  829. }
  830. catch (OperationCanceledException)
  831. {
  832. throw;
  833. }
  834. catch (Exception ex)
  835. {
  836. _logger.ErrorException("Error refreshing channels for service", ex);
  837. }
  838. numComplete++;
  839. double percent = numComplete;
  840. percent /= _services.Count;
  841. progress.Report(100 * percent);
  842. }
  843. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  844. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  845. // Load these now which will prefetch metadata
  846. var dtoOptions = new DtoOptions();
  847. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  848. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  849. progress.Report(100);
  850. }
  851. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  852. {
  853. progress.Report(10);
  854. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  855. var allChannelsList = allChannels.ToList();
  856. var list = new List<LiveTvChannel>();
  857. var numComplete = 0;
  858. foreach (var channelInfo in allChannelsList)
  859. {
  860. cancellationToken.ThrowIfCancellationRequested();
  861. try
  862. {
  863. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  864. list.Add(item);
  865. _libraryManager.RegisterItem(item);
  866. }
  867. catch (OperationCanceledException)
  868. {
  869. throw;
  870. }
  871. catch (Exception ex)
  872. {
  873. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  874. }
  875. numComplete++;
  876. double percent = numComplete;
  877. percent /= allChannelsList.Count;
  878. progress.Report(5 * percent + 10);
  879. }
  880. progress.Report(15);
  881. numComplete = 0;
  882. var programs = new List<Guid>();
  883. var channels = new List<Guid>();
  884. var guideDays = GetGuideDays(list.Count);
  885. cancellationToken.ThrowIfCancellationRequested();
  886. foreach (var currentChannel in list)
  887. {
  888. channels.Add(currentChannel.Id);
  889. cancellationToken.ThrowIfCancellationRequested();
  890. try
  891. {
  892. var start = DateTime.UtcNow.AddHours(-1);
  893. var end = start.AddDays(guideDays);
  894. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  895. var channelId = currentChannel.Id.ToString("N");
  896. foreach (var program in channelPrograms)
  897. {
  898. var programItem = await GetProgram(program, channelId, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  899. programs.Add(programItem.Id);
  900. }
  901. }
  902. catch (OperationCanceledException)
  903. {
  904. throw;
  905. }
  906. catch (Exception ex)
  907. {
  908. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  909. }
  910. numComplete++;
  911. double percent = numComplete;
  912. percent /= allChannelsList.Count;
  913. progress.Report(80 * percent + 10);
  914. }
  915. progress.Report(100);
  916. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  917. }
  918. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  919. {
  920. var list = _itemRepo.GetItemIds(new InternalItemsQuery
  921. {
  922. IncludeItemTypes = validTypes
  923. }).Items.ToList();
  924. var numComplete = 0;
  925. foreach (var itemId in list)
  926. {
  927. cancellationToken.ThrowIfCancellationRequested();
  928. if (!currentIdList.Contains(itemId))
  929. {
  930. var item = _libraryManager.GetItemById(itemId);
  931. if (item != null)
  932. {
  933. await _libraryManager.DeleteItem(item, new DeleteOptions
  934. {
  935. DeleteFileLocation = false
  936. }).ConfigureAwait(false);
  937. }
  938. }
  939. numComplete++;
  940. double percent = numComplete;
  941. percent /= list.Count;
  942. progress.Report(100 * percent);
  943. }
  944. }
  945. private double GetGuideDays(int channelCount)
  946. {
  947. var config = GetConfiguration();
  948. if (config.GuideDays.HasValue)
  949. {
  950. return config.GuideDays.Value;
  951. }
  952. var programsPerDay = channelCount * 48;
  953. const int maxPrograms = 24000;
  954. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  955. return Math.Max(3, Math.Min(days, 14));
  956. }
  957. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  958. {
  959. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  960. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  961. }
  962. private DateTime _lastRecordingRefreshTime;
  963. private async Task RefreshRecordings(CancellationToken cancellationToken)
  964. {
  965. const int cacheMinutes = 5;
  966. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  967. {
  968. return;
  969. }
  970. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  971. try
  972. {
  973. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  974. {
  975. return;
  976. }
  977. var tasks = _services.Select(async i =>
  978. {
  979. try
  980. {
  981. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  982. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  983. }
  984. catch (Exception ex)
  985. {
  986. _logger.ErrorException("Error getting recordings", ex);
  987. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  988. }
  989. });
  990. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  991. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, cancellationToken));
  992. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  993. CleanDatabaseInternal(idList.ToList(), new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  994. _lastRecordingRefreshTime = DateTime.UtcNow;
  995. }
  996. finally
  997. {
  998. _refreshRecordingsLock.Release();
  999. }
  1000. }
  1001. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1002. {
  1003. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1004. if (user != null && !IsLiveTvEnabled(user))
  1005. {
  1006. return new QueryResult<BaseItem>();
  1007. }
  1008. await RefreshRecordings(cancellationToken).ConfigureAwait(false);
  1009. var internalQuery = new InternalItemsQuery
  1010. {
  1011. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }
  1012. };
  1013. if (!string.IsNullOrEmpty(query.ChannelId))
  1014. {
  1015. internalQuery.ChannelIds = new[] { query.ChannelId };
  1016. }
  1017. var queryResult = _libraryManager.GetItems(internalQuery);
  1018. IEnumerable<ILiveTvRecording> recordings = queryResult.Items.Cast<ILiveTvRecording>();
  1019. if (!string.IsNullOrEmpty(query.Id))
  1020. {
  1021. var guid = new Guid(query.Id);
  1022. recordings = recordings
  1023. .Where(i => i.Id == guid);
  1024. }
  1025. if (!string.IsNullOrEmpty(query.GroupId))
  1026. {
  1027. var guid = new Guid(query.GroupId);
  1028. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1029. }
  1030. if (query.IsInProgress.HasValue)
  1031. {
  1032. var val = query.IsInProgress.Value;
  1033. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  1034. }
  1035. if (query.Status.HasValue)
  1036. {
  1037. var val = query.Status.Value;
  1038. recordings = recordings.Where(i => (i.Status == val));
  1039. }
  1040. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1041. {
  1042. var guid = new Guid(query.SeriesTimerId);
  1043. recordings = recordings
  1044. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1045. }
  1046. if (user != null)
  1047. {
  1048. var currentUser = user;
  1049. recordings = recordings.Where(i => i.IsParentalAllowed(currentUser));
  1050. }
  1051. recordings = recordings.OrderByDescending(i => i.StartDate);
  1052. var entityList = recordings.ToList();
  1053. IEnumerable<ILiveTvRecording> entities = entityList;
  1054. if (query.StartIndex.HasValue)
  1055. {
  1056. entities = entities.Skip(query.StartIndex.Value);
  1057. }
  1058. if (query.Limit.HasValue)
  1059. {
  1060. entities = entities.Take(query.Limit.Value);
  1061. }
  1062. return new QueryResult<BaseItem>
  1063. {
  1064. Items = entities.Cast<BaseItem>().ToArray(),
  1065. TotalRecordCount = entityList.Count
  1066. };
  1067. }
  1068. public void AddInfoToProgramDto(BaseItem item, BaseItemDto dto, User user = null)
  1069. {
  1070. var program = (LiveTvProgram)item;
  1071. var service = GetService(program);
  1072. var channel = GetInternalChannel(program.ChannelId);
  1073. dto.Id = _tvDtoService.GetInternalProgramId(service.Name, program.ExternalId).ToString("N");
  1074. dto.ChannelId = item.ChannelId;
  1075. dto.StartDate = program.StartDate;
  1076. dto.IsRepeat = program.IsRepeat;
  1077. dto.EpisodeTitle = program.EpisodeTitle;
  1078. dto.ChannelType = program.ChannelType;
  1079. dto.Audio = program.Audio;
  1080. dto.IsHD = program.IsHD;
  1081. dto.IsMovie = program.IsMovie;
  1082. dto.IsSeries = program.IsSeries;
  1083. dto.IsSports = program.IsSports;
  1084. dto.IsLive = program.IsLive;
  1085. dto.IsNews = program.IsNews;
  1086. dto.IsKids = program.IsKids;
  1087. dto.IsPremiere = program.IsPremiere;
  1088. dto.OriginalAirDate = program.OriginalAirDate;
  1089. if (channel != null)
  1090. {
  1091. dto.ChannelName = channel.Name;
  1092. if (!string.IsNullOrEmpty(channel.PrimaryImagePath))
  1093. {
  1094. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1095. }
  1096. }
  1097. }
  1098. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1099. {
  1100. var recording = (ILiveTvRecording)item;
  1101. var service = GetService(recording);
  1102. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1103. var info = recording;
  1104. dto.Id = item.Id.ToString("N");
  1105. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1106. ? null
  1107. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1108. dto.ChannelId = item.ChannelId;
  1109. dto.StartDate = info.StartDate;
  1110. dto.RecordingStatus = info.Status;
  1111. dto.IsRepeat = info.IsRepeat;
  1112. dto.EpisodeTitle = info.EpisodeTitle;
  1113. dto.ChannelType = info.ChannelType;
  1114. dto.Audio = info.Audio;
  1115. dto.IsHD = info.IsHD;
  1116. dto.IsMovie = info.IsMovie;
  1117. dto.IsSeries = info.IsSeries;
  1118. dto.IsSports = info.IsSports;
  1119. dto.IsLive = info.IsLive;
  1120. dto.IsNews = info.IsNews;
  1121. dto.IsKids = info.IsKids;
  1122. dto.IsPremiere = info.IsPremiere;
  1123. dto.OriginalAirDate = info.OriginalAirDate;
  1124. dto.CanDelete = user == null
  1125. ? recording.CanDelete()
  1126. : recording.CanDelete(user);
  1127. if (dto.MediaSources == null)
  1128. {
  1129. dto.MediaSources = recording.GetMediaSources(true).ToList();
  1130. }
  1131. if (dto.MediaStreams == null)
  1132. {
  1133. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToList();
  1134. }
  1135. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1136. {
  1137. var now = DateTime.UtcNow.Ticks;
  1138. var start = info.StartDate.Ticks;
  1139. var end = info.EndDate.Value.Ticks;
  1140. var pct = now - start;
  1141. pct /= end;
  1142. pct *= 100;
  1143. dto.CompletionPercentage = pct;
  1144. }
  1145. dto.ProgramId = info.ProgramId;
  1146. if (channel != null)
  1147. {
  1148. dto.ChannelName = channel.Name;
  1149. if (!string.IsNullOrEmpty(channel.PrimaryImagePath))
  1150. {
  1151. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1152. }
  1153. }
  1154. }
  1155. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1156. {
  1157. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1158. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1159. var returnArray = internalResult.Items
  1160. .Select(i => _dtoService.GetBaseItemDto(i, options, user))
  1161. .ToArray();
  1162. if (user != null)
  1163. {
  1164. _dtoService.FillSyncInfo(returnArray, new DtoOptions(), user);
  1165. }
  1166. return new QueryResult<BaseItemDto>
  1167. {
  1168. Items = returnArray,
  1169. TotalRecordCount = internalResult.TotalRecordCount
  1170. };
  1171. }
  1172. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1173. {
  1174. var tasks = _services.Select(async i =>
  1175. {
  1176. try
  1177. {
  1178. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1179. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1180. }
  1181. catch (Exception ex)
  1182. {
  1183. _logger.ErrorException("Error getting recordings", ex);
  1184. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1185. }
  1186. });
  1187. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1188. var timers = results.SelectMany(i => i.ToList());
  1189. if (!string.IsNullOrEmpty(query.ChannelId))
  1190. {
  1191. var guid = new Guid(query.ChannelId);
  1192. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1193. }
  1194. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1195. {
  1196. var guid = new Guid(query.SeriesTimerId);
  1197. timers = timers
  1198. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1199. }
  1200. var returnList = new List<TimerInfoDto>();
  1201. foreach (var i in timers)
  1202. {
  1203. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1204. null :
  1205. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1206. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1207. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1208. }
  1209. var returnArray = returnList
  1210. .OrderBy(i => i.StartDate)
  1211. .ToArray();
  1212. return new QueryResult<TimerInfoDto>
  1213. {
  1214. Items = returnArray,
  1215. TotalRecordCount = returnArray.Length
  1216. };
  1217. }
  1218. public async Task DeleteRecording(string recordingId)
  1219. {
  1220. var recording = await GetInternalRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1221. if (recording == null)
  1222. {
  1223. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1224. }
  1225. var service = GetService(recording.ServiceName);
  1226. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1227. _lastRecordingRefreshTime = DateTime.MinValue;
  1228. }
  1229. public async Task CancelTimer(string id)
  1230. {
  1231. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1232. if (timer == null)
  1233. {
  1234. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1235. }
  1236. var service = GetService(timer.ServiceName);
  1237. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1238. _lastRecordingRefreshTime = DateTime.MinValue;
  1239. }
  1240. public async Task CancelSeriesTimer(string id)
  1241. {
  1242. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1243. if (timer == null)
  1244. {
  1245. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1246. }
  1247. var service = GetService(timer.ServiceName);
  1248. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1249. _lastRecordingRefreshTime = DateTime.MinValue;
  1250. }
  1251. public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1252. {
  1253. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  1254. if (item == null)
  1255. {
  1256. return null;
  1257. }
  1258. return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
  1259. }
  1260. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1261. {
  1262. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1263. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1264. }
  1265. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1266. {
  1267. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1268. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1269. }
  1270. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1271. {
  1272. var tasks = _services.Select(async i =>
  1273. {
  1274. try
  1275. {
  1276. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1277. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1278. }
  1279. catch (Exception ex)
  1280. {
  1281. _logger.ErrorException("Error getting recordings", ex);
  1282. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1283. }
  1284. });
  1285. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1286. var timers = results.SelectMany(i => i.ToList());
  1287. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1288. {
  1289. timers = query.SortOrder == SortOrder.Descending ?
  1290. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1291. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1292. }
  1293. else
  1294. {
  1295. timers = query.SortOrder == SortOrder.Descending ?
  1296. timers.OrderByStringDescending(i => i.Item1.Name) :
  1297. timers.OrderByString(i => i.Item1.Name);
  1298. }
  1299. var returnArray = timers
  1300. .Select(i =>
  1301. {
  1302. string channelName = null;
  1303. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1304. {
  1305. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1306. var channel = GetInternalChannel(internalChannelId);
  1307. channelName = channel == null ? null : channel.Name;
  1308. }
  1309. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1310. })
  1311. .ToArray();
  1312. return new QueryResult<SeriesTimerInfoDto>
  1313. {
  1314. Items = returnArray,
  1315. TotalRecordCount = returnArray.Length
  1316. };
  1317. }
  1318. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1319. {
  1320. var channel = GetInternalChannel(id);
  1321. var now = DateTime.UtcNow;
  1322. var programs = _libraryManager.GetItems(new InternalItemsQuery
  1323. {
  1324. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1325. ChannelIds = new[] { id },
  1326. MaxStartDate = now,
  1327. MinEndDate = now,
  1328. Limit = 1
  1329. }).Items.Cast<LiveTvProgram>();
  1330. var currentProgram = programs
  1331. .OrderBy(i => i.StartDate)
  1332. .FirstOrDefault();
  1333. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1334. return dto;
  1335. }
  1336. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1337. {
  1338. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1339. GetService(program) :
  1340. _services.FirstOrDefault();
  1341. ProgramInfo programInfo = null;
  1342. if (program != null)
  1343. {
  1344. var channel = GetInternalChannel(program.ChannelId);
  1345. programInfo = new ProgramInfo
  1346. {
  1347. Audio = program.Audio,
  1348. ChannelId = channel.ExternalId,
  1349. CommunityRating = program.CommunityRating,
  1350. EndDate = program.EndDate ?? DateTime.MinValue,
  1351. EpisodeTitle = program.EpisodeTitle,
  1352. Genres = program.Genres,
  1353. HasImage = program.HasProviderImage,
  1354. Id = program.ExternalId,
  1355. IsHD = program.IsHD,
  1356. IsKids = program.IsKids,
  1357. IsLive = program.IsLive,
  1358. IsMovie = program.IsMovie,
  1359. IsNews = program.IsNews,
  1360. IsPremiere = program.IsPremiere,
  1361. IsRepeat = program.IsRepeat,
  1362. IsSeries = program.IsSeries,
  1363. IsSports = program.IsSports,
  1364. OriginalAirDate = program.PremiereDate,
  1365. Overview = program.Overview,
  1366. StartDate = program.StartDate,
  1367. ImagePath = program.ProviderImagePath,
  1368. ImageUrl = program.ProviderImageUrl,
  1369. Name = program.Name,
  1370. OfficialRating = program.OfficialRating
  1371. };
  1372. }
  1373. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1374. info.Id = null;
  1375. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1376. }
  1377. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1378. {
  1379. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1380. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1381. return obj;
  1382. }
  1383. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1384. {
  1385. var program = GetInternalProgram(programId);
  1386. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1387. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1388. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1389. info.Days = new List<DayOfWeek>
  1390. {
  1391. program.StartDate.ToLocalTime().DayOfWeek
  1392. };
  1393. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1394. info.Name = program.Name;
  1395. info.ChannelId = programDto.ChannelId;
  1396. info.ChannelName = programDto.ChannelName;
  1397. info.StartDate = program.StartDate;
  1398. info.Name = program.Name;
  1399. info.Overview = program.Overview;
  1400. info.ProgramId = programDto.Id;
  1401. info.ExternalProgramId = program.ExternalId;
  1402. if (program.EndDate.HasValue)
  1403. {
  1404. info.EndDate = program.EndDate.Value;
  1405. }
  1406. return info;
  1407. }
  1408. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1409. {
  1410. var service = GetService(timer.ServiceName);
  1411. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1412. // Set priority from default values
  1413. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1414. info.Priority = defaultValues.Priority;
  1415. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1416. _lastRecordingRefreshTime = DateTime.MinValue;
  1417. }
  1418. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1419. {
  1420. var service = GetService(timer.ServiceName);
  1421. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1422. // Set priority from default values
  1423. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1424. info.Priority = defaultValues.Priority;
  1425. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1426. _lastRecordingRefreshTime = DateTime.MinValue;
  1427. }
  1428. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1429. {
  1430. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1431. var service = GetService(timer.ServiceName);
  1432. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1433. _lastRecordingRefreshTime = DateTime.MinValue;
  1434. }
  1435. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1436. {
  1437. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1438. var service = GetService(timer.ServiceName);
  1439. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1440. _lastRecordingRefreshTime = DateTime.MinValue;
  1441. }
  1442. private IEnumerable<string> GetRecordingGroupNames(ILiveTvRecording recording)
  1443. {
  1444. var list = new List<string>();
  1445. if (recording.IsSeries)
  1446. {
  1447. list.Add(recording.Name);
  1448. }
  1449. if (recording.IsKids)
  1450. {
  1451. list.Add("Kids");
  1452. }
  1453. if (recording.IsMovie)
  1454. {
  1455. list.Add("Movies");
  1456. }
  1457. if (recording.IsNews)
  1458. {
  1459. list.Add("News");
  1460. }
  1461. if (recording.IsSports)
  1462. {
  1463. list.Add("Sports");
  1464. }
  1465. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1466. {
  1467. list.Add("Others");
  1468. }
  1469. return list;
  1470. }
  1471. private List<Guid> GetRecordingGroupIds(ILiveTvRecording recording)
  1472. {
  1473. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1474. .GetMD5())
  1475. .ToList();
  1476. }
  1477. public async Task<QueryResult<BaseItemDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1478. {
  1479. var recordingResult = await GetInternalRecordings(new RecordingQuery
  1480. {
  1481. UserId = query.UserId
  1482. }, cancellationToken).ConfigureAwait(false);
  1483. var recordings = recordingResult.Items.Cast<ILiveTvRecording>().ToList();
  1484. var groups = new List<BaseItemDto>();
  1485. var series = recordings
  1486. .Where(i => i.IsSeries)
  1487. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1488. .ToList();
  1489. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  1490. {
  1491. Name = i.Key,
  1492. RecordingCount = i.Count()
  1493. }));
  1494. groups.Add(new BaseItemDto
  1495. {
  1496. Name = "Kids",
  1497. RecordingCount = recordings.Count(i => i.IsKids)
  1498. });
  1499. groups.Add(new BaseItemDto
  1500. {
  1501. Name = "Movies",
  1502. RecordingCount = recordings.Count(i => i.IsMovie)
  1503. });
  1504. groups.Add(new BaseItemDto
  1505. {
  1506. Name = "News",
  1507. RecordingCount = recordings.Count(i => i.IsNews)
  1508. });
  1509. groups.Add(new BaseItemDto
  1510. {
  1511. Name = "Sports",
  1512. RecordingCount = recordings.Count(i => i.IsSports)
  1513. });
  1514. groups.Add(new BaseItemDto
  1515. {
  1516. Name = "Others",
  1517. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1518. });
  1519. groups = groups
  1520. .Where(i => i.RecordingCount > 0)
  1521. .ToList();
  1522. foreach (var group in groups)
  1523. {
  1524. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1525. }
  1526. return new QueryResult<BaseItemDto>
  1527. {
  1528. Items = groups.ToArray(),
  1529. TotalRecordCount = groups.Count
  1530. };
  1531. }
  1532. class LiveStreamData
  1533. {
  1534. internal MediaSourceInfo Info;
  1535. internal string ItemId;
  1536. internal bool IsChannel;
  1537. }
  1538. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1539. {
  1540. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1541. try
  1542. {
  1543. var parts = id.Split(new[] { '_' }, 2);
  1544. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1545. if (service == null)
  1546. {
  1547. throw new ArgumentException("Service not found.");
  1548. }
  1549. id = parts[1];
  1550. LiveStreamData data;
  1551. _openStreams.TryRemove(id, out data);
  1552. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1553. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1554. }
  1555. catch (Exception ex)
  1556. {
  1557. _logger.ErrorException("Error closing live stream", ex);
  1558. throw;
  1559. }
  1560. finally
  1561. {
  1562. _liveStreamSemaphore.Release();
  1563. }
  1564. }
  1565. public GuideInfo GetGuideInfo()
  1566. {
  1567. var startDate = DateTime.UtcNow;
  1568. var endDate = startDate.AddDays(14);
  1569. return new GuideInfo
  1570. {
  1571. StartDate = startDate,
  1572. EndDate = endDate
  1573. };
  1574. }
  1575. /// <summary>
  1576. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1577. /// </summary>
  1578. public void Dispose()
  1579. {
  1580. Dispose(true);
  1581. }
  1582. private readonly object _disposeLock = new object();
  1583. /// <summary>
  1584. /// Releases unmanaged and - optionally - managed resources.
  1585. /// </summary>
  1586. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1587. protected virtual void Dispose(bool dispose)
  1588. {
  1589. if (dispose)
  1590. {
  1591. lock (_disposeLock)
  1592. {
  1593. foreach (var stream in _openStreams.Values.ToList())
  1594. {
  1595. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1596. Task.WaitAll(task);
  1597. }
  1598. _openStreams.Clear();
  1599. }
  1600. }
  1601. }
  1602. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1603. {
  1604. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1605. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1606. }
  1607. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1608. {
  1609. var info = new LiveTvServiceInfo
  1610. {
  1611. Name = service.Name
  1612. };
  1613. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1614. try
  1615. {
  1616. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1617. info.Status = statusInfo.Status;
  1618. info.StatusMessage = statusInfo.StatusMessage;
  1619. info.Version = statusInfo.Version;
  1620. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1621. info.HomePageUrl = service.HomePageUrl;
  1622. info.Tuners = statusInfo.Tuners.Select(i =>
  1623. {
  1624. string channelName = null;
  1625. if (!string.IsNullOrEmpty(i.ChannelId))
  1626. {
  1627. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1628. var channel = GetInternalChannel(internalChannelId);
  1629. channelName = channel == null ? null : channel.Name;
  1630. }
  1631. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1632. dto.Id = tunerIdPrefix + dto.Id;
  1633. return dto;
  1634. }).ToList();
  1635. }
  1636. catch (Exception ex)
  1637. {
  1638. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1639. info.Status = LiveTvServiceStatus.Unavailable;
  1640. info.StatusMessage = ex.Message;
  1641. }
  1642. return info;
  1643. }
  1644. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1645. {
  1646. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1647. var servicesList = services.ToList();
  1648. var info = new LiveTvInfo
  1649. {
  1650. Services = servicesList.ToList(),
  1651. IsEnabled = servicesList.Count > 0
  1652. };
  1653. info.EnabledUsers = _userManager.Users
  1654. .Where(IsLiveTvEnabled)
  1655. .Select(i => i.Id.ToString("N"))
  1656. .ToList();
  1657. return info;
  1658. }
  1659. private bool IsLiveTvEnabled(User user)
  1660. {
  1661. return user.Policy.EnableLiveTvAccess && Services.Count > 0;
  1662. }
  1663. public IEnumerable<User> GetEnabledUsers()
  1664. {
  1665. return _userManager.Users
  1666. .Where(IsLiveTvEnabled);
  1667. }
  1668. /// <summary>
  1669. /// Resets the tuner.
  1670. /// </summary>
  1671. /// <param name="id">The identifier.</param>
  1672. /// <param name="cancellationToken">The cancellation token.</param>
  1673. /// <returns>Task.</returns>
  1674. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1675. {
  1676. var parts = id.Split(new[] { '_' }, 2);
  1677. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1678. if (service == null)
  1679. {
  1680. throw new ArgumentException("Service not found.");
  1681. }
  1682. return service.ResetTuner(parts[1], cancellationToken);
  1683. }
  1684. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1685. {
  1686. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1687. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1688. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1689. }
  1690. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1691. {
  1692. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1693. var user = _userManager.GetUserById(userId);
  1694. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1695. }
  1696. }
  1697. }