LiveTvManager.cs 77 KB

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