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