LiveTvManager.cs 103 KB

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