LiveTvManager.cs 108 KB

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