LiveTvManager.cs 90 KB

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