LiveTvManager.cs 84 KB

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