LiveTvManager.cs 90 KB

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