LiveTvManager.cs 91 KB

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