LiveTvManager.cs 89 KB

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