LiveTvManager.cs 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  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.EpisodeTitle = info.EpisodeTitle;
  551. item.ExternalId = info.Id;
  552. item.Genres = info.Genres;
  553. item.IsHD = info.IsHD;
  554. item.IsKids = info.IsKids;
  555. item.IsLive = info.IsLive;
  556. item.IsMovie = info.IsMovie;
  557. item.IsNews = info.IsNews;
  558. item.IsPremiere = info.IsPremiere;
  559. item.IsRepeat = info.IsRepeat;
  560. item.IsSeries = info.IsSeries;
  561. item.IsSports = info.IsSports;
  562. item.Name = info.Name;
  563. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  564. item.Overview = item.Overview ?? info.Overview;
  565. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  566. if (item.StartDate != info.StartDate)
  567. {
  568. forceUpdate = true;
  569. }
  570. item.StartDate = info.StartDate;
  571. if (item.EndDate != info.EndDate)
  572. {
  573. forceUpdate = true;
  574. }
  575. item.EndDate = info.EndDate;
  576. item.HomePageUrl = info.HomePageUrl;
  577. item.ProductionYear = info.ProductionYear;
  578. item.PremiereDate = info.OriginalAirDate;
  579. item.IndexNumber = info.EpisodeNumber;
  580. item.ParentIndexNumber = info.SeasonNumber;
  581. if (!item.HasImage(ImageType.Primary))
  582. {
  583. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  584. {
  585. item.SetImage(new ItemImageInfo
  586. {
  587. Path = info.ImagePath,
  588. Type = ImageType.Primary,
  589. IsPlaceholder = true
  590. }, 0);
  591. }
  592. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  593. {
  594. item.SetImage(new ItemImageInfo
  595. {
  596. Path = info.ImageUrl,
  597. Type = ImageType.Primary,
  598. IsPlaceholder = true
  599. }, 0);
  600. }
  601. }
  602. if (isNew)
  603. {
  604. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  605. }
  606. else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
  607. {
  608. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  609. }
  610. else
  611. {
  612. // Increment this whenver some internal change deems it necessary
  613. var etag = info.Etag + "4";
  614. if (!string.Equals(etag, item.ExternalEtag, StringComparison.OrdinalIgnoreCase))
  615. {
  616. item.ExternalEtag = etag;
  617. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  618. }
  619. }
  620. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem));
  621. return item;
  622. }
  623. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  624. {
  625. var isNew = false;
  626. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  627. var item = _itemRepo.RetrieveItem(id);
  628. if (item == null)
  629. {
  630. if (info.ChannelType == ChannelType.TV)
  631. {
  632. item = new LiveTvVideoRecording
  633. {
  634. Name = info.Name,
  635. Id = id,
  636. DateCreated = DateTime.UtcNow,
  637. DateModified = DateTime.UtcNow,
  638. VideoType = VideoType.VideoFile
  639. };
  640. }
  641. else
  642. {
  643. item = new LiveTvAudioRecording
  644. {
  645. Name = info.Name,
  646. Id = id,
  647. DateCreated = DateTime.UtcNow,
  648. DateModified = DateTime.UtcNow
  649. };
  650. }
  651. isNew = true;
  652. }
  653. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  654. item.CommunityRating = info.CommunityRating;
  655. item.OfficialRating = info.OfficialRating;
  656. item.Overview = info.Overview;
  657. item.EndDate = info.EndDate;
  658. item.Genres = info.Genres;
  659. item.PremiereDate = info.OriginalAirDate;
  660. var recording = (ILiveTvRecording)item;
  661. recording.ExternalId = info.Id;
  662. var dataChanged = false;
  663. recording.Audio = info.Audio;
  664. recording.EndDate = info.EndDate;
  665. recording.EpisodeTitle = info.EpisodeTitle;
  666. recording.IsHD = info.IsHD;
  667. recording.IsKids = info.IsKids;
  668. recording.IsLive = info.IsLive;
  669. recording.IsMovie = info.IsMovie;
  670. recording.IsNews = info.IsNews;
  671. recording.IsPremiere = info.IsPremiere;
  672. recording.IsRepeat = info.IsRepeat;
  673. recording.IsSports = info.IsSports;
  674. recording.SeriesTimerId = info.SeriesTimerId;
  675. recording.StartDate = info.StartDate;
  676. if (!dataChanged)
  677. {
  678. dataChanged = recording.IsSeries != info.IsSeries;
  679. }
  680. recording.IsSeries = info.IsSeries;
  681. if (!item.ParentId.Equals(parentFolderId))
  682. {
  683. dataChanged = true;
  684. }
  685. item.ParentId = parentFolderId;
  686. if (!item.HasImage(ImageType.Primary))
  687. {
  688. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  689. {
  690. item.SetImage(new ItemImageInfo
  691. {
  692. Path = info.ImagePath,
  693. Type = ImageType.Primary,
  694. IsPlaceholder = true
  695. }, 0);
  696. }
  697. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  698. {
  699. item.SetImage(new ItemImageInfo
  700. {
  701. Path = info.ImageUrl,
  702. Type = ImageType.Primary,
  703. IsPlaceholder = true
  704. }, 0);
  705. }
  706. }
  707. var statusChanged = info.Status != recording.Status;
  708. recording.Status = info.Status;
  709. recording.ServiceName = serviceName;
  710. if (!string.IsNullOrEmpty(info.Path))
  711. {
  712. if (!dataChanged)
  713. {
  714. dataChanged = !string.Equals(item.Path, info.Path);
  715. }
  716. var fileInfo = _fileSystem.GetFileInfo(info.Path);
  717. recording.DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo);
  718. recording.DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo);
  719. item.Path = info.Path;
  720. }
  721. else if (!string.IsNullOrEmpty(info.Url))
  722. {
  723. if (!dataChanged)
  724. {
  725. dataChanged = !string.Equals(item.Path, info.Url);
  726. }
  727. item.Path = info.Url;
  728. }
  729. var metadataRefreshMode = MetadataRefreshMode.Default;
  730. if (isNew)
  731. {
  732. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  733. }
  734. else if (dataChanged || info.DateLastUpdated > recording.DateLastSaved || statusChanged)
  735. {
  736. metadataRefreshMode = MetadataRefreshMode.FullRefresh;
  737. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  738. }
  739. if (info.Status != RecordingStatus.InProgress)
  740. {
  741. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  742. {
  743. MetadataRefreshMode = metadataRefreshMode
  744. });
  745. }
  746. return item.Id;
  747. }
  748. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  749. {
  750. var program = GetInternalProgram(id);
  751. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  752. var list = new List<Tuple<BaseItemDto, string, string>>();
  753. list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ServiceName, program.ExternalId));
  754. await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
  755. return dto;
  756. }
  757. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  758. {
  759. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  760. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  761. if (query.SortBy.Length == 0)
  762. {
  763. // Unless something else was specified, order by start date to take advantage of a specialized index
  764. query.SortBy = new[] { ItemSortBy.StartDate };
  765. }
  766. var internalQuery = new InternalItemsQuery(user)
  767. {
  768. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  769. MinEndDate = query.MinEndDate,
  770. MinStartDate = query.MinStartDate,
  771. MaxEndDate = query.MaxEndDate,
  772. MaxStartDate = query.MaxStartDate,
  773. ChannelIds = query.ChannelIds,
  774. IsMovie = query.IsMovie,
  775. IsSports = query.IsSports,
  776. IsKids = query.IsKids,
  777. Genres = query.Genres,
  778. StartIndex = query.StartIndex,
  779. Limit = query.Limit,
  780. SortBy = query.SortBy,
  781. SortOrder = query.SortOrder ?? SortOrder.Ascending,
  782. EnableTotalRecordCount = query.EnableTotalRecordCount,
  783. TopParentIds = new[] { topFolder.Id.ToString("N") }
  784. };
  785. if (query.HasAired.HasValue)
  786. {
  787. if (query.HasAired.Value)
  788. {
  789. internalQuery.MaxEndDate = DateTime.UtcNow;
  790. }
  791. else
  792. {
  793. internalQuery.MinEndDate = DateTime.UtcNow;
  794. }
  795. }
  796. var queryResult = _libraryManager.QueryItems(internalQuery);
  797. var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ConfigureAwait(false)).ToArray();
  798. var result = new QueryResult<BaseItemDto>
  799. {
  800. Items = returnArray,
  801. TotalRecordCount = queryResult.TotalRecordCount
  802. };
  803. return result;
  804. }
  805. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  806. {
  807. var user = _userManager.GetUserById(query.UserId);
  808. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  809. var internalQuery = new InternalItemsQuery(user)
  810. {
  811. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  812. IsAiring = query.IsAiring,
  813. IsMovie = query.IsMovie,
  814. IsSports = query.IsSports,
  815. IsKids = query.IsKids,
  816. EnableTotalRecordCount = query.EnableTotalRecordCount,
  817. SortBy = new[] { ItemSortBy.StartDate },
  818. TopParentIds = new[] { topFolder.Id.ToString("N") }
  819. };
  820. if (query.Limit.HasValue)
  821. {
  822. internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
  823. }
  824. if (query.HasAired.HasValue)
  825. {
  826. if (query.HasAired.Value)
  827. {
  828. internalQuery.MaxEndDate = DateTime.UtcNow;
  829. }
  830. else
  831. {
  832. internalQuery.MinEndDate = DateTime.UtcNow;
  833. }
  834. }
  835. IEnumerable<LiveTvProgram> programs = _libraryManager.QueryItems(internalQuery).Items.Cast<LiveTvProgram>();
  836. var programList = programs.ToList();
  837. var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false);
  838. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  839. .ThenByDescending(i => GetRecommendationScore(i, user.Id, factorChannelWatchCount))
  840. .ThenBy(i => i.StartDate);
  841. if (query.Limit.HasValue)
  842. {
  843. programs = programs.Take(query.Limit.Value);
  844. }
  845. programList = programs.ToList();
  846. var returnArray = programList.ToArray();
  847. var result = new QueryResult<LiveTvProgram>
  848. {
  849. Items = returnArray,
  850. TotalRecordCount = returnArray.Length
  851. };
  852. return result;
  853. }
  854. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  855. {
  856. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  857. var user = _userManager.GetUserById(query.UserId);
  858. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
  859. var result = new QueryResult<BaseItemDto>
  860. {
  861. Items = returnArray,
  862. TotalRecordCount = internalResult.TotalRecordCount
  863. };
  864. return result;
  865. }
  866. private int GetRecommendationScore(LiveTvProgram program, Guid userId, bool factorChannelWatchCount)
  867. {
  868. var score = 0;
  869. if (program.IsLive)
  870. {
  871. score++;
  872. }
  873. if (program.IsSeries && !program.IsRepeat)
  874. {
  875. score++;
  876. }
  877. var channel = GetInternalChannel(program.ChannelId);
  878. var channelUserdata = _userDataManager.GetUserData(userId, channel);
  879. if (channelUserdata.Likes ?? false)
  880. {
  881. score += 2;
  882. }
  883. else if (!(channelUserdata.Likes ?? true))
  884. {
  885. score -= 2;
  886. }
  887. if (channelUserdata.IsFavorite)
  888. {
  889. score += 3;
  890. }
  891. if (factorChannelWatchCount)
  892. {
  893. score += channelUserdata.PlayCount;
  894. }
  895. return score;
  896. }
  897. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
  898. {
  899. var timers = new Dictionary<string, List<TimerInfo>>();
  900. foreach (var programTuple in programs)
  901. {
  902. var program = programTuple.Item1;
  903. var serviceName = programTuple.Item2;
  904. var externalProgramId = programTuple.Item3;
  905. if (string.IsNullOrWhiteSpace(serviceName))
  906. {
  907. continue;
  908. }
  909. List<TimerInfo> timerList;
  910. if (!timers.TryGetValue(serviceName, out timerList))
  911. {
  912. try
  913. {
  914. var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  915. timers[serviceName] = timerList = tempTimers.ToList();
  916. }
  917. catch (Exception ex)
  918. {
  919. _logger.ErrorException("Error getting timer infos", ex);
  920. timers[serviceName] = timerList = new List<TimerInfo>();
  921. }
  922. }
  923. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  924. if (timer != null)
  925. {
  926. program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id)
  927. .ToString("N");
  928. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  929. {
  930. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
  931. .ToString("N");
  932. }
  933. }
  934. }
  935. }
  936. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  937. {
  938. return RefreshChannelsInternal(progress, cancellationToken);
  939. }
  940. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  941. {
  942. EmbyTV.EmbyTV.Current.CreateRecordingFolders();
  943. var numComplete = 0;
  944. double progressPerService = _services.Count == 0
  945. ? 0
  946. : 1 / _services.Count;
  947. var newChannelIdList = new List<Guid>();
  948. var newProgramIdList = new List<Guid>();
  949. foreach (var service in _services)
  950. {
  951. cancellationToken.ThrowIfCancellationRequested();
  952. _logger.Debug("Refreshing guide from {0}", service.Name);
  953. try
  954. {
  955. var innerProgress = new ActionableProgress<double>();
  956. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  957. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  958. newChannelIdList.AddRange(idList.Item1);
  959. newProgramIdList.AddRange(idList.Item2);
  960. }
  961. catch (OperationCanceledException)
  962. {
  963. throw;
  964. }
  965. catch (Exception ex)
  966. {
  967. _logger.ErrorException("Error refreshing channels for service", ex);
  968. }
  969. numComplete++;
  970. double percent = numComplete;
  971. percent /= _services.Count;
  972. progress.Report(100 * percent);
  973. }
  974. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  975. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  976. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  977. if (coreService != null)
  978. {
  979. await coreService.RefreshSeriesTimers(cancellationToken, new Progress<double>()).ConfigureAwait(false);
  980. }
  981. // Load these now which will prefetch metadata
  982. var dtoOptions = new DtoOptions();
  983. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  984. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  985. progress.Report(100);
  986. }
  987. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  988. {
  989. progress.Report(10);
  990. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  991. var allChannelsList = allChannels.ToList();
  992. var list = new List<LiveTvChannel>();
  993. var numComplete = 0;
  994. var parentFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  995. var parentFolderId = parentFolder.Id;
  996. foreach (var channelInfo in allChannelsList)
  997. {
  998. cancellationToken.ThrowIfCancellationRequested();
  999. try
  1000. {
  1001. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolderId, cancellationToken).ConfigureAwait(false);
  1002. list.Add(item);
  1003. }
  1004. catch (OperationCanceledException)
  1005. {
  1006. throw;
  1007. }
  1008. catch (Exception ex)
  1009. {
  1010. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  1011. }
  1012. numComplete++;
  1013. double percent = numComplete;
  1014. percent /= allChannelsList.Count;
  1015. progress.Report(5 * percent + 10);
  1016. }
  1017. progress.Report(15);
  1018. numComplete = 0;
  1019. var programs = new List<Guid>();
  1020. var channels = new List<Guid>();
  1021. var guideDays = GetGuideDays(list.Count);
  1022. _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
  1023. cancellationToken.ThrowIfCancellationRequested();
  1024. foreach (var currentChannel in list)
  1025. {
  1026. channels.Add(currentChannel.Id);
  1027. cancellationToken.ThrowIfCancellationRequested();
  1028. try
  1029. {
  1030. var start = DateTime.UtcNow.AddHours(-1);
  1031. var end = start.AddDays(guideDays);
  1032. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  1033. foreach (var program in channelPrograms)
  1034. {
  1035. var programItem = await GetProgram(program, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  1036. programs.Add(programItem.Id);
  1037. }
  1038. }
  1039. catch (OperationCanceledException)
  1040. {
  1041. throw;
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  1046. }
  1047. numComplete++;
  1048. double percent = numComplete;
  1049. percent /= allChannelsList.Count;
  1050. progress.Report(80 * percent + 10);
  1051. }
  1052. progress.Report(100);
  1053. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1054. }
  1055. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1056. {
  1057. var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
  1058. {
  1059. IncludeItemTypes = validTypes
  1060. }).ToList();
  1061. var numComplete = 0;
  1062. foreach (var itemId in list)
  1063. {
  1064. cancellationToken.ThrowIfCancellationRequested();
  1065. if (itemId == Guid.Empty)
  1066. {
  1067. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1068. continue;
  1069. }
  1070. if (!currentIdList.Contains(itemId))
  1071. {
  1072. var item = _libraryManager.GetItemById(itemId);
  1073. if (item != null)
  1074. {
  1075. await _libraryManager.DeleteItem(item, new DeleteOptions
  1076. {
  1077. DeleteFileLocation = false
  1078. }).ConfigureAwait(false);
  1079. }
  1080. }
  1081. numComplete++;
  1082. double percent = numComplete;
  1083. percent /= list.Count;
  1084. progress.Report(100 * percent);
  1085. }
  1086. }
  1087. private const int MaxGuideDays = 14;
  1088. private double GetGuideDays(int channelCount)
  1089. {
  1090. var config = GetConfiguration();
  1091. if (config.GuideDays.HasValue)
  1092. {
  1093. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1094. }
  1095. var programsPerDay = channelCount * 48;
  1096. const int maxPrograms = 24000;
  1097. var days = Math.Round((double)maxPrograms / programsPerDay);
  1098. return Math.Max(3, Math.Min(days, MaxGuideDays));
  1099. }
  1100. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  1101. {
  1102. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  1103. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  1104. }
  1105. private DateTime _lastRecordingRefreshTime;
  1106. private async Task RefreshRecordings(CancellationToken cancellationToken)
  1107. {
  1108. const int cacheMinutes = 5;
  1109. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1110. {
  1111. return;
  1112. }
  1113. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1114. try
  1115. {
  1116. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1117. {
  1118. return;
  1119. }
  1120. var tasks = _services.Select(async i =>
  1121. {
  1122. try
  1123. {
  1124. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  1125. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  1126. }
  1127. catch (Exception ex)
  1128. {
  1129. _logger.ErrorException("Error getting recordings", ex);
  1130. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  1131. }
  1132. });
  1133. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1134. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1135. var parentFolderId = folder.Id;
  1136. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, parentFolderId, cancellationToken));
  1137. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  1138. await CleanDatabaseInternal(idList.ToList(), new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  1139. _lastRecordingRefreshTime = DateTime.UtcNow;
  1140. }
  1141. finally
  1142. {
  1143. _refreshRecordingsLock.Release();
  1144. }
  1145. }
  1146. private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, User user)
  1147. {
  1148. if (user == null || (query.IsInProgress ?? false))
  1149. {
  1150. return new QueryResult<BaseItem>();
  1151. }
  1152. var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
  1153. .SelectMany(i => i.Locations)
  1154. .Distinct(StringComparer.OrdinalIgnoreCase)
  1155. .Select(i => _libraryManager.FindByPath(i, true))
  1156. .Where(i => i != null)
  1157. .Where(i => i.IsVisibleStandalone(user))
  1158. .ToList();
  1159. if (folders.Count == 0)
  1160. {
  1161. return new QueryResult<BaseItem>();
  1162. }
  1163. return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  1164. {
  1165. MediaTypes = new[] { MediaType.Video },
  1166. Recursive = true,
  1167. AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
  1168. IsFolder = false,
  1169. ExcludeLocationTypes = new[] { LocationType.Virtual },
  1170. Limit = Math.Min(200, query.Limit ?? int.MaxValue),
  1171. SortBy = new[] { ItemSortBy.DateCreated },
  1172. SortOrder = SortOrder.Descending,
  1173. EnableTotalRecordCount = query.EnableTotalRecordCount
  1174. });
  1175. }
  1176. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1177. {
  1178. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1179. if (user != null && !IsLiveTvEnabled(user))
  1180. {
  1181. return new QueryResult<BaseItem>();
  1182. }
  1183. if (_services.Count == 1)
  1184. {
  1185. return GetEmbyRecordings(query, user);
  1186. }
  1187. await RefreshRecordings(cancellationToken).ConfigureAwait(false);
  1188. var internalQuery = new InternalItemsQuery(user)
  1189. {
  1190. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }
  1191. };
  1192. if (!string.IsNullOrEmpty(query.ChannelId))
  1193. {
  1194. internalQuery.ChannelIds = new[] { query.ChannelId };
  1195. }
  1196. var queryResult = _libraryManager.GetItemList(internalQuery);
  1197. IEnumerable<ILiveTvRecording> recordings = queryResult.Cast<ILiveTvRecording>();
  1198. if (!string.IsNullOrWhiteSpace(query.Id))
  1199. {
  1200. var guid = new Guid(query.Id);
  1201. recordings = recordings
  1202. .Where(i => i.Id == guid);
  1203. }
  1204. if (!string.IsNullOrWhiteSpace(query.GroupId))
  1205. {
  1206. var guid = new Guid(query.GroupId);
  1207. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1208. }
  1209. if (query.IsInProgress.HasValue)
  1210. {
  1211. var val = query.IsInProgress.Value;
  1212. recordings = recordings.Where(i => i.Status == RecordingStatus.InProgress == val);
  1213. }
  1214. if (query.Status.HasValue)
  1215. {
  1216. var val = query.Status.Value;
  1217. recordings = recordings.Where(i => i.Status == val);
  1218. }
  1219. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1220. {
  1221. var guid = new Guid(query.SeriesTimerId);
  1222. recordings = recordings
  1223. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1224. }
  1225. recordings = recordings.OrderByDescending(i => i.StartDate);
  1226. var entityList = recordings.ToList();
  1227. IEnumerable<ILiveTvRecording> entities = entityList;
  1228. if (query.StartIndex.HasValue)
  1229. {
  1230. entities = entities.Skip(query.StartIndex.Value);
  1231. }
  1232. if (query.Limit.HasValue)
  1233. {
  1234. entities = entities.Take(query.Limit.Value);
  1235. }
  1236. return new QueryResult<BaseItem>
  1237. {
  1238. Items = entities.Cast<BaseItem>().ToArray(),
  1239. TotalRecordCount = entityList.Count
  1240. };
  1241. }
  1242. public async Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, List<ItemFields> fields, User user = null)
  1243. {
  1244. var recordingTuples = new List<Tuple<BaseItemDto, string, string>>();
  1245. foreach (var tuple in tuples)
  1246. {
  1247. var program = (LiveTvProgram)tuple.Item1;
  1248. var dto = tuple.Item2;
  1249. dto.StartDate = program.StartDate;
  1250. dto.EpisodeTitle = program.EpisodeTitle;
  1251. if (program.IsRepeat)
  1252. {
  1253. dto.IsRepeat = program.IsRepeat;
  1254. }
  1255. if (program.IsMovie)
  1256. {
  1257. dto.IsMovie = program.IsMovie;
  1258. }
  1259. if (program.IsSeries)
  1260. {
  1261. dto.IsSeries = program.IsSeries;
  1262. }
  1263. if (program.IsSports)
  1264. {
  1265. dto.IsSports = program.IsSports;
  1266. }
  1267. if (program.IsLive)
  1268. {
  1269. dto.IsLive = program.IsLive;
  1270. }
  1271. if (program.IsNews)
  1272. {
  1273. dto.IsNews = program.IsNews;
  1274. }
  1275. if (program.IsKids)
  1276. {
  1277. dto.IsKids = program.IsKids;
  1278. }
  1279. if (program.IsPremiere)
  1280. {
  1281. dto.IsPremiere = program.IsPremiere;
  1282. }
  1283. if (fields.Contains(ItemFields.ChannelInfo))
  1284. {
  1285. var channel = GetInternalChannel(program.ChannelId);
  1286. if (channel != null)
  1287. {
  1288. dto.ChannelName = channel.Name;
  1289. dto.MediaType = channel.MediaType;
  1290. dto.ChannelNumber = channel.Number;
  1291. if (channel.HasImage(ImageType.Primary))
  1292. {
  1293. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1294. }
  1295. }
  1296. }
  1297. var service = GetService(program);
  1298. var serviceName = service == null ? null : service.Name;
  1299. if (fields.Contains(ItemFields.ServiceName))
  1300. {
  1301. dto.ServiceName = serviceName;
  1302. }
  1303. recordingTuples.Add(new Tuple<BaseItemDto, string, string>(dto, serviceName, program.ExternalId));
  1304. }
  1305. await AddRecordingInfo(recordingTuples, CancellationToken.None).ConfigureAwait(false);
  1306. }
  1307. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1308. {
  1309. var recording = (ILiveTvRecording)item;
  1310. var service = GetService(recording);
  1311. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1312. var info = recording;
  1313. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1314. ? null
  1315. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1316. dto.StartDate = info.StartDate;
  1317. dto.RecordingStatus = info.Status;
  1318. dto.IsRepeat = info.IsRepeat;
  1319. dto.EpisodeTitle = info.EpisodeTitle;
  1320. dto.IsMovie = info.IsMovie;
  1321. dto.IsSeries = info.IsSeries;
  1322. dto.IsSports = info.IsSports;
  1323. dto.IsLive = info.IsLive;
  1324. dto.IsNews = info.IsNews;
  1325. dto.IsKids = info.IsKids;
  1326. dto.IsPremiere = info.IsPremiere;
  1327. dto.CanDelete = user == null
  1328. ? recording.CanDelete()
  1329. : recording.CanDelete(user);
  1330. if (dto.MediaSources == null)
  1331. {
  1332. dto.MediaSources = recording.GetMediaSources(true).ToList();
  1333. }
  1334. if (dto.MediaStreams == null)
  1335. {
  1336. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToList();
  1337. }
  1338. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1339. {
  1340. var now = DateTime.UtcNow.Ticks;
  1341. var start = info.StartDate.Ticks;
  1342. var end = info.EndDate.Value.Ticks;
  1343. var pct = now - start;
  1344. pct /= end;
  1345. pct *= 100;
  1346. dto.CompletionPercentage = pct;
  1347. }
  1348. if (channel != null)
  1349. {
  1350. dto.ChannelName = channel.Name;
  1351. if (channel.HasImage(ImageType.Primary))
  1352. {
  1353. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1354. }
  1355. }
  1356. }
  1357. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1358. {
  1359. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1360. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1361. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
  1362. return new QueryResult<BaseItemDto>
  1363. {
  1364. Items = returnArray,
  1365. TotalRecordCount = internalResult.TotalRecordCount
  1366. };
  1367. }
  1368. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1369. {
  1370. var tasks = _services.Select(async i =>
  1371. {
  1372. try
  1373. {
  1374. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1375. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1376. }
  1377. catch (Exception ex)
  1378. {
  1379. _logger.ErrorException("Error getting recordings", ex);
  1380. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1381. }
  1382. });
  1383. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1384. var timers = results.SelectMany(i => i.ToList());
  1385. if (query.IsActive.HasValue)
  1386. {
  1387. if (query.IsActive.Value)
  1388. {
  1389. timers = timers.Where(i => i.Item1.Status == RecordingStatus.InProgress);
  1390. }
  1391. else
  1392. {
  1393. timers = timers.Where(i => i.Item1.Status != RecordingStatus.InProgress);
  1394. }
  1395. }
  1396. if (!string.IsNullOrEmpty(query.ChannelId))
  1397. {
  1398. var guid = new Guid(query.ChannelId);
  1399. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1400. }
  1401. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1402. {
  1403. var guid = new Guid(query.SeriesTimerId);
  1404. timers = timers
  1405. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1406. }
  1407. var returnList = new List<TimerInfoDto>();
  1408. foreach (var i in timers)
  1409. {
  1410. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1411. null :
  1412. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1413. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1414. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1415. }
  1416. var returnArray = returnList
  1417. .OrderBy(i => i.StartDate)
  1418. .ToArray();
  1419. return new QueryResult<TimerInfoDto>
  1420. {
  1421. Items = returnArray,
  1422. TotalRecordCount = returnArray.Length
  1423. };
  1424. }
  1425. public Task OnRecordingFileDeleted(BaseItem recording)
  1426. {
  1427. var service = GetService(recording);
  1428. if (service is EmbyTV.EmbyTV)
  1429. {
  1430. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  1431. return service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None);
  1432. }
  1433. return Task.FromResult(true);
  1434. }
  1435. public async Task DeleteRecording(string recordingId)
  1436. {
  1437. var recording = await GetInternalRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1438. if (recording == null)
  1439. {
  1440. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1441. }
  1442. await DeleteRecording((BaseItem)recording).ConfigureAwait(false);
  1443. }
  1444. public async Task DeleteRecording(BaseItem recording)
  1445. {
  1446. var service = GetService(recording.ServiceName);
  1447. try
  1448. {
  1449. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1450. }
  1451. catch (ResourceNotFoundException)
  1452. {
  1453. }
  1454. _lastRecordingRefreshTime = DateTime.MinValue;
  1455. // This is the responsibility of the live tv service
  1456. await _libraryManager.DeleteItem((BaseItem)recording, new DeleteOptions
  1457. {
  1458. DeleteFileLocation = false
  1459. }).ConfigureAwait(false);
  1460. _lastRecordingRefreshTime = DateTime.MinValue;
  1461. }
  1462. public async Task CancelTimer(string id)
  1463. {
  1464. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1465. if (timer == null)
  1466. {
  1467. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1468. }
  1469. var service = GetService(timer.ServiceName);
  1470. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1471. _lastRecordingRefreshTime = DateTime.MinValue;
  1472. EventHelper.QueueEventIfNotNull(TimerCancelled, this, new GenericEventArgs<TimerEventInfo>
  1473. {
  1474. Argument = new TimerEventInfo
  1475. {
  1476. Id = id
  1477. }
  1478. }, _logger);
  1479. }
  1480. public async Task CancelSeriesTimer(string id)
  1481. {
  1482. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1483. if (timer == null)
  1484. {
  1485. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1486. }
  1487. var service = GetService(timer.ServiceName);
  1488. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1489. _lastRecordingRefreshTime = DateTime.MinValue;
  1490. EventHelper.QueueEventIfNotNull(SeriesTimerCancelled, this, new GenericEventArgs<TimerEventInfo>
  1491. {
  1492. Argument = new TimerEventInfo
  1493. {
  1494. Id = id
  1495. }
  1496. }, _logger);
  1497. }
  1498. public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1499. {
  1500. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  1501. if (item == null)
  1502. {
  1503. return null;
  1504. }
  1505. return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
  1506. }
  1507. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1508. {
  1509. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1510. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1511. }
  1512. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1513. {
  1514. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1515. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1516. }
  1517. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1518. {
  1519. var tasks = _services.Select(async i =>
  1520. {
  1521. try
  1522. {
  1523. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1524. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1525. }
  1526. catch (Exception ex)
  1527. {
  1528. _logger.ErrorException("Error getting recordings", ex);
  1529. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1530. }
  1531. });
  1532. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1533. var timers = results.SelectMany(i => i.ToList());
  1534. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1535. {
  1536. timers = query.SortOrder == SortOrder.Descending ?
  1537. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1538. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1539. }
  1540. else
  1541. {
  1542. timers = query.SortOrder == SortOrder.Descending ?
  1543. timers.OrderByStringDescending(i => i.Item1.Name) :
  1544. timers.OrderByString(i => i.Item1.Name);
  1545. }
  1546. var returnArray = timers
  1547. .Select(i =>
  1548. {
  1549. string channelName = null;
  1550. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1551. {
  1552. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1553. var channel = GetInternalChannel(internalChannelId);
  1554. channelName = channel == null ? null : channel.Name;
  1555. }
  1556. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1557. })
  1558. .ToArray();
  1559. return new QueryResult<SeriesTimerInfoDto>
  1560. {
  1561. Items = returnArray,
  1562. TotalRecordCount = returnArray.Length
  1563. };
  1564. }
  1565. public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
  1566. {
  1567. var now = DateTime.UtcNow;
  1568. var channelIds = tuples.Select(i => i.Item2.Id.ToString("N")).Distinct().ToArray();
  1569. var programs = _libraryManager.GetItemList(new InternalItemsQuery(user)
  1570. {
  1571. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1572. ChannelIds = channelIds,
  1573. MaxStartDate = now,
  1574. MinEndDate = now,
  1575. Limit = channelIds.Length,
  1576. SortBy = new[] { "StartDate" },
  1577. TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Result.Id.ToString("N") }
  1578. }).ToList();
  1579. foreach (var tuple in tuples)
  1580. {
  1581. var dto = tuple.Item1;
  1582. var channel = tuple.Item2;
  1583. dto.Number = channel.Number;
  1584. dto.ChannelNumber = channel.Number;
  1585. dto.ChannelType = channel.ChannelType;
  1586. dto.ServiceName = GetService(channel).Name;
  1587. dto.MediaSources = channel.GetMediaSources(true).ToList();
  1588. var channelIdString = channel.Id.ToString("N");
  1589. var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString));
  1590. if (currentProgram != null)
  1591. {
  1592. dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
  1593. }
  1594. }
  1595. }
  1596. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1597. {
  1598. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1599. GetService(program) :
  1600. _services.FirstOrDefault();
  1601. ProgramInfo programInfo = null;
  1602. if (program != null)
  1603. {
  1604. var channel = GetInternalChannel(program.ChannelId);
  1605. programInfo = new ProgramInfo
  1606. {
  1607. Audio = program.Audio,
  1608. ChannelId = channel.ExternalId,
  1609. CommunityRating = program.CommunityRating,
  1610. EndDate = program.EndDate ?? DateTime.MinValue,
  1611. EpisodeTitle = program.EpisodeTitle,
  1612. Genres = program.Genres,
  1613. Id = program.ExternalId,
  1614. IsHD = program.IsHD,
  1615. IsKids = program.IsKids,
  1616. IsLive = program.IsLive,
  1617. IsMovie = program.IsMovie,
  1618. IsNews = program.IsNews,
  1619. IsPremiere = program.IsPremiere,
  1620. IsRepeat = program.IsRepeat,
  1621. IsSeries = program.IsSeries,
  1622. IsSports = program.IsSports,
  1623. OriginalAirDate = program.PremiereDate,
  1624. Overview = program.Overview,
  1625. StartDate = program.StartDate,
  1626. //ImagePath = program.ExternalImagePath,
  1627. Name = program.Name,
  1628. OfficialRating = program.OfficialRating
  1629. };
  1630. }
  1631. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1632. info.Id = null;
  1633. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1634. }
  1635. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1636. {
  1637. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1638. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1639. return obj;
  1640. }
  1641. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1642. {
  1643. var program = GetInternalProgram(programId);
  1644. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1645. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1646. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1647. info.Days = defaults.Item1.Days;
  1648. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1649. info.Name = program.Name;
  1650. info.ChannelId = programDto.ChannelId;
  1651. info.ChannelName = programDto.ChannelName;
  1652. info.StartDate = program.StartDate;
  1653. info.Name = program.Name;
  1654. info.Overview = program.Overview;
  1655. info.ProgramId = programDto.Id;
  1656. info.ExternalProgramId = program.ExternalId;
  1657. if (program.EndDate.HasValue)
  1658. {
  1659. info.EndDate = program.EndDate.Value;
  1660. }
  1661. return info;
  1662. }
  1663. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1664. {
  1665. var service = GetService(timer.ServiceName);
  1666. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1667. // Set priority from default values
  1668. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1669. info.Priority = defaultValues.Priority;
  1670. string newTimerId = null;
  1671. var supportsNewTimerIds = service as ISupportsNewTimerIds;
  1672. if (supportsNewTimerIds != null)
  1673. {
  1674. newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false);
  1675. newTimerId = _tvDtoService.GetInternalTimerId(timer.ServiceName, newTimerId).ToString("N");
  1676. }
  1677. else
  1678. {
  1679. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1680. }
  1681. _lastRecordingRefreshTime = DateTime.MinValue;
  1682. _logger.Info("New recording scheduled");
  1683. EventHelper.QueueEventIfNotNull(TimerCreated, this, new GenericEventArgs<TimerEventInfo>
  1684. {
  1685. Argument = new TimerEventInfo
  1686. {
  1687. ProgramId = _tvDtoService.GetInternalProgramId(timer.ServiceName, info.ProgramId).ToString("N"),
  1688. Id = newTimerId
  1689. }
  1690. }, _logger);
  1691. }
  1692. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1693. {
  1694. var service = GetService(timer.ServiceName);
  1695. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1696. // Set priority from default values
  1697. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1698. info.Priority = defaultValues.Priority;
  1699. string newTimerId = null;
  1700. var supportsNewTimerIds = service as ISupportsNewTimerIds;
  1701. if (supportsNewTimerIds != null)
  1702. {
  1703. newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
  1704. newTimerId = _tvDtoService.GetInternalSeriesTimerId(timer.ServiceName, newTimerId).ToString("N");
  1705. }
  1706. else
  1707. {
  1708. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1709. }
  1710. _lastRecordingRefreshTime = DateTime.MinValue;
  1711. EventHelper.QueueEventIfNotNull(SeriesTimerCreated, this, new GenericEventArgs<TimerEventInfo>
  1712. {
  1713. Argument = new TimerEventInfo
  1714. {
  1715. ProgramId = _tvDtoService.GetInternalProgramId(timer.ServiceName, info.ProgramId).ToString("N"),
  1716. Id = newTimerId
  1717. }
  1718. }, _logger);
  1719. }
  1720. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1721. {
  1722. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1723. var service = GetService(timer.ServiceName);
  1724. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1725. _lastRecordingRefreshTime = DateTime.MinValue;
  1726. }
  1727. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1728. {
  1729. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1730. var service = GetService(timer.ServiceName);
  1731. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1732. _lastRecordingRefreshTime = DateTime.MinValue;
  1733. }
  1734. private IEnumerable<string> GetRecordingGroupNames(ILiveTvRecording recording)
  1735. {
  1736. var list = new List<string>();
  1737. if (recording.IsSeries)
  1738. {
  1739. list.Add(recording.Name);
  1740. }
  1741. if (recording.IsKids)
  1742. {
  1743. list.Add("Kids");
  1744. }
  1745. if (recording.IsMovie)
  1746. {
  1747. list.Add("Movies");
  1748. }
  1749. if (recording.IsNews)
  1750. {
  1751. list.Add("News");
  1752. }
  1753. if (recording.IsSports)
  1754. {
  1755. list.Add("Sports");
  1756. }
  1757. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1758. {
  1759. list.Add("Others");
  1760. }
  1761. return list;
  1762. }
  1763. private List<Guid> GetRecordingGroupIds(ILiveTvRecording recording)
  1764. {
  1765. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1766. .GetMD5())
  1767. .ToList();
  1768. }
  1769. public async Task<QueryResult<BaseItemDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1770. {
  1771. var recordingResult = await GetInternalRecordings(new RecordingQuery
  1772. {
  1773. UserId = query.UserId
  1774. }, cancellationToken).ConfigureAwait(false);
  1775. var recordings = recordingResult.Items.OfType<ILiveTvRecording>().ToList();
  1776. var groups = new List<BaseItemDto>();
  1777. var series = recordings
  1778. .Where(i => i.IsSeries)
  1779. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1780. .ToList();
  1781. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  1782. {
  1783. Name = i.Key,
  1784. RecordingCount = i.Count()
  1785. }));
  1786. groups.Add(new BaseItemDto
  1787. {
  1788. Name = "Kids",
  1789. RecordingCount = recordings.Count(i => i.IsKids)
  1790. });
  1791. groups.Add(new BaseItemDto
  1792. {
  1793. Name = "Movies",
  1794. RecordingCount = recordings.Count(i => i.IsMovie)
  1795. });
  1796. groups.Add(new BaseItemDto
  1797. {
  1798. Name = "News",
  1799. RecordingCount = recordings.Count(i => i.IsNews)
  1800. });
  1801. groups.Add(new BaseItemDto
  1802. {
  1803. Name = "Sports",
  1804. RecordingCount = recordings.Count(i => i.IsSports)
  1805. });
  1806. groups.Add(new BaseItemDto
  1807. {
  1808. Name = "Others",
  1809. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1810. });
  1811. groups = groups
  1812. .Where(i => i.RecordingCount > 0)
  1813. .ToList();
  1814. foreach (var group in groups)
  1815. {
  1816. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1817. }
  1818. return new QueryResult<BaseItemDto>
  1819. {
  1820. Items = groups.ToArray(),
  1821. TotalRecordCount = groups.Count
  1822. };
  1823. }
  1824. class LiveStreamData
  1825. {
  1826. internal MediaSourceInfo Info;
  1827. internal string ItemId;
  1828. internal bool IsChannel;
  1829. }
  1830. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1831. {
  1832. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1833. try
  1834. {
  1835. var parts = id.Split(new[] { '_' }, 2);
  1836. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1837. if (service == null)
  1838. {
  1839. throw new ArgumentException("Service not found.");
  1840. }
  1841. id = parts[1];
  1842. LiveStreamData data;
  1843. _openStreams.TryRemove(id, out data);
  1844. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1845. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1846. }
  1847. catch (Exception ex)
  1848. {
  1849. _logger.ErrorException("Error closing live stream", ex);
  1850. throw;
  1851. }
  1852. finally
  1853. {
  1854. _liveStreamSemaphore.Release();
  1855. }
  1856. }
  1857. public GuideInfo GetGuideInfo()
  1858. {
  1859. var startDate = DateTime.UtcNow;
  1860. var endDate = startDate.AddDays(14);
  1861. return new GuideInfo
  1862. {
  1863. StartDate = startDate,
  1864. EndDate = endDate
  1865. };
  1866. }
  1867. /// <summary>
  1868. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1869. /// </summary>
  1870. public void Dispose()
  1871. {
  1872. Dispose(true);
  1873. }
  1874. private readonly object _disposeLock = new object();
  1875. /// <summary>
  1876. /// Releases unmanaged and - optionally - managed resources.
  1877. /// </summary>
  1878. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1879. protected virtual void Dispose(bool dispose)
  1880. {
  1881. if (dispose)
  1882. {
  1883. lock (_disposeLock)
  1884. {
  1885. foreach (var stream in _openStreams.Values.ToList())
  1886. {
  1887. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1888. Task.WaitAll(task);
  1889. }
  1890. _openStreams.Clear();
  1891. }
  1892. }
  1893. }
  1894. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1895. {
  1896. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1897. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1898. }
  1899. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1900. {
  1901. var info = new LiveTvServiceInfo
  1902. {
  1903. Name = service.Name
  1904. };
  1905. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1906. try
  1907. {
  1908. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1909. info.Status = statusInfo.Status;
  1910. info.StatusMessage = statusInfo.StatusMessage;
  1911. info.Version = statusInfo.Version;
  1912. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1913. info.HomePageUrl = service.HomePageUrl;
  1914. info.IsVisible = statusInfo.IsVisible;
  1915. info.Tuners = statusInfo.Tuners.Select(i =>
  1916. {
  1917. string channelName = null;
  1918. if (!string.IsNullOrEmpty(i.ChannelId))
  1919. {
  1920. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1921. var channel = GetInternalChannel(internalChannelId);
  1922. channelName = channel == null ? null : channel.Name;
  1923. }
  1924. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1925. dto.Id = tunerIdPrefix + dto.Id;
  1926. return dto;
  1927. }).ToList();
  1928. }
  1929. catch (Exception ex)
  1930. {
  1931. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1932. info.Status = LiveTvServiceStatus.Unavailable;
  1933. info.StatusMessage = ex.Message;
  1934. }
  1935. return info;
  1936. }
  1937. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1938. {
  1939. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1940. var servicesList = services.ToList();
  1941. var info = new LiveTvInfo
  1942. {
  1943. Services = servicesList.ToList(),
  1944. IsEnabled = servicesList.Count > 0
  1945. };
  1946. info.EnabledUsers = _userManager.Users
  1947. .Where(IsLiveTvEnabled)
  1948. .Select(i => i.Id.ToString("N"))
  1949. .ToList();
  1950. return info;
  1951. }
  1952. private bool IsLiveTvEnabled(User user)
  1953. {
  1954. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Count(i => i.IsEnabled) > 0);
  1955. }
  1956. public IEnumerable<User> GetEnabledUsers()
  1957. {
  1958. return _userManager.Users
  1959. .Where(IsLiveTvEnabled);
  1960. }
  1961. /// <summary>
  1962. /// Resets the tuner.
  1963. /// </summary>
  1964. /// <param name="id">The identifier.</param>
  1965. /// <param name="cancellationToken">The cancellation token.</param>
  1966. /// <returns>Task.</returns>
  1967. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1968. {
  1969. var parts = id.Split(new[] { '_' }, 2);
  1970. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1971. if (service == null)
  1972. {
  1973. throw new ArgumentException("Service not found.");
  1974. }
  1975. return service.ResetTuner(parts[1], cancellationToken);
  1976. }
  1977. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1978. {
  1979. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1980. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1981. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1982. }
  1983. public async Task<Folder> GetInternalLiveTvFolder(CancellationToken cancellationToken)
  1984. {
  1985. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1986. return await _libraryManager.GetNamedView(name, CollectionType.LiveTv, name, cancellationToken).ConfigureAwait(false);
  1987. }
  1988. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info)
  1989. {
  1990. info = (TunerHostInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(TunerHostInfo));
  1991. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1992. if (provider == null)
  1993. {
  1994. throw new ResourceNotFoundException();
  1995. }
  1996. var configurable = provider as IConfigurableTunerHost;
  1997. if (configurable != null)
  1998. {
  1999. await configurable.Validate(info).ConfigureAwait(false);
  2000. }
  2001. var config = GetConfiguration();
  2002. var index = config.TunerHosts.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2003. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2004. {
  2005. info.Id = Guid.NewGuid().ToString("N");
  2006. config.TunerHosts.Add(info);
  2007. }
  2008. else
  2009. {
  2010. config.TunerHosts[index] = info;
  2011. }
  2012. _config.SaveConfiguration("livetv", config);
  2013. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2014. return info;
  2015. }
  2016. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  2017. {
  2018. info = (ListingsProviderInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(ListingsProviderInfo));
  2019. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2020. if (provider == null)
  2021. {
  2022. throw new ResourceNotFoundException();
  2023. }
  2024. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  2025. var config = GetConfiguration();
  2026. var index = config.ListingProviders.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2027. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2028. {
  2029. info.Id = Guid.NewGuid().ToString("N");
  2030. config.ListingProviders.Add(info);
  2031. }
  2032. else
  2033. {
  2034. config.ListingProviders[index] = info;
  2035. }
  2036. _config.SaveConfiguration("livetv", config);
  2037. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2038. return info;
  2039. }
  2040. public void DeleteListingsProvider(string id)
  2041. {
  2042. var config = GetConfiguration();
  2043. config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToList();
  2044. _config.SaveConfiguration("livetv", config);
  2045. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2046. }
  2047. public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
  2048. {
  2049. var config = GetConfiguration();
  2050. var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
  2051. listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
  2052. if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
  2053. {
  2054. var list = listingsProviderInfo.ChannelMappings.ToList();
  2055. list.Add(new NameValuePair
  2056. {
  2057. Name = tunerChannelNumber,
  2058. Value = providerChannelNumber
  2059. });
  2060. listingsProviderInfo.ChannelMappings = list.ToArray();
  2061. }
  2062. _config.SaveConfiguration("livetv", config);
  2063. var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
  2064. .ConfigureAwait(false);
  2065. var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
  2066. .ConfigureAwait(false);
  2067. var mappings = listingsProviderInfo.ChannelMappings.ToList();
  2068. var tunerChannelMappings =
  2069. tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
  2070. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2071. return tunerChannelMappings.First(i => string.Equals(i.Number, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2072. }
  2073. public TunerChannelMapping GetTunerChannelMapping(ChannelInfo channel, List<NameValuePair> mappings, List<ChannelInfo> providerChannels)
  2074. {
  2075. var result = new TunerChannelMapping
  2076. {
  2077. Name = channel.Number + " " + channel.Name,
  2078. Number = channel.Number
  2079. };
  2080. var mapping = mappings.FirstOrDefault(i => string.Equals(i.Name, channel.Number, StringComparison.OrdinalIgnoreCase));
  2081. var providerChannelNumber = channel.Number;
  2082. if (mapping != null)
  2083. {
  2084. providerChannelNumber = mapping.Value;
  2085. }
  2086. var providerChannel = providerChannels.FirstOrDefault(i => string.Equals(i.Number, providerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2087. if (providerChannel != null)
  2088. {
  2089. result.ProviderChannelNumber = providerChannel.Number;
  2090. result.ProviderChannelName = providerChannel.Name;
  2091. }
  2092. return result;
  2093. }
  2094. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  2095. {
  2096. var config = GetConfiguration();
  2097. if (string.IsNullOrWhiteSpace(providerId))
  2098. {
  2099. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  2100. if (provider == null)
  2101. {
  2102. throw new ResourceNotFoundException();
  2103. }
  2104. return provider.GetLineups(null, country, location);
  2105. }
  2106. else
  2107. {
  2108. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  2109. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2110. if (provider == null)
  2111. {
  2112. throw new ResourceNotFoundException();
  2113. }
  2114. return provider.GetLineups(info, country, location);
  2115. }
  2116. }
  2117. public Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature)
  2118. {
  2119. ILiveTvService service;
  2120. if (string.IsNullOrWhiteSpace(programId))
  2121. {
  2122. var channel = GetInternalChannel(channelId);
  2123. service = GetService(channel);
  2124. }
  2125. else
  2126. {
  2127. var program = GetInternalProgram(programId);
  2128. service = GetService(program);
  2129. }
  2130. var hasRegistration = service as IHasRegistrationInfo;
  2131. if (hasRegistration != null)
  2132. {
  2133. return hasRegistration.GetRegistrationInfo(feature);
  2134. }
  2135. return Task.FromResult(new MBRegistrationRecord
  2136. {
  2137. IsValid = true,
  2138. IsRegistered = true
  2139. });
  2140. }
  2141. public List<NameValuePair> GetSatIniMappings()
  2142. {
  2143. var names = GetType().Assembly.GetManifestResourceNames().Where(i => i.IndexOf("SatIp.ini", StringComparison.OrdinalIgnoreCase) != -1).ToList();
  2144. return names.Select(GetSatIniMappings).Where(i => i != null).DistinctBy(i => i.Value.Split('|')[0]).ToList();
  2145. }
  2146. public NameValuePair GetSatIniMappings(string resource)
  2147. {
  2148. using (var stream = GetType().Assembly.GetManifestResourceStream(resource))
  2149. {
  2150. using (var reader = new StreamReader(stream))
  2151. {
  2152. var parser = new StreamIniDataParser();
  2153. IniData data = parser.ReadData(reader);
  2154. var satType1 = data["SATTYPE"]["1"];
  2155. var satType2 = data["SATTYPE"]["2"];
  2156. if (string.IsNullOrWhiteSpace(satType2))
  2157. {
  2158. return null;
  2159. }
  2160. var srch = "SatIp.ini.";
  2161. var filename = Path.GetFileName(resource);
  2162. return new NameValuePair
  2163. {
  2164. Name = satType1 + " " + satType2,
  2165. Value = satType2 + "|" + filename.Substring(filename.IndexOf(srch) + srch.Length)
  2166. };
  2167. }
  2168. }
  2169. }
  2170. public Task<List<ChannelInfo>> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken)
  2171. {
  2172. return new TunerHosts.SatIp.ChannelScan(_logger).Scan(info, cancellationToken);
  2173. }
  2174. public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
  2175. {
  2176. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2177. return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
  2178. }
  2179. public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
  2180. {
  2181. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2182. var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
  2183. return provider.GetChannels(info, cancellationToken);
  2184. }
  2185. }
  2186. }