LiveTvManager.cs 90 KB

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