LiveTvManager.cs 116 KB

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