LiveTvManager.cs 82 KB

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