LiveTvManager.cs 86 KB

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