LiveTvManager.cs 91 KB

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