LiveTvManager.cs 91 KB

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