LiveTvManager.cs 87 KB

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