LiveTvManager.cs 95 KB

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