LiveTvManager.cs 111 KB

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