LiveTvManager.cs 112 KB

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