LiveTvManager.cs 84 KB

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