LiveTvManager.cs 111 KB

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