LiveTvManager.cs 82 KB

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