LiveTvManager.cs 89 KB

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