LiveTvManager.cs 110 KB

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