LiveTvManager.cs 112 KB

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