LiveTvManager.cs 107 KB

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