LiveTvManager.cs 83 KB

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