LiveTvManager.cs 111 KB

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