LiveTvManager.cs 88 KB

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